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.
@@ -0,0 +1,845 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Transfers on Node (design/transfer.md, adapters/moadim/TRANSFER.md): the files, the consent, the
3
+ // signalling over the carrier, the direct path (sigelo-transfer, loaded only when a transfer starts)
4
+ // and the Tor path (a tor daemon's control and SOCKS ports; nothing is ever installed for it). The
5
+ // protocol is transfer.mjs's.
6
+ //
7
+ // Two layers. The verbs change the transfers file and queue messages; they run anywhere (a CLI beside
8
+ // a watcher queues with local: true and kicks it). The Engine runs in the one process that holds the
9
+ // identity's relay session (watch, ui, the MCP server, or a CLI transfer verb with no holder): it takes
10
+ // the TRANSFER_LABEL messages the carrier kept apart, makes and answers offers, and moves the bytes.
11
+ //
12
+ // send({ carrier, identity, to, path, via, direct, local }) → the record: the file hashed in place, its manifest sent
13
+ // accept({ carrier, identity, id, direct, via, local }) the receiver's yes (free disk checked); the engine offers
14
+ // decline / cancel / resume / forget({ carrier, identity, id, local })
15
+ // intake({ carrier, identity }) → the files asked: manifests and ends filed by a process with no engine (inbox)
16
+ // list({ carrier, identity }) → { out, in }; setDirect({ carrier, identity, contact, on }); settings({ identity, patch })
17
+ // const e = new Engine({ carrier, identity, rtc, tor, stun, pro, onEvent }); e.kick(); await e.idle(); e.live(); await e.close()
18
+ //
19
+ // The file, 0600, beside the identity (x.json → x.transfers.json), under its own lock:
20
+ // { v, out: { id: sender's record }, in: { id: receiver's record }, direct: { contact's DID: true|false }, settings: { tor, prefer } }
21
+ // Partials: <identity>.files/.transfer/<id>.part (0600, written at offsets), <id>.have (a bit a chunk:
22
+ // checked and flushed), <id>.list (the chunk hashes); the sender's <id>.list beside them. A finished
23
+ // file is placed as send-file places one (<identity>.files/<contact>-<16 hex>/<sha256[0..8]>-<name>),
24
+ // never opened, and given to inbox as one item {type: "file", …, transfer: id}.
25
+ //
26
+ // The direct switch (design §7): direct gives the contact this agent's public and LAN addresses. On
27
+ // for own contacts (tier own or ours), asked once for the others (direct_ask until a yes or a no is
28
+ // kept); off: Tor, else no path. Tor: settings.tor (default on), effective only when a tor daemon
29
+ // answers (SIGELO_TOR: "<control host:port>[,<socks host:port>]", default 127.0.0.1:9051,127.0.0.1:9050;
30
+ // "off": none; SIGELO_TOR_PASSWORD for a HashedControlPassword). STUN: SIGELO_STUN, host:port,
31
+ // comma-separated ("" = host candidates only), default port 3478 of this agent's relay host and the
32
+ // contact's (coturn there, relay/deploy/README.md).
33
+ import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from 'node:crypto';
34
+ import { closeSync, createReadStream, existsSync, fdatasyncSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
35
+ import { open as openFile } from 'node:fs/promises';
36
+ import net from 'node:net';
37
+ import { dirname, join } from 'node:path';
38
+ import { fileURLToPath, pathToFileURL } from 'node:url';
39
+ import { TRANSFER_SEND, contactDir } from './carrier.mjs';
40
+ import { FILE_LABEL, safeName } from './file.mjs';
41
+ import { MsgError, fail } from './kdf.mjs';
42
+ import { sendable, transact } from './platform-node.mjs';
43
+ import {
44
+ ANSWER_WAIT, CHUNK, DAY, GATHER_MS, Have, ICE_MS, MANIFEST_TTL, MAX_SIZE, Pull, Serve, TRANSFER_LABEL, T, WAIT_ALL, WAIT_CONTACT,
45
+ channelLabel, checkMessage, chunkLength, chunksOf, deframer, enframe, frames, listOf, manifest, noPath, pathOrder, readFrame, torRoles,
46
+ } from './transfer.mjs';
47
+
48
+ export const FILE_V = 'sigelo-transfers/1';
49
+ export { TRANSFER_LABEL };
50
+ const KEPT = 30 * DAY, RETRIES_AUTO = 3, RETRY_MS = 5000, TOR_CONNECT_MS = 120_000, TOR_PROBE_MS = 1500, STUN_PORT = 3478;
51
+ const FREE_MARGIN = 64 * CHUNK;
52
+ const STATES_LIVE_IN = ['accepted', 'offering', 'active'], STATES_LIVE_OUT = ['active'];
53
+
54
+ export const transfersPath = (identity) => identity.replace(/\.json$/, '') + '.transfers.json';
55
+ const nowS = (carrier) => carrier?.clock ? carrier.clock() : Math.floor(Date.now() / 1000);
56
+ const dirOf = (carrier) => join(carrier.filesDir, '.transfer');
57
+ const partOf = (carrier, id) => join(dirOf(carrier), `${id}.part`);
58
+ const haveOf = (carrier, id) => join(dirOf(carrier), `${id}.have`);
59
+ const listPath = (carrier, id, side) => join(dirOf(carrier), `${id}.${side}.list`);
60
+ const writeAtomic = (file, bytes) => { const tmp = `${file}.tmp`; rmSync(tmp, { force: true }); writeFileSync(tmp, bytes, { mode: 0o600, flag: 'wx' }); renameSync(tmp, file); };
61
+ const folder = (d) => mkdirSync(d, { recursive: true, mode: 0o700 });
62
+
63
+ // ---------------------------------------------------------------- the file
64
+
65
+ /** Load, purge, change (fn), save, under the file's lock. → fn's result. */
66
+ export function state(identity, now, fn = () => undefined) {
67
+ const file = transfersPath(identity);
68
+ return transact(file, () => {
69
+ let s = { v: FILE_V, out: {}, in: {}, direct: {}, settings: {} };
70
+ if (existsSync(file)) {
71
+ try { s = JSON.parse(readFileSync(file, 'utf8')); } catch (e) { fail('transfer_file', `${file} does not parse (${e.message}): delete it to drop the transfers in progress`); }
72
+ if (s?.v !== FILE_V || typeof s.out !== 'object' || typeof s.in !== 'object') fail('transfer_file', `${file} is not a ${FILE_V} file`);
73
+ s.direct ??= {}; s.settings ??= {};
74
+ }
75
+ const before = JSON.stringify(s);
76
+ for (const side of ['out', 'in']) for (const [k, r] of Object.entries(s[side])) if (['done', 'declined', 'cancelled', 'failed', 'expired'].includes(r.state) && r.at + KEPT < now) delete s[side][k];
77
+ const out = fn(s);
78
+ if (JSON.stringify(s) !== before) writeAtomic(file, JSON.stringify(s, null, 2));
79
+ return out;
80
+ }, 'sigelo transfer');
81
+ }
82
+
83
+ /** The live contact named (DID or name), or not_contact. */
84
+ export function contactOf(carrier, who) {
85
+ const cs = carrier.contacts().contacts.filter((c) => !c.revoked);
86
+ const hit = typeof who === 'string' && who.startsWith('did:sigelo:') ? cs.filter((c) => c.did === who || c.chain?.includes(who)) : cs.filter((c) => c.name === who);
87
+ if (hit.length === 0) fail('not_contact', `${JSON.stringify(who)} is not a contact`);
88
+ if (hit.length > 1) fail('name', `${hit.length} contacts are named ${JSON.stringify(who)}: use the DID`);
89
+ return hit[0];
90
+ }
91
+ const own = (c) => c.tier === 'own' || c.ours === true;
92
+ /** May this contact learn this agent's addresses (direct)? true, false, or null: not asked yet (never for own). */
93
+ export const directFor = (s, c) => (Object.hasOwn(s.direct, c.did) ? s.direct[c.did] : own(c) ? true : null);
94
+ const decideDirect = (s, c, direct) => {
95
+ if (direct === true || direct === false) { s.direct[c.did] = direct; return direct; }
96
+ const d = directFor(s, c);
97
+ if (d === null) fail('direct_ask', `direct shows ${c.name} this computer's public and local addresses; say once whether it may (direct on or off for ${c.name}); off: Tor only`);
98
+ return d;
99
+ };
100
+ const sendMsg = (carrier, to, content, local) => carrier.send(to, content, { label: TRANSFER_LABEL, internal: TRANSFER_SEND, local });
101
+
102
+ // ---------------------------------------------------------------- the verbs
103
+
104
+ /** The sender: hashes the file in place (each chunk, the whole), keeps its list, sends the manifest. */
105
+ export async function send({ carrier, identity, to, path, via = 'auto', direct, local = false }) {
106
+ if (via !== 'auto' && via !== 'tor') fail('usage', 'via: auto or tor');
107
+ const c = contactOf(carrier, to);
108
+ const f = sendable(path, { base: identity.replace(/\.json$/, ''), files: carrier.filesDir, log: carrier.logPath }, MAX_SIZE);
109
+ const now = nowS(carrier);
110
+ state(identity, now, (s) => decideDirect(s, c, direct));
111
+ const { hashes, whole } = await hashFile(f.real, f.size);
112
+ const m = manifest({ name: safeName(f.name), size: f.size, sha256: whole, hashes, now });
113
+ folder(dirOf(carrier));
114
+ writeAtomic(listPath(carrier, m.id, 'out'), hashes);
115
+ // The file must still be the one hashed.
116
+ const s2 = statSync(f.real);
117
+ if (s2.size !== f.size || s2.mtimeMs !== f.mtimeMs) fail('file_changed', `${path} changed while it was read: send it again`);
118
+ const rec = { id: m.id, to: c.did, contact: c.name, file: f.real, name: m.name, size: m.size, mtimeMs: f.mtimeMs, sha256: m.sha256, chunks: m.chunks, list: m.list, exp: m.exp, via, state: 'offered', attempt: 0, at: now, sent: 0 };
119
+ state(identity, now, (s) => { s.out[m.id] = rec; });
120
+ try { await sendMsg(carrier, c.did, m, local); } catch (e) {
121
+ state(identity, now, (s) => { s.out[m.id].state = 'failed'; s.out[m.id].reason = e.check ?? 'send'; s.out[m.id].detail = e.message; });
122
+ throw e;
123
+ }
124
+ return rec;
125
+ }
126
+ async function hashFile(file, size) {
127
+ const n = chunksOf(size), hashes = new Uint8Array(n * 32), whole = createHash('sha256'), fh = await openFile(file, 'r'), buf = Buffer.alloc(CHUNK);
128
+ try {
129
+ for (let i = 0; i < n; i++) {
130
+ const len = chunkLength(size, i);
131
+ const { bytesRead } = await fh.read(buf, 0, len, i * CHUNK);
132
+ if (bytesRead !== len) fail('file_changed', `${file} is shorter than it was`);
133
+ const b = buf.subarray(0, len);
134
+ hashes.set(createHash('sha256').update(b).digest(), i * 32);
135
+ whole.update(b);
136
+ }
137
+ } finally { await fh.close(); }
138
+ return { hashes, whole: whole.digest('hex') };
139
+ }
140
+ const sha = (b) => createHash('sha256').update(b).digest();
141
+
142
+ const recIn = (s, id) => s.in[id] ?? fail('transfer_unknown', `no transfer ${id} offered to this agent`);
143
+ const recOut = (s, id) => s.out[id] ?? fail('transfer_unknown', `no transfer ${id} of this agent's`);
144
+ /** Either side's record: → { side, r }. */
145
+ const either = (s, id) => (s.in[id] ? { side: 'in', r: s.in[id] } : s.out[id] ? { side: 'out', r: s.out[id] } : fail('transfer_unknown', `no transfer ${id}`));
146
+
147
+ /** The receiver's yes to a manifest (or a resume of one that stopped): free disk checked, the direct switch settled. */
148
+ export function accept({ carrier, identity, id, direct, via }) {
149
+ const now = nowS(carrier);
150
+ return state(identity, now, (s) => {
151
+ const r = recIn(s, id);
152
+ if (!['asked', 'interrupted', 'failed'].includes(r.state) || (r.state === 'failed' && !['no_path', 'cancelled', 'ice_timeout', 'tor'].includes(r.reason))) fail('transfer_state', `transfer ${id} is ${r.state}${r.reason ? ` (${r.reason})` : ''}`);
153
+ if (r.exp <= now) fail('transfer_expired', `the offer of ${r.name} expired`);
154
+ const c = contactOf(carrier, r.from);
155
+ decideDirect(s, c, direct);
156
+ folder(dirOf(carrier));
157
+ const have = readHave(carrier, r), need = r.size - have.bytes(r.size), st = statfsSync(dirOf(carrier)), free = st.bavail * st.bsize;
158
+ if (free < need + FREE_MARGIN) fail('disk_full', `${r.name} needs ${need} bytes more here, ${free} are free`);
159
+ if (via === 'tor' || via === 'auto') r.via = via;
160
+ r.state = 'accepted'; r.auto = 0; r.at = now; delete r.reason; delete r.detail;
161
+ return { ...r };
162
+ });
163
+ }
164
+ /** The receiver's no: the sender is told declined; nothing was written. */
165
+ export async function decline({ carrier, identity, id, local = false }) {
166
+ const now = nowS(carrier);
167
+ const r = state(identity, now, (s) => {
168
+ const x = recIn(s, id);
169
+ if (x.state !== 'asked') fail('transfer_state', `transfer ${id} is ${x.state}`);
170
+ x.state = 'declined'; x.at = now;
171
+ return { ...x };
172
+ });
173
+ await sendMsg(carrier, r.from, { typ: 'end', id, reason: 'declined' }, local).catch(() => {});
174
+ return r;
175
+ }
176
+ /** Either side stops a transfer: the other is told cancelled; the receiver's partials go. */
177
+ export async function cancel({ carrier, identity, id, local = false, engine = null }) {
178
+ const now = nowS(carrier);
179
+ const { side, r } = state(identity, now, (s) => {
180
+ const x = either(s, id);
181
+ if (['done', 'declined', 'cancelled', 'expired'].includes(x.r.state)) fail('transfer_state', `transfer ${id} is ${x.r.state}`);
182
+ x.r.state = 'cancelled'; x.r.at = now;
183
+ return { side: x.side, r: { ...x.r } };
184
+ });
185
+ engine?.drop(id, 'cancelled');
186
+ if (side === 'in') dropPartial(carrier, id);
187
+ await sendMsg(carrier, side === 'in' ? r.from : r.to, { typ: 'end', id, reason: 'cancelled' }, local).catch(() => {});
188
+ return r;
189
+ }
190
+ /** A finished, failed or unwanted record and its partials gone, here only. */
191
+ export function forget({ carrier, identity, id, engine = null }) {
192
+ const now = nowS(carrier);
193
+ const r = state(identity, now, (s) => {
194
+ const x = either(s, id);
195
+ if (x.side === 'in' && STATES_LIVE_IN.includes(x.r.state)) fail('transfer_state', `transfer ${id} is ${x.r.state}: cancel it first`);
196
+ delete s[x.side][id];
197
+ return x.r;
198
+ });
199
+ engine?.drop(id, 'cancelled');
200
+ dropPartial(carrier, id);
201
+ rmSync(listPath(carrier, id, 'out'), { force: true });
202
+ return r;
203
+ }
204
+ function dropPartial(carrier, id) { for (const f of [partOf(carrier, id), haveOf(carrier, id), listPath(carrier, id, 'in')]) rmSync(f, { force: true }); }
205
+
206
+ /** Both sides' records, newest first, with what the engine of this process knows live. */
207
+ export function list({ carrier, identity, engine = null }) {
208
+ const now = nowS(carrier);
209
+ return state(identity, now, (s) => {
210
+ const live = (r) => ({ ...r, ...(engine?.progress(r.id) ?? {}) });
211
+ const sort = (a, b) => b.at - a.at;
212
+ return {
213
+ out: Object.values(s.out).map((r) => { const { file: _f, ...x } = live(r); return x; }).sort(sort),
214
+ in: Object.values(s.in).map(live).sort(sort),
215
+ direct: { ...s.direct },
216
+ settings: settingsOf(s),
217
+ };
218
+ });
219
+ }
220
+ export function setDirect({ carrier, identity, contact, on }) {
221
+ if (typeof on !== 'boolean') fail('usage', 'on: true or false');
222
+ const c = contactOf(carrier, contact);
223
+ return state(identity, nowS(carrier), (s) => { s.direct[c.did] = on; return { did: c.did, name: c.name, direct: on }; });
224
+ }
225
+ const settingsOf = (s) => ({ tor: s.settings.tor !== false, prefer: s.settings.prefer === 'private' ? 'private' : 'fast' });
226
+ /** The settings, patched: { tor: true|false, prefer: 'fast'|'private' }. */
227
+ export function settings({ identity, patch = {}, now = Math.floor(Date.now() / 1000) }) {
228
+ if (patch.tor !== undefined && typeof patch.tor !== 'boolean') fail('usage', 'tor: on or off');
229
+ if (patch.prefer !== undefined && patch.prefer !== 'fast' && patch.prefer !== 'private') fail('usage', 'prefer: fast or private');
230
+ return state(identity, now, (s) => { if (patch.tor !== undefined) s.settings.tor = patch.tor; if (patch.prefer !== undefined) s.settings.prefer = patch.prefer; return settingsOf(s); });
231
+ }
232
+
233
+ function readHave(carrier, r) {
234
+ const f = haveOf(carrier, r.id);
235
+ try { return new Have(r.chunks, readFileSync(f)); } catch { return new Have(r.chunks); }
236
+ }
237
+
238
+ // ---------------------------------------------------------------- Tor (design §5a)
239
+
240
+ /** SIGELO_TOR → { control: [host, port], socks: [host, port], password } | null ("off"). */
241
+ export function torConfig(env = process.env) {
242
+ const v = (env.SIGELO_TOR ?? '').trim();
243
+ if (v === 'off') return null;
244
+ const [c, s] = (v || '127.0.0.1:9051,127.0.0.1:9050').split(',').map((x) => x.trim());
245
+ const hp = (x, d) => { const m = /^(.+):(\d{1,5})$/.exec(x ?? ''); return m ? [m[1], Number(m[2])] : d; };
246
+ return { control: hp(c, ['127.0.0.1', 9051]), socks: hp(s, ['127.0.0.1', 9050]), password: env.SIGELO_TOR_PASSWORD ?? null };
247
+ }
248
+ const connectTcp = (host, port, ms) => new Promise((ok, no) => {
249
+ const s = net.connect({ host, port });
250
+ const t = setTimeout(() => { s.destroy(); no(Object.assign(new Error(`tor: ${host}:${port} did not answer`), { check: 'tor' })); }, ms);
251
+ s.once('connect', () => { clearTimeout(t); ok(s); });
252
+ s.once('error', (e) => { clearTimeout(t); no(Object.assign(new Error(`tor: ${host}:${port}: ${e.code ?? e.message}`), { check: 'tor' })); });
253
+ });
254
+ /** An authenticated control connection: cmd(line) → the reply's lines (2xx), else throws check tor. */
255
+ export async function torControl(cfg, ms = TOR_PROBE_MS) {
256
+ const s = await connectTcp(cfg.control[0], cfg.control[1], ms);
257
+ let buf = '', waiting = [];
258
+ const replies = [];
259
+ s.setEncoding('utf8');
260
+ s.on('data', (d) => {
261
+ buf += d;
262
+ let i;
263
+ while ((i = buf.indexOf('\r\n')) >= 0) {
264
+ const line = buf.slice(0, i); buf = buf.slice(i + 2);
265
+ replies.push(line);
266
+ if (/^\d{3} /.test(line)) { const lines = replies.splice(0); const w = waiting.shift(); w?.(lines); }
267
+ }
268
+ });
269
+ s.on('error', () => {});
270
+ const cmd = (line) => new Promise((ok, no) => {
271
+ const t = setTimeout(() => no(Object.assign(new Error(`tor: no answer to ${line.split(' ')[0]}`), { check: 'tor' })), 15000);
272
+ waiting.push((lines) => {
273
+ clearTimeout(t);
274
+ const last = lines.at(-1);
275
+ if (!last.startsWith('2')) no(Object.assign(new Error(`tor: ${line.split(' ')[0]}: ${last}`), { check: 'tor' })); else ok(lines);
276
+ });
277
+ s.write(`${line}\r\n`);
278
+ });
279
+ try {
280
+ const info = (await cmd('PROTOCOLINFO 1')).join('\n');
281
+ const methods = /METHODS=([A-Z,]+)/.exec(info)?.[1].split(',') ?? [], cookieFile = /COOKIEFILE="((?:[^"\\]|\\.)*)"/.exec(info)?.[1]?.replace(/\\(.)/g, '$1');
282
+ let cookie = null;
283
+ if (cookieFile && (methods.includes('SAFECOOKIE') || methods.includes('COOKIE'))) { try { cookie = readFileSync(cookieFile); } catch {} }
284
+ if (methods.includes('NULL')) await cmd('AUTHENTICATE');
285
+ else if (cookie && methods.includes('SAFECOOKIE')) {
286
+ const cn = randomBytes(32), r = (await cmd(`AUTHCHALLENGE SAFECOOKIE ${cn.toString('hex')}`)).join(' ');
287
+ const sh = /SERVERHASH=([0-9A-Fa-f]{64})/.exec(r)?.[1], sn = /SERVERNONCE=([0-9A-Fa-f]{64})/.exec(r)?.[1];
288
+ if (!sh || !sn) fail('tor', 'tor: AUTHCHALLENGE answer unreadable');
289
+ const msg = Buffer.concat([cookie, cn, Buffer.from(sn, 'hex')]);
290
+ if (createHmac('sha256', 'Tor safe cookie authentication server-to-controller hash').update(msg).digest('hex') !== sh.toLowerCase()) fail('tor', 'tor: the control port did not prove it holds the cookie');
291
+ await cmd(`AUTHENTICATE ${createHmac('sha256', 'Tor safe cookie authentication controller-to-server hash').update(msg).digest('hex')}`);
292
+ } else if (cookie && methods.includes('COOKIE')) await cmd(`AUTHENTICATE ${cookie.toString('hex')}`);
293
+ else if (cfg.password !== null && methods.includes('HASHEDPASSWORD')) await cmd(`AUTHENTICATE "${cfg.password.replace(/[\\"]/g, '\\$&')}"`);
294
+ else fail('tor', `tor: cannot authenticate to the control port (methods ${methods.join(',') || 'none'}; set SIGELO_TOR_PASSWORD, or make the cookie readable)`);
295
+ } catch (e) { s.destroy(); throw e; }
296
+ return { cmd, close: () => { try { s.end('QUIT\r\n'); } catch {} s.destroy(); } };
297
+ }
298
+ /** What this side can do with Tor: { serve: a control port that authenticates, connect: a SOCKS port that answers }. */
299
+ export async function torCaps(cfg) {
300
+ if (!cfg) return { serve: false, connect: false };
301
+ const serve = await torControl(cfg).then((c) => { c.close(); return true; }, () => false);
302
+ const connect = await connectTcp(cfg.socks[0], cfg.socks[1], TOR_PROBE_MS).then((s) => { s.destroy(); return true; }, () => false);
303
+ return { serve, connect };
304
+ }
305
+ const b32 = (b) => { const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; let bits = 0, v = 0, o = ''; for (const x of b) { v = (v << 8) | x; bits += 8; while (bits >= 5) { o += A[(v >>> (bits - 5)) & 31]; bits -= 5; } } if (bits) o += A[(v << (5 - bits)) & 31]; return o; };
306
+ /** A fresh x25519 client key for onion client authorization: { pub (base32, ADD_ONION's), priv (base64, ONION_CLIENT_AUTH_ADD's) }. */
307
+ export function clientKey() {
308
+ const { publicKey, privateKey } = generateKeyPairSync('x25519');
309
+ const x = Buffer.from(publicKey.export({ format: 'jwk' }).x, 'base64url'), d = Buffer.from(privateKey.export({ format: 'jwk' }).d, 'base64url');
310
+ return { pub: b32(x), priv: d.toString('base64') };
311
+ }
312
+ /** The base32 public key of a base64 x25519 private key (the fake tor of the tests checks client auth with it). */
313
+ export function clientPub(priv) {
314
+ const der = Buffer.concat([Buffer.from('302e020100300506032b656e04220420', 'hex'), Buffer.from(priv, 'base64')]);
315
+ return b32(Buffer.from(createPublicKey(createPrivateKey({ key: der, format: 'der', type: 'pkcs8' })).export({ format: 'jwk' }).x, 'base64url'));
316
+ }
317
+ /** SOCKS5 CONNECT to host:port through tor, tried until ms passed (a new onion takes 10 to 60 s to be reachable). */
318
+ export async function socksConnect(cfg, host, port, ms = TOR_CONNECT_MS) {
319
+ const until = Date.now() + ms;
320
+ for (;;) {
321
+ try { return await socksOnce(cfg, host, port); } catch (e) {
322
+ if (Date.now() + 3000 > until) throw e;
323
+ await new Promise((r) => setTimeout(r, 3000));
324
+ }
325
+ }
326
+ }
327
+ async function socksOnce(cfg, host, port) {
328
+ const s = await connectTcp(cfg.socks[0], cfg.socks[1], 10000);
329
+ // Everything the proxy sent, read n bytes at a time; what follows the reply is the stream's (kept for it).
330
+ let acc = Buffer.alloc(0), want = null, gone = false;
331
+ const onData = (d) => { acc = Buffer.concat([acc, d]); want?.(); };
332
+ const onClose = () => { gone = true; want?.(); };
333
+ s.on('data', onData); s.once('close', onClose);
334
+ const read = (n) => new Promise((ok, no) => {
335
+ const t = setTimeout(() => { want = null; no(Object.assign(new Error('tor: SOCKS gave no answer'), { check: 'tor' })); }, 60000);
336
+ want = () => {
337
+ if (acc.length >= n) { clearTimeout(t); want = null; const x = acc.subarray(0, n); acc = acc.subarray(n); ok(x); }
338
+ else if (gone) { clearTimeout(t); want = null; no(Object.assign(new Error('tor: SOCKS closed'), { check: 'tor' })); }
339
+ };
340
+ want();
341
+ });
342
+ try {
343
+ s.write(Buffer.from([5, 1, 0]));
344
+ const g = await read(2);
345
+ if (g[0] !== 5 || g[1] !== 0) fail('tor', 'tor: SOCKS refused the greeting');
346
+ const h = Buffer.from(host);
347
+ s.write(Buffer.concat([Buffer.from([5, 1, 0, 3, h.length]), h, Buffer.from([port >> 8, port & 255])]));
348
+ const r = await read(4);
349
+ if (r[1] !== 0) fail('tor', `tor: SOCKS could not reach ${host} (reply ${r[1]})`);
350
+ await read(r[3] === 1 ? 6 : r[3] === 4 ? 18 : (await read(1))[0] + 2);
351
+ s.pause(); s.off('data', onData); s.off('close', onClose);
352
+ s.removeAllListeners('error'); s.on('error', () => {});
353
+ if (acc.length) s.unshift(acc); // before any 'data' listener: read again by the stream's own
354
+ return s;
355
+ } catch (e) { s.destroy(); throw e; }
356
+ }
357
+ /** A net.Socket as transfer.mjs's channel: frames behind a u32 length. */
358
+ export function streamChannel(sock, first = []) {
359
+ const on = { frame: [], low: [], close: [] }, take = deframer();
360
+ let closed = false;
361
+ const shut = () => { if (closed) return; closed = true; for (const f of on.close) { try { f(); } catch {} } };
362
+ const feed = (d) => { let fs; try { fs = take(new Uint8Array(d.buffer, d.byteOffset, d.length)); } catch { sock.destroy(); return; } for (const f of fs) for (const g of on.frame) g(f); };
363
+ // Paused by whoever handed it over: nothing is read before the frame handlers are on.
364
+ setImmediate(() => { for (const d of first) feed(d); sock.on('data', feed); sock.resume(); });
365
+ sock.on('drain', () => { for (const f of on.low) f(); });
366
+ sock.on('close', shut);
367
+ sock.on('error', () => {});
368
+ return {
369
+ send(f) { if (closed) throw new Error('closed'); sock.write(enframe(f)); },
370
+ buffered: () => sock.writableLength,
371
+ close() { sock.destroy(); shut(); },
372
+ on(e, fn) { on[e].push(fn); },
373
+ };
374
+ }
375
+
376
+ // ---------------------------------------------------------------- the direct path's library
377
+
378
+ const HERE = dirname(fileURLToPath(import.meta.url));
379
+ /** sigelo-transfer's rtc.mjs, from beside sigelo-contact (an install's node_modules, or the repository's
380
+ * sigelo-transfer/), or null: then transfers go over Tor only. Only a package named sigelo-transfer loads. */
381
+ export async function loadRtc() {
382
+ for (const d of [join(HERE, '..', 'sigelo-transfer'), join(HERE, 'node_modules', 'sigelo-transfer')]) {
383
+ try {
384
+ const m = JSON.parse(readFileSync(join(d, 'package.json'), 'utf8'));
385
+ if (m?.name !== 'sigelo-transfer') continue;
386
+ return await import(pathToFileURL(join(d, 'rtc.mjs')).href);
387
+ } catch {}
388
+ }
389
+ return null;
390
+ }
391
+ const hostOf = (relay) => (typeof relay === 'string' && relay ? relay.replace(/:\d+$/, '') : null);
392
+ /** The STUN servers for a transfer with contact c: SIGELO_STUN, else this agent's relay host and the contact's, port 3478. */
393
+ export function stunFor(carrier, c, env = process.env) {
394
+ if (env.SIGELO_STUN !== undefined) return env.SIGELO_STUN.split(',').map((x) => x.trim()).filter(Boolean).map((x) => (/:\d+$/.test(x) ? x : `${x}:${STUN_PORT}`));
395
+ return [...new Set([hostOf(carrier.relay), hostOf(c?.relay)].filter(Boolean))].map((h) => `${h}:${STUN_PORT}`);
396
+ }
397
+
398
+ /**
399
+ * Without an engine (a CLI inbox, transfer list): the manifests and ends the carrier kept, taken and
400
+ * filed; offers, answers and onions stay for the engine of the next session. → the files now asked.
401
+ */
402
+ export async function intake({ carrier, identity }) {
403
+ const e = new Engine({ carrier, identity, rtc: async () => null, tor: null, timer: false });
404
+ const asked = [];
405
+ e.onEvent = (x) => { if (x.what === 'asked') asked.push(x); };
406
+ await e.round((m) => ['manifest', 'end'].includes(m?.content?.typ) && m.content.reason !== 'try_tor');
407
+ await e.close();
408
+ return asked;
409
+ }
410
+
411
+ // ---------------------------------------------------------------- the engine
412
+
413
+ export class Engine {
414
+ /**
415
+ * carrier: started (it holds the session); identity: the identity file; rtc: () → sigelo-transfer or null
416
+ * (loadRtc); tor: torConfig(); stun: a list, or null for stunFor; pro: () → whether this agent's pool is Pro
417
+ * (T4 knows it; until then false: the free order); onEvent(e): {type: 'transfer', what, id, …}.
418
+ */
419
+ constructor({ carrier, identity, rtc = loadRtc, tor = torConfig(), stun = null, pro = () => false, onEvent = () => {}, retryMs = RETRY_MS, torConnectMs = TOR_CONNECT_MS, timer = true }) {
420
+ Object.assign(this, { carrier, identity, rtcLoad: rtc, torCfg: tor, stun, pro, onEvent, retryMs, torConnectMs });
421
+ this.attempts = new Map(); // id → { role, attempt, peer, channel, proto, onion, server, got, sent, path }
422
+ this.chain = Promise.resolve(); this.again = false; this.running = false; this.closed = false;
423
+ this.timer = timer ? setInterval(() => this.kick(), 2000) : null; this.timer?.unref?.();
424
+ this.capsAt = 0; this.caps = null;
425
+ }
426
+ now() { return nowS(this.carrier); }
427
+ emit(what, x) { try { this.onEvent({ type: 'transfer', what, ...x, at_ms: Date.now() }); } catch {} }
428
+ async rtc() { if (this.rtcMod === undefined) this.rtcMod = await this.rtcLoad(); return this.rtcMod; }
429
+ async torCaps() {
430
+ const on = state(this.identity, this.now(), (s) => settingsOf(s).tor);
431
+ if (!on || !this.torCfg) return { serve: false, connect: false };
432
+ if (!this.caps || Date.now() - this.capsAt > 60_000) { this.caps = await torCaps(this.torCfg); this.capsAt = Date.now(); }
433
+ return this.caps;
434
+ }
435
+ /** One round soon (a `transfer` event, a kick from a verb beside this process). */
436
+ kick() {
437
+ if (this.closed) return this.chain;
438
+ if (this.running) { this.again = true; return this.chain; }
439
+ this.running = true;
440
+ this.chain = this.chain.then(async () => { do { this.again = false; await this.round(); } while (this.again && !this.closed); }).catch((e) => this.emit('error', { detail: e.message })).finally(() => { this.running = false; });
441
+ return this.chain;
442
+ }
443
+ live() { return this.attempts.size > 0 || state(this.identity, this.now(), (s) => Object.values(s.in).some((r) => STATES_LIVE_IN.includes(r.state)) || Object.values(s.out).some((r) => STATES_LIVE_OUT.includes(r.state))); }
444
+ /** Resolves true when nothing is live (busy: another test, e.g. a transfer's record not finished), false once ms passed. */
445
+ async idle(ms = Infinity, busy = () => this.live()) {
446
+ const until = Date.now() + ms;
447
+ while (Date.now() < until && !this.closed) {
448
+ await this.kick();
449
+ if (!busy()) return true;
450
+ await new Promise((r) => setTimeout(r, 500));
451
+ }
452
+ return false;
453
+ }
454
+ progress(id) { const a = this.attempts.get(id); return a ? { live: a.path ?? 'connecting', got: a.got, sent: a.sent, rate: a.rate ?? null } : null; }
455
+ /** An attempt of this process stopped (cancel, forget). */
456
+ drop(id, reason) { const a = this.attempts.get(id); if (!a) return; this.attempts.delete(id); a.stopped = reason; try { a.proto?.stop(reason); } catch {} this.#closeAttempt(a); }
457
+ async close() {
458
+ this.closed = true;
459
+ if (this.timer) clearInterval(this.timer);
460
+ await this.chain.catch(() => {});
461
+ for (const [id, a] of [...this.attempts]) {
462
+ this.attempts.delete(id);
463
+ a.stopped = 'closed';
464
+ try { a.proto?.stop('cancelled'); } catch {}
465
+ this.#closeAttempt(a);
466
+ // Stopped here, not refused there: the receiver may resume it later.
467
+ state(this.identity, this.now(), (s) => { const r = s.in[id] ?? s.out[id]; if (r && r.state === 'active') r.state = s.in[id] ? 'interrupted' : 'offered'; });
468
+ }
469
+ }
470
+ #closeAttempt(a) {
471
+ try { a.channel?.close(); } catch {}
472
+ try { a.peer?.close(); } catch {}
473
+ try { a.server?.close(); } catch {}
474
+ if (a.onion) { const o = a.onion; void torControl(this.torCfg).then(async (c) => { try { await c.cmd(`DEL_ONION ${o}`); } finally { c.close(); } }, () => {}); a.onion = null; }
475
+ if (a.authAdded) { const o = a.authAdded; void torControl(this.torCfg).then(async (c) => { try { await c.cmd(`ONION_CLIENT_AUTH_REMOVE ${o}`); } finally { c.close(); } }, () => {}); a.authAdded = null; }
476
+ }
477
+
478
+ async round(pick) {
479
+ for (const m of this.carrier.takeTransfers(pick)) {
480
+ try { await this.#onMessage(m); } catch (e) {
481
+ if (!(e instanceof MsgError)) throw e;
482
+ this.emit('refused', { from: m.from, check: e.check, detail: e.message });
483
+ }
484
+ }
485
+ const now = this.now();
486
+ const todo = state(this.identity, now, (s) => {
487
+ const out = [];
488
+ for (const r of Object.values(s.in)) {
489
+ if (r.state === 'asked' && r.exp <= now) { r.state = 'expired'; r.at = now; }
490
+ if (r.state === 'accepted' && !this.attempts.has(r.id)) out.push(r.id);
491
+ if ((r.state === 'offering' || r.state === 'active') && !this.attempts.has(r.id)) { r.state = 'interrupted'; r.reason = 'drop'; r.retryAt = 0; }
492
+ if (r.state === 'offering' && r.offerAt + ANSWER_WAIT < now) { r.state = 'interrupted'; r.reason = 'lapsed'; r.detail = 'no answer within 10 minutes: is the sender online? transfer resume'; this.drop(r.id, 'lapsed'); }
493
+ if (r.state === 'interrupted' && r.reason === 'drop' && (r.auto ?? 0) < RETRIES_AUTO && !this.attempts.has(r.id) && (r.retryAt ?? 0) <= Date.now()) { r.auto = (r.auto ?? 0) + 1; r.state = 'accepted'; out.push(r.id); }
494
+ if (['interrupted', 'failed', 'cancelled'].includes(r.state) && (r.last ?? r.at) + MANIFEST_TTL < now && existsSync(partOf(this.carrier, r.id))) { dropPartial(this.carrier, r.id); r.state = 'expired'; }
495
+ }
496
+ for (const r of Object.values(s.out)) {
497
+ if (r.state === 'offered' && r.exp <= now) { r.state = 'expired'; r.at = now; }
498
+ if (r.state === 'active' && !this.attempts.has(r.id)) r.state = 'offered';
499
+ }
500
+ return out;
501
+ });
502
+ if (pick) return; // intake: no session here
503
+ for (const id of todo) await this.#offer(id).catch((e) => this.#fail('in', id, e.check ?? 'offer', e.message));
504
+ }
505
+
506
+ #fail(side, id, reason, detail) {
507
+ state(this.identity, this.now(), (s) => { const r = s[side][id]; if (r && !['done', 'cancelled', 'declined'].includes(r.state)) Object.assign(r, { state: 'failed', reason, detail, at: this.now() }); });
508
+ this.emit('failed', { id, reason, detail });
509
+ }
510
+
511
+ async #onMessage(m) {
512
+ const x = checkMessage(m.content), now = this.now();
513
+ if (x.typ === 'manifest') {
514
+ const r = state(this.identity, now, (s) => {
515
+ if (s.in[x.id]) return null; // seen
516
+ if (x.exp <= now) return null;
517
+ const waiting = Object.values(s.in).filter((y) => y.state === 'asked');
518
+ if (waiting.length >= WAIT_ALL || waiting.filter((y) => y.from === m.from).length >= WAIT_CONTACT) return 'busy';
519
+ s.in[x.id] = { id: x.id, from: m.from, contact: m.name, name: safeName(x.name), size: x.size, sha256: x.sha256, chunks: x.chunks, list: x.list, exp: x.exp, state: 'asked', attempt: 0, at: now, got: 0 };
520
+ return { ...s.in[x.id] };
521
+ });
522
+ if (r === 'busy') { await sendMsg(this.carrier, m.from, { typ: 'end', id: x.id, reason: 'busy' }, false).catch(() => {}); return; }
523
+ if (r) this.emit('asked', { id: r.id, from: r.from, contact: r.contact, name: r.name, size: r.size });
524
+ return;
525
+ }
526
+ // Any other: only from the contact the transfer is with.
527
+ const { side, r } = state(this.identity, now, (s) => (s.out[x.id]?.to === m.from ? { side: 'out', r: { ...s.out[x.id] } } : s.in[x.id]?.from === m.from ? { side: 'in', r: { ...s.in[x.id] } } : { side: null, r: null }));
528
+ if (!r) fail('transfer_unknown', `a ${x.typ} for a transfer this agent has with no such contact`);
529
+ if (x.typ === 'end') return this.#onEnd(side, r, x);
530
+ // Detached: ICE (30 s) and a Tor connection (up to 2 minutes) must not hold the next message.
531
+ const bg = (p) => { void p.catch((e) => this.emit('error', { id: r.id, detail: e.message })); };
532
+ if (side === 'out' && x.typ === 'offer') return bg(this.#onOffer(r, x, m));
533
+ if (side === 'in' && x.typ === 'answer') return bg(this.#onAnswer(r, x));
534
+ if (x.typ === 'onion') return bg(this.#onOnion(side, r, x));
535
+ fail('transfer_message', `a ${x.typ} on the ${side === 'in' ? 'receiving' : 'sending'} side`);
536
+ }
537
+
538
+ async #onEnd(side, r, x) {
539
+ const a = this.attempts.get(r.id);
540
+ if (x.reason === 'try_tor') {
541
+ if (side !== 'out' || !a || a.attempt !== x.attempt) return;
542
+ return this.#serveTor(side, r, a);
543
+ }
544
+ if (x.reason === 'done' && side === 'out') {
545
+ state(this.identity, this.now(), (s) => { if (s.out[r.id]) Object.assign(s.out[r.id], { state: 'done', at: this.now(), sent: r.size }); });
546
+ if (a) { this.attempts.delete(r.id); this.#closeAttempt(a); }
547
+ this.emit('done', { id: r.id, side, name: r.name });
548
+ return;
549
+ }
550
+ if (a && x.attempt !== undefined && x.attempt !== a.attempt) return;
551
+ if (a) { this.attempts.delete(r.id); a.stopped = x.reason; try { a.proto?.stop(x.reason); } catch {} this.#closeAttempt(a); }
552
+ const st = x.reason === 'declined' ? 'declined' : x.reason === 'cancelled' ? 'cancelled' : 'failed';
553
+ state(this.identity, this.now(), (s) => { const y = s[side][r.id]; if (y && !['done'].includes(y.state)) Object.assign(y, { state: st, ...(st === 'failed' && { reason: x.reason, detail: x.reason === 'no_path' ? noPath(y.contact) : `the other side ended it: ${x.reason}` }), at: this.now() }); });
554
+ if (side === 'in' && ['cancelled', 'chunk_hash', 'file_changed'].includes(x.reason)) dropPartial(this.carrier, r.id);
555
+ this.emit(st, { id: r.id, side, reason: x.reason });
556
+ }
557
+
558
+ // ---- the receiver: an attempt is an offer
559
+ async #offer(id) {
560
+ const now = this.now();
561
+ const prev = this.attempts.get(id);
562
+ if (prev) { this.attempts.delete(id); this.#closeAttempt(prev); }
563
+ const r = state(this.identity, now, (s) => ({ ...s.in[id], directOk: directFor(s, contactOf(this.carrier, s.in[id].from)) === true, pro: this.pro(), prefer: settingsOf(s).prefer }));
564
+ const c = contactOf(this.carrier, r.from), tor = await this.torCaps(), rtc = await this.rtc();
565
+ // The paths this attempt may take, in order; Tor here means this side can play either part.
566
+ const order = pathOrder({ pro: r.pro, prefer: r.prefer, via: r.via === 'tor' ? 'tor' : 'auto', direct: r.directOk && rtc !== null, tor: tor.serve || tor.connect });
567
+ if (order.length === 0) {
568
+ this.#fail('in', id, 'no_path', r.directOk ? noPath(c.name) : `direct is off for ${c.name} and Tor is not on here: ${noPath(c.name)}`);
569
+ await sendMsg(this.carrier, r.from, { typ: 'end', id, reason: 'no_path' }, false).catch(() => {});
570
+ return;
571
+ }
572
+ const attempt = (r.attempt ?? 0) + 1, a = { role: 'in', attempt, order, tor, got: 0, sent: 0 };
573
+ this.attempts.set(id, a);
574
+ let sdp = null;
575
+ if (order[0] === 'direct') {
576
+ a.peer = await rtc.peer({ stun: this.stun ?? stunFor(this.carrier, c), gatherMs: GATHER_MS });
577
+ sdp = await a.peer.offer(channelLabel(id, attempt));
578
+ }
579
+ state(this.identity, now, (s) => Object.assign(s.in[id], { state: 'offering', attempt, offerAt: this.now(), path: order[0] }));
580
+ await sendMsg(this.carrier, r.from, { typ: 'offer', id, attempt, sdp, tor, ...(order[0] === 'tor' && { via: 'tor' }) }, false);
581
+ this.emit('offered', { id, attempt, path: order[0] });
582
+ }
583
+ async #onAnswer(r, x) {
584
+ const a = this.attempts.get(r.id);
585
+ if (!a || a.attempt !== x.attempt || a.answered) return;
586
+ a.answered = true; a.peerTor = x.tor;
587
+ state(this.identity, this.now(), (s) => { if (s.in[r.id]) s.in[r.id].state = 'active'; });
588
+ if (a.order[0] === 'direct' && x.sdp !== null && a.peer) {
589
+ try {
590
+ await a.peer.accept(x.sdp);
591
+ a.path = 'direct';
592
+ const ch = await a.peer.open(ICE_MS);
593
+ if (this.attempts.get(r.id) !== a) { ch.close(); return; }
594
+ return this.#pull(r, a, ch);
595
+ } catch (e) { if (this.attempts.get(r.id) !== a) return; a.peer?.close(); a.peer = null; this.emit('no_direct', { id: r.id, detail: e.message }); }
596
+ }
597
+ return this.#nextPath(r, a, a.order[0] === 'direct' ? 1 : 0);
598
+ }
599
+ // The receiver, after the direct path failed (or was not offered): Tor if both sides can, else the next attempt or no path.
600
+ async #nextPath(r, a, k) {
601
+ const rest = a.order.slice(k);
602
+ const who = torRoles(a.peerTor, a.tor);
603
+ if (rest[0] === 'tor' && who) {
604
+ a.path = 'tor';
605
+ if (who === 'receiver') return this.#serveTor('in', r, a);
606
+ await sendMsg(this.carrier, r.from, { typ: 'end', id: r.id, reason: 'try_tor', attempt: a.attempt }, false);
607
+ return;
608
+ }
609
+ // Tor first (Pro private) and it cannot: direct as a new attempt.
610
+ if (rest[0] === 'tor' && rest.includes('direct') && a.order[0] === 'tor') {
611
+ state(this.identity, this.now(), (s) => { s.in[r.id].via = 'auto'; s.in[r.id].state = 'accepted'; });
612
+ this.attempts.delete(r.id); this.#closeAttempt(a);
613
+ return this.kick();
614
+ }
615
+ this.attempts.delete(r.id); this.#closeAttempt(a);
616
+ const c = contactOf(this.carrier, r.from);
617
+ this.#fail('in', r.id, 'no_path', noPath(c.name));
618
+ await sendMsg(this.carrier, r.from, { typ: 'end', id: r.id, reason: 'no_path', attempt: a.attempt }, false).catch(() => {});
619
+ }
620
+
621
+ // ---- the sender: an offer is answered
622
+ async #onOffer(r, x, m) {
623
+ if (['done', 'cancelled', 'declined', 'expired'].includes(r.state)) { await sendMsg(this.carrier, m.from, { typ: 'end', id: r.id, reason: r.state === 'done' ? 'done' : 'cancelled' }, false).catch(() => {}); return; }
624
+ if (x.attempt <= (r.attempt ?? 0)) return;
625
+ const prev = this.attempts.get(r.id);
626
+ if (prev) { this.attempts.delete(r.id); this.#closeAttempt(prev); }
627
+ // Read in place: the file must be the one hashed.
628
+ let st;
629
+ try { st = statSync(r.file); } catch { st = null; }
630
+ if (!st || st.size !== r.size || st.mtimeMs !== r.mtimeMs) {
631
+ this.#fail('out', r.id, 'file_changed', `${r.file} changed or went since it was offered: send it again`);
632
+ await sendMsg(this.carrier, m.from, { typ: 'end', id: r.id, reason: 'file_changed' }, false).catch(() => {});
633
+ return;
634
+ }
635
+ const c = contactOf(this.carrier, r.to), tor = await this.torCaps(), rtc = await this.rtc();
636
+ const directOk = state(this.identity, this.now(), (s) => directFor(s, c) === true) && r.via !== 'tor' && x.via !== 'tor' && x.sdp !== null && rtc !== null;
637
+ const a = { role: 'out', attempt: x.attempt, tor, peerTor: x.tor, got: 0, sent: 0 };
638
+ this.attempts.set(r.id, a);
639
+ state(this.identity, this.now(), (s) => Object.assign(s.out[r.id], { state: 'active', attempt: x.attempt }));
640
+ let sdp = null;
641
+ if (directOk) {
642
+ a.peer = await rtc.peer({ stun: this.stun ?? stunFor(this.carrier, c), gatherMs: GATHER_MS });
643
+ sdp = await a.peer.answer(x.sdp, channelLabel(r.id, x.attempt));
644
+ }
645
+ await sendMsg(this.carrier, m.from, { typ: 'answer', id: r.id, attempt: x.attempt, sdp, tor }, false);
646
+ if (!a.peer) return; // the receiver says what comes next: try_tor, an onion, or end
647
+ try {
648
+ a.path = 'direct';
649
+ const ch = await a.peer.open(ICE_MS);
650
+ if (this.attempts.get(r.id) !== a) { ch.close(); return; }
651
+ this.#serve(r, a, ch);
652
+ } catch (e) { if (this.attempts.get(r.id) === a) { a.peer?.close(); a.peer = null; a.path = null; } }
653
+ }
654
+
655
+ // ---- Tor: the side that serves makes a one-shot onion; the other connects and proves the token
656
+ async #serveTor(side, r, a) {
657
+ if (!a.tor.serve || !this.torCfg) return;
658
+ const token = randomBytes(32), key = a.peerTor?.serve ? clientKey() : null;
659
+ a.path = 'tor';
660
+ const server = net.createServer();
661
+ a.server = server;
662
+ await new Promise((ok, no) => { server.once('error', no); server.listen(0, '127.0.0.1', ok); });
663
+ const local = server.address().port, port = 1024 + (randomBytes(2).readUInt16BE() % 60000);
664
+ const ctl = await torControl(this.torCfg);
665
+ let onion;
666
+ try {
667
+ const lines = await ctl.cmd(`ADD_ONION NEW:ED25519-V3 Flags=DiscardPK${key ? ',V3Auth' : ''} Port=${port},127.0.0.1:${local}${key ? ` ClientAuthV3=${key.pub}` : ''}`);
668
+ onion = /ServiceID=([a-z2-7]{56})/.exec(lines.join('\n'))?.[1] ?? fail('tor', 'tor: ADD_ONION gave no ServiceID');
669
+ } finally { ctl.close(); }
670
+ a.onion = onion;
671
+ server.on('connection', (sock) => {
672
+ // One stream, the one that proves the token first; any other is closed.
673
+ if (a.channel) { sock.destroy(); return; }
674
+ let got = Buffer.alloc(0);
675
+ const t = setTimeout(() => sock.destroy(), 30000);
676
+ const on = (d) => {
677
+ got = Buffer.concat([got, d]);
678
+ if (got.length < 4 + 33) return;
679
+ sock.pause(); sock.off('data', on); clearTimeout(t);
680
+ let f;
681
+ try { f = readFrame(new Uint8Array(got.subarray(4, 4 + 33))); } catch { sock.destroy(); return; }
682
+ if (got.readUInt32BE(0) !== 33 || f.type !== T.TOKEN || !Buffer.from(f.token).equals(token) || a.channel || this.attempts.get(r.id) !== a) { sock.destroy(); return; }
683
+ server.close();
684
+ const ch = streamChannel(sock, got.length > 37 ? [got.subarray(37)] : []);
685
+ a.channel = ch;
686
+ if (side === 'in') this.#pull(r, a, ch); else this.#serve(r, a, ch);
687
+ };
688
+ sock.on('data', on); sock.on('error', () => {});
689
+ });
690
+ await sendMsg(this.carrier, side === 'in' ? r.from : r.to, { typ: 'onion', id: r.id, attempt: a.attempt, onion, port, auth: key?.priv ?? null, token: token.toString('hex') }, false);
691
+ this.emit('onion', { id: r.id });
692
+ }
693
+ async #onOnion(side, r, x) {
694
+ const a = this.attempts.get(r.id);
695
+ if (!a || a.attempt !== x.attempt || a.channel || !a.tor.connect || !this.torCfg) return;
696
+ a.path = 'tor';
697
+ try {
698
+ if (x.auth !== null && a.tor.serve) {
699
+ const ctl = await torControl(this.torCfg);
700
+ try { await ctl.cmd(`ONION_CLIENT_AUTH_ADD ${x.onion} x25519:${x.auth}`); a.authAdded = x.onion; } finally { ctl.close(); }
701
+ }
702
+ const sock = await socksConnect(this.torCfg, `${x.onion}.onion`, x.port, this.torConnectMs);
703
+ if (this.attempts.get(r.id) !== a) { sock.destroy(); return; }
704
+ sock.write(enframe(frames.token(Buffer.from(x.token, 'hex'))));
705
+ const ch = streamChannel(sock);
706
+ a.channel = ch;
707
+ if (side === 'in') this.#pull(r, a, ch); else this.#serve(r, a, ch);
708
+ } catch (e) {
709
+ if (this.attempts.get(r.id) !== a) return;
710
+ this.attempts.delete(r.id); this.#closeAttempt(a);
711
+ if (side === 'in') {
712
+ this.#interrupt(r.id, 'tor', e.message);
713
+ await sendMsg(this.carrier, r.from, { typ: 'end', id: r.id, reason: 'no_path', attempt: a.attempt }, false).catch(() => {});
714
+ this.#fail('in', r.id, 'no_path', `Tor: ${e.message}`);
715
+ }
716
+ }
717
+ }
718
+
719
+ // ---- the bytes
720
+ #serve(r, a, ch) {
721
+ a.channel = ch;
722
+ const hashes = new Uint8Array(readFileSync(listPath(this.carrier, r.id, 'out')));
723
+ let fh = null;
724
+ const t0 = Date.now();
725
+ const read = async (i) => {
726
+ fh ??= await openFile(r.file, 'r');
727
+ const s = await fh.stat();
728
+ if (s.size !== r.size || s.mtimeMs !== r.mtimeMs) fail('file_changed', `${r.file} changed`);
729
+ const len = chunkLength(r.size, i), buf = Buffer.alloc(len);
730
+ const { bytesRead } = await fh.read(buf, 0, len, i * CHUNK);
731
+ if (bytesRead !== len) fail('file_changed', `${r.file} is shorter`);
732
+ return new Uint8Array(buf.buffer, buf.byteOffset, len);
733
+ };
734
+ const m = { ...r };
735
+ this.emit('active', { id: r.id, side: 'out', path: a.path });
736
+ a.proto = new Serve({
737
+ m, hashes, channel: ch, read,
738
+ onProgress: (n) => { a.sent = n; a.rate = n / 1e6 / Math.max(0.001, (Date.now() - t0) / 1000); },
739
+ onEnd: (reason, o) => {
740
+ void fh?.close().catch(() => {});
741
+ if (this.attempts.get(r.id) !== a) return;
742
+ this.attempts.delete(r.id); this.#closeAttempt(a);
743
+ if (reason === 'done' && o.remote) {
744
+ state(this.identity, this.now(), (s) => { if (s.out[r.id]) Object.assign(s.out[r.id], { state: 'done', at: this.now(), sent: r.size, path_used: a.path }); });
745
+ this.emit('done', { id: r.id, side: 'out', name: r.name, via: a.path, rate: a.rate });
746
+ } else if (reason === 'chunk_hash' || reason === 'file_changed') {
747
+ this.#fail('out', r.id, reason, `ended: ${reason}`);
748
+ } else {
749
+ // A drop or a stop on the channel: the receiver resumes with a new offer; a cancel comes as an end message.
750
+ state(this.identity, this.now(), (s) => { if (s.out[r.id]?.state === 'active') s.out[r.id].state = 'offered'; });
751
+ this.emit('interrupted', { id: r.id, side: 'out' });
752
+ }
753
+ },
754
+ });
755
+ a.proto.start();
756
+ }
757
+ #pull(r, a, ch) {
758
+ a.channel = ch;
759
+ const carrier = this.carrier, id = r.id;
760
+ folder(dirOf(carrier));
761
+ const part = partOf(carrier, id);
762
+ closeSync(openSync(part, 'a', 0o600));
763
+ const fd = openSync(part, 'r+');
764
+ const have = readHave(carrier, r);
765
+ let known = null;
766
+ try { known = new Uint8Array(readFileSync(listPath(carrier, id, 'in'))); if (listOf(known) !== r.list) known = null; } catch {}
767
+ a.got = have.bytes(r.size);
768
+ const t0 = Date.now(), start = a.got;
769
+ let saved = Date.now();
770
+ this.emit('active', { id, side: 'in', path: a.path });
771
+ const write = (b, pos) => { let o = 0; while (o < b.length) o += writeSync(fd, b, o, b.length - o, pos + o); };
772
+ a.proto = new Pull({
773
+ m: { ...r, chunk: CHUNK }, have, hashes: known, channel: ch,
774
+ write: async (i, bytes) => { write(bytes, i * CHUNK); },
775
+ flush: async () => {
776
+ datasync(fd);
777
+ // .have once Pull has set the bits, after the bytes are on disk: a bit means checked and flushed.
778
+ setImmediate(() => {
779
+ try { writeAtomic(haveOf(carrier, id), have.bits); } catch {}
780
+ if (Date.now() - saved > 2000) { saved = Date.now(); state(this.identity, this.now(), (s) => { if (s.in[id]) Object.assign(s.in[id], { got: a.got, last: this.now() }); }); }
781
+ });
782
+ },
783
+ onList: (h) => { try { writeAtomic(listPath(carrier, id, 'in'), h); } catch {} },
784
+ onProgress: (n) => { a.got += n; a.rate = (a.got - start) / 1e6 / Math.max(0.001, (Date.now() - t0) / 1000); },
785
+ onEnd: (reason, o) => { void this.#pulled(r, a, fd, have, reason, o); },
786
+ });
787
+ a.proto.start();
788
+ }
789
+ async #pulled(r, a, fd, have, reason, o) {
790
+ const id = r.id, carrier = this.carrier;
791
+ try { writeAtomic(haveOf(carrier, id), have.bits); } catch {}
792
+ if (reason !== 'complete') {
793
+ try { closeSync(fd); } catch {}
794
+ if (this.attempts.get(id) !== a) return;
795
+ this.attempts.delete(id); this.#closeAttempt(a);
796
+ if (o.gone || (reason === 'cancelled' && !o.remote)) return this.#interrupt(id, 'drop', 'the channel went: resumed with a new offer');
797
+ if (reason === 'cancelled') { state(this.identity, this.now(), (s) => { if (s.in[id]) Object.assign(s.in[id], { state: 'cancelled', at: this.now() }); }); dropPartial(carrier, id); return; }
798
+ this.#fail('in', id, reason, `ended: ${reason}`);
799
+ if (reason === 'chunk_hash' || reason === 'file_changed') dropPartial(carrier, id);
800
+ if (!o.remote) await sendMsg(carrier, r.from, { typ: 'end', id, reason, attempt: a.attempt }, false).catch(() => {});
801
+ return;
802
+ }
803
+ // Every chunk checked and flushed: the whole file read back from disk.
804
+ datasync(fd); closeSync(fd);
805
+ const whole = await new Promise((ok, no) => {
806
+ const h = createHash('sha256');
807
+ createReadStream(partOf(carrier, id)).on('data', (d) => h.update(d)).on('end', () => ok(h.digest('hex'))).on('error', no);
808
+ });
809
+ if (whole !== r.sha256) {
810
+ a.proto.finish('chunk_hash');
811
+ this.attempts.delete(id); this.#closeAttempt(a);
812
+ dropPartial(carrier, id);
813
+ this.#fail('in', id, 'chunk_hash', 'the file read back is not the manifest\'s: dropped');
814
+ return;
815
+ }
816
+ const c = contactOf(carrier, r.from), dir = join(carrier.filesDir, contactDir(c));
817
+ folder(dir);
818
+ let path = null;
819
+ for (let i = 0; i < 64 && path === null; i++) {
820
+ const p = join(dir, `${r.sha256.slice(0, 8)}-${i === 0 ? '' : `${i + 1}-`}${r.name}`);
821
+ try { linkSync(partOf(carrier, id), p); unlinkSync(partOf(carrier, id)); path = p; } catch (e) {
822
+ if (e.code === 'EEXIST') continue;
823
+ if (!existsSync(p)) { renameSync(partOf(carrier, id), p); path = p; }
824
+ }
825
+ }
826
+ if (path === null) { this.#fail('in', id, 'file_exists', `64 files of that name and hash are in ${dir} already`); return; }
827
+ for (const f of [haveOf(carrier, id), listPath(carrier, id, 'in')]) rmSync(f, { force: true });
828
+ a.proto.finish('done');
829
+ state(this.identity, this.now(), (s) => { if (s.in[id]) Object.assign(s.in[id], { state: 'done', got: r.size, at: this.now(), saved: path, path_used: a.path }); });
830
+ this.attempts.delete(id);
831
+ setTimeout(() => this.#closeAttempt(a), 2000).unref?.();
832
+ carrier.deliver({ type: 'file', from: c.did, contact: c.name, current_did: c.current_did, label: FILE_LABEL, name: r.name, size: r.size, sha256: r.sha256, path, transfer: id, via: a.path });
833
+ await sendMsg(carrier, r.from, { typ: 'end', id, reason: 'done', attempt: a.attempt }, false).catch(() => {});
834
+ this.emit('done', { id, side: 'in', name: r.name, path, via: a.path, rate: a.rate });
835
+ }
836
+ #interrupt(id, reason, detail) {
837
+ state(this.identity, this.now(), (s) => { const r = s.in[id]; if (r && STATES_LIVE_IN.includes(r.state)) Object.assign(r, { state: 'interrupted', reason, detail, retryAt: Date.now() + this.retryMs, last: this.now() }); });
838
+ this.emit('interrupted', { id, side: 'in', reason });
839
+ }
840
+ }
841
+
842
+ /** A verb's resume: a stopped transfer offered again (the engine makes the offer; only what .have lacks is asked). */
843
+ export const resume = (o) => accept(o);
844
+
845
+ const datasync = (fd) => { try { fdatasyncSync(fd); } catch {} };