sigelo-contact 0.1.14 → 0.1.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -10
- package/call.mjs +831 -0
- package/carrier.mjs +1013 -112
- package/control.mjs +81 -22
- package/device.mjs +1 -1
- package/enrol.mjs +214 -35
- package/gen-carrier.mjs +4 -4
- package/gen-device.mjs +2 -2
- package/gen-envelope.mjs +3 -3
- package/gen-invite.mjs +3 -3
- package/gen-short.mjs +3 -3
- package/group.mjs +28 -9
- package/invite.mjs +63 -13
- package/kdf.mjs +1 -1
- package/link.mjs +1 -1
- package/package.json +34 -7
- package/page.mjs +1018 -81
- package/photo.mjs +37 -0
- package/platform-node.mjs +110 -13
- package/prekeys.mjs +10 -2
- package/public.mjs +93 -0
- package/relays.mjs +1 -1
- package/restore.mjs +3 -3
- package/rtc-web.mjs +109 -0
- package/short.mjs +19 -3
- package/store.mjs +126 -10
- package/test-carrier.mjs +121 -18
- package/test-device.mjs +1 -1
- package/test-enrol.mjs +123 -8
- package/test-envelope.mjs +16 -3
- package/test-file.mjs +5 -5
- package/test-group.mjs +48 -7
- package/test-invite.mjs +15 -2
- package/test-link.mjs +6 -6
- package/test-platform.mjs +5 -5
- package/test-presence.mjs +5 -5
- package/test-push.mjs +136 -0
- package/test-relay-lane.mjs +323 -0
- package/test-short.mjs +35 -12
- package/test-tier.mjs +6 -6
- package/test-transfer-web.mjs +313 -0
- package/test-transfer.mjs +51 -11
- package/test-voice.mjs +161 -0
- package/test-ws.mjs +5 -5
- package/transfer-engine.mjs +858 -0
- package/transfer-node.mjs +254 -641
- package/transfer-web.mjs +80 -0
- package/transfer.mjs +25 -6
- package/voice-web.mjs +113 -0
- package/voice.mjs +70 -0
- package/words-lock.mjs +25 -10
package/transfer-node.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// SPDX-License-Identifier: MIT
|
|
2
|
-
// Transfers on Node (design/transfer.md,
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// protocol is transfer.mjs's.
|
|
2
|
+
// Transfers on Node (design/transfer.md, apps/agent/TRANSFER.md): transfer-engine.mjs's records, verbs
|
|
3
|
+
// and Engine over this machine's disk, the file sent read in place, and the Tor path (a tor daemon's
|
|
4
|
+
// control and SOCKS ports; nothing is ever installed for it); the direct path is sigelo-transfer,
|
|
5
|
+
// loaded only when a transfer starts. The protocol is transfer.mjs's.
|
|
6
6
|
//
|
|
7
7
|
// Two layers. The verbs change the transfers file and queue messages; they run anywhere (a CLI beside
|
|
8
8
|
// a watcher queues with local: true and kicks it). The Engine runs in the one process that holds the
|
|
@@ -12,116 +12,128 @@
|
|
|
12
12
|
// send({ carrier, identity, to, path, via, direct, local }) → the record: the file hashed in place, its manifest sent
|
|
13
13
|
// accept({ carrier, identity, id, direct, via, local }) the receiver's yes (free disk checked); the engine offers
|
|
14
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 });
|
|
17
|
-
//
|
|
15
|
+
// intake({ carrier, identity, compared }) → the files asked: manifests and ends filed by a process with no engine (inbox)
|
|
16
|
+
// list({ carrier, identity }) → { out, in, direct, auto, settings }; setDirect({ carrier, identity, contact, on });
|
|
17
|
+
// setAuto({ carrier, identity, contact, mb }); settings({ identity, patch })
|
|
18
|
+
// const e = new Engine({ carrier, identity, rtc, tor, stun, pro, compared, onEvent }); e.kick(); await e.idle(); e.live(); await e.close()
|
|
18
19
|
//
|
|
19
|
-
// The file, 0600, beside the identity (x.json → x.transfers.json), under its own lock
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
//
|
|
23
|
-
// file is placed as send-file places one (<identity>.files/<contact>-<16 hex>/<sha256[0..8]>-<name>),
|
|
20
|
+
// The file, 0600, beside the identity (x.json → x.transfers.json), under its own lock (transfer-engine.mjs
|
|
21
|
+
// says what it holds). Partials: <identity>.files/.transfer/<id>.part (0600, written at offsets), <id>.have
|
|
22
|
+
// (a bit a chunk: checked and flushed), <id>.in.list (the chunk hashes); the sender's <id>.out.list beside
|
|
23
|
+
// them. A finished file is placed as send-file places one (<identity>.files/<contact>-<16 hex>/<sha256[0..8]>-<name>),
|
|
24
24
|
// never opened, and given to inbox as one item {type: "file", …, transfer: id}.
|
|
25
25
|
//
|
|
26
26
|
// The direct switch (design §7): direct gives the contact this agent's public and LAN addresses. On
|
|
27
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.
|
|
29
|
-
// answers (SIGELO_TOR: "<control host:port>[,<socks
|
|
30
|
-
// "off": none; SIGELO_TOR_PASSWORD for a
|
|
31
|
-
// comma-separated ("" = host candidates only),
|
|
32
|
-
// contact's (coturn there, relay/deploy/README.md).
|
|
28
|
+
// kept); off: Tor, else no path. The accept rule (design §10.2): transfer-engine.mjs. Tor: settings.tor
|
|
29
|
+
// (default on), effective only when a tor daemon answers (SIGELO_TOR: "<control host:port>[,<socks
|
|
30
|
+
// host:port>]", default 127.0.0.1:9051,127.0.0.1:9050; "off": none; SIGELO_TOR_PASSWORD for a
|
|
31
|
+
// HashedControlPassword). STUN: SIGELO_STUN, host:port, comma-separated ("" = host candidates only),
|
|
32
|
+
// default port 3478 of this agent's relay host and the contact's (coturn there, relay/deploy/README.md).
|
|
33
33
|
import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from 'node:crypto';
|
|
34
34
|
import { closeSync, createReadStream, existsSync, fdatasyncSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, statfsSync, unlinkSync, writeFileSync, writeSync } from 'node:fs';
|
|
35
35
|
import { open as openFile } from 'node:fs/promises';
|
|
36
36
|
import net from 'node:net';
|
|
37
|
-
import {
|
|
37
|
+
import { createRequire } from 'node:module';
|
|
38
|
+
import { dirname, join, resolve } from 'node:path';
|
|
38
39
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
39
40
|
import { TRANSFER_SEND, contactDir } from './carrier.mjs';
|
|
40
|
-
import {
|
|
41
|
-
import { MsgError, fail } from './kdf.mjs';
|
|
41
|
+
import { fail } from './kdf.mjs';
|
|
42
42
|
import { sendable, transact } from './platform-node.mjs';
|
|
43
|
-
import
|
|
44
|
-
|
|
45
|
-
channelLabel, checkMessage, chunkLength, chunksOf, deframer, enframe, frames, listOf, manifest, noPath, pathOrder, readFrame, torRoles,
|
|
46
|
-
} from './transfer.mjs';
|
|
43
|
+
import * as E from './transfer-engine.mjs';
|
|
44
|
+
import { CHUNK, MAX_SIZE, T, TRANSFER_LABEL, chunkLength, chunksOf, deframer, enframe, frames, readFrame } from './transfer.mjs';
|
|
47
45
|
|
|
48
|
-
export const FILE_V =
|
|
46
|
+
export const { FILE_V, contactOf, directFor, trustOf } = E;
|
|
49
47
|
export { TRANSFER_LABEL };
|
|
50
|
-
const
|
|
51
|
-
const FREE_MARGIN = 64 * CHUNK;
|
|
52
|
-
const STATES_LIVE_IN = ['accepted', 'offering', 'active'], STATES_LIVE_OUT = ['active'];
|
|
48
|
+
const TOR_CONNECT_MS = 120_000, TOR_PROBE_MS = 1500;
|
|
53
49
|
|
|
54
50
|
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
51
|
const writeAtomic = (file, bytes) => { const tmp = `${file}.tmp`; rmSync(tmp, { force: true }); writeFileSync(tmp, bytes, { mode: 0o600, flag: 'wx' }); renameSync(tmp, file); };
|
|
61
52
|
const folder = (d) => mkdirSync(d, { recursive: true, mode: 0o700 });
|
|
53
|
+
const datasync = (fd) => { try { fdatasyncSync(fd); } catch {} };
|
|
54
|
+
const u8 = (b) => new Uint8Array(b.buffer, b.byteOffset, b.length);
|
|
62
55
|
|
|
63
|
-
// ----------------------------------------------------------------
|
|
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
|
|
56
|
+
// ---------------------------------------------------------------- this machine's io (transfer-engine.mjs)
|
|
103
57
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
58
|
+
const ios = new Map();
|
|
59
|
+
/** The io of an identity file, its carrier's files directory (filesDir: carrier.filesDir, or <identity>.files). */
|
|
60
|
+
export function nodeIo(identity, filesDir = identity.replace(/\.json$/, '') + '.files', torCfg = null, logPath = null) {
|
|
61
|
+
const key = `${identity}\n${filesDir}\n${torCfg ? JSON.stringify(torCfg) : ''}\n${logPath ?? ''}`;
|
|
62
|
+
if (ios.has(key)) return ios.get(key);
|
|
63
|
+
const file = transfersPath(identity), dir = join(filesDir, '.transfer');
|
|
64
|
+
const partOf = (id) => join(dir, `${id}.part`), haveOf = (id) => join(dir, `${id}.have`), listOf = (id, side) => join(dir, `${id}.${side}.list`);
|
|
65
|
+
const io = {
|
|
66
|
+
flushEach: 8,
|
|
67
|
+
lock: (fn) => transact(file, fn, 'sigelo transfer'),
|
|
68
|
+
read: () => (existsSync(file) ? readFileSync(file, 'utf8') : null),
|
|
69
|
+
write: (text) => writeAtomic(file, text),
|
|
70
|
+
have: {
|
|
71
|
+
read: (id) => { try { return u8(readFileSync(haveOf(id))); } catch { return null; } },
|
|
72
|
+
write: (id, bits) => { if (bits === null) rmSync(haveOf(id), { force: true }); else { folder(dir); writeAtomic(haveOf(id), bits); } },
|
|
73
|
+
},
|
|
74
|
+
list: {
|
|
75
|
+
read: (id, side) => { try { return u8(readFileSync(listOf(id, side))); } catch { return null; } },
|
|
76
|
+
write: (id, side, bytes) => { folder(dir); writeAtomic(listOf(id, side), bytes); },
|
|
77
|
+
drop: (id, side) => rmSync(listOf(id, side), { force: true }),
|
|
78
|
+
},
|
|
79
|
+
part: {
|
|
80
|
+
exists: (id) => existsSync(partOf(id)),
|
|
81
|
+
drop: (id) => rmSync(partOf(id), { force: true }),
|
|
82
|
+
async open(id) {
|
|
83
|
+
folder(dir);
|
|
84
|
+
closeSync(openSync(partOf(id), 'a', 0o600));
|
|
85
|
+
const fd = openSync(partOf(id), 'r+');
|
|
86
|
+
return {
|
|
87
|
+
async write(b, pos) { let o = 0; while (o < b.length) o += writeSync(fd, b, o, b.length - o, pos + o); },
|
|
88
|
+
async flush() { datasync(fd); },
|
|
89
|
+
async close() { try { closeSync(fd); } catch {} },
|
|
90
|
+
};
|
|
91
|
+
},
|
|
92
|
+
sha256: (id) => new Promise((ok, no) => {
|
|
93
|
+
const h = createHash('sha256');
|
|
94
|
+
createReadStream(partOf(id)).on('data', (d) => h.update(d)).on('end', () => ok(h.digest('hex'))).on('error', no);
|
|
95
|
+
}),
|
|
96
|
+
},
|
|
97
|
+
free() { folder(dir); const st = statfsSync(dir); return st.bavail * st.bsize; },
|
|
98
|
+
async land(r, c) {
|
|
99
|
+
const to = join(filesDir, contactDir(c));
|
|
100
|
+
folder(to);
|
|
101
|
+
for (let i = 0; i < 64; i++) {
|
|
102
|
+
const p = join(to, `${r.sha256.slice(0, 8)}-${i === 0 ? '' : `${i + 1}-`}${r.name}`);
|
|
103
|
+
try { linkSync(partOf(r.id), p); unlinkSync(partOf(r.id)); return p; } catch (e) {
|
|
104
|
+
if (e.code === 'EEXIST') continue;
|
|
105
|
+
if (!existsSync(p)) { renameSync(partOf(r.id), p); return p; }
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
fail('file_exists', `64 files of that name and hash are in ${to} already`);
|
|
109
|
+
},
|
|
110
|
+
async prepare({ path }) {
|
|
111
|
+
const f = sendable(path, { base: identity.replace(/\.json$/, ''), files: filesDir, log: logPath }, MAX_SIZE);
|
|
112
|
+
const { hashes, whole } = await hashFile(f.real, f.size);
|
|
113
|
+
// The file must still be the one hashed.
|
|
114
|
+
const s2 = statSync(f.real);
|
|
115
|
+
if (s2.size !== f.size || s2.mtimeMs !== f.mtimeMs) fail('file_changed', `${path} changed while it was read: send it again`);
|
|
116
|
+
return { file: f.real, name: f.name, size: f.size, mtimeMs: f.mtimeMs, hashes, whole };
|
|
117
|
+
},
|
|
118
|
+
async changed(r) { let st; try { st = statSync(r.file); } catch { return true; } return st.size !== r.size || st.mtimeMs !== r.mtimeMs; },
|
|
119
|
+
async source(r) {
|
|
120
|
+
const fh = await openFile(r.file, 'r');
|
|
121
|
+
return {
|
|
122
|
+
async read(i) {
|
|
123
|
+
const s = await fh.stat();
|
|
124
|
+
if (s.size !== r.size || s.mtimeMs !== r.mtimeMs) fail('file_changed', `${r.file} changed`);
|
|
125
|
+
const len = chunkLength(r.size, i), buf = Buffer.alloc(len);
|
|
126
|
+
const { bytesRead } = await fh.read(buf, 0, len, i * CHUNK);
|
|
127
|
+
if (bytesRead !== len) fail('file_changed', `${r.file} is shorter`);
|
|
128
|
+
return u8(buf);
|
|
129
|
+
},
|
|
130
|
+
close: () => fh.close(),
|
|
131
|
+
};
|
|
132
|
+
},
|
|
133
|
+
tor: torCfg ? torOf(torCfg) : null,
|
|
134
|
+
};
|
|
135
|
+
ios.set(key, io);
|
|
136
|
+
return io;
|
|
125
137
|
}
|
|
126
138
|
async function hashFile(file, size) {
|
|
127
139
|
const n = chunksOf(size), hashes = new Uint8Array(n * 32), whole = createHash('sha256'), fh = await openFile(file, 'r'), buf = Buffer.alloc(CHUNK);
|
|
@@ -137,102 +149,42 @@ async function hashFile(file, size) {
|
|
|
137
149
|
} finally { await fh.close(); }
|
|
138
150
|
return { hashes, whole: whole.digest('hex') };
|
|
139
151
|
}
|
|
140
|
-
const
|
|
152
|
+
const ioOf = (o) => nodeIo(o.identity, o.carrier?.filesDir, null, o.carrier?.logPath ?? null);
|
|
141
153
|
|
|
142
|
-
|
|
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}`));
|
|
154
|
+
// ---------------------------------------------------------------- the verbs (transfer-engine.mjs's, on this machine)
|
|
146
155
|
|
|
147
|
-
/**
|
|
148
|
-
export
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
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
|
-
}
|
|
156
|
+
/** Load, purge, change (fn), save, under the file's lock. → fn's result. */
|
|
157
|
+
export const state = (identity, now, fn) => E.state(nodeIo(identity), now, fn);
|
|
158
|
+
export const send = (o) => E.send({ ...o, io: ioOf(o) });
|
|
159
|
+
export const prepare = (o) => E.prepare({ ...o, io: ioOf(o) });
|
|
160
|
+
export const sendTo = (o) => E.sendTo({ ...o, io: ioOf(o) });
|
|
161
|
+
export const fanOut = (o) => E.fanOut({ ...o, io: ioOf(o) });
|
|
162
|
+
export const accept = (o) => E.accept({ ...o, io: ioOf(o) });
|
|
163
|
+
/** A verb's resume: a stopped transfer offered again, a stuck one too (the engine makes the offer; only what .have lacks is asked). */
|
|
164
|
+
export const resume = (o) => E.resume({ ...o, io: ioOf(o) });
|
|
165
|
+
/** The sender's Retry: the file offered afresh under a new id, the old transfer cancelled. */
|
|
166
|
+
export const retry = (o) => E.retry({ ...o, io: ioOf(o) });
|
|
167
|
+
export const decline = (o) => E.decline({ ...o, io: ioOf(o) });
|
|
168
|
+
export const cancel = (o) => E.cancel({ ...o, io: ioOf(o) });
|
|
169
|
+
export const forget = (o) => E.forget({ ...o, io: ioOf(o) });
|
|
170
|
+
export const list = (o) => E.list({ ...o, io: ioOf(o) });
|
|
171
|
+
export const setDirect = (o) => E.setDirect({ ...o, io: ioOf(o) });
|
|
172
|
+
export const setAuto = (o) => E.setAuto({ ...o, io: ioOf(o) });
|
|
173
|
+
export const settings = ({ identity, patch, now }) => E.settings({ io: nodeIo(identity), patch, ...(now !== undefined && { now }) });
|
|
174
|
+
/** The STUN servers for a transfer with contact c: SIGELO_STUN, else this agent's relay host and the contact's, port 3478. */
|
|
175
|
+
export const stunFor = (carrier, c, env = process.env) => E.stunFor(carrier, c, env);
|
|
176
|
+
/**
|
|
177
|
+
* Without an engine (a CLI inbox, transfer list): the manifests and ends the carrier kept, taken and
|
|
178
|
+
* filed; offers, answers and onions stay for the engine of the next session. → the files now asked.
|
|
179
|
+
*/
|
|
180
|
+
export const intake = ({ carrier, identity, compared }) => E.intake({ carrier, io: nodeIo(identity, carrier.filesDir), compared });
|
|
232
181
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
182
|
+
/** The engine on this machine: E.Engine over nodeIo, with Tor when a tor daemon is configured. */
|
|
183
|
+
export class Engine extends E.Engine {
|
|
184
|
+
constructor({ carrier, identity, rtc = loadRtc, tor = torConfig(), stun = null, pro, compared, maxServe, onEvent, retryMs, torConnectMs = TOR_CONNECT_MS, timer, fallbackMs, stallMs, policy, env = process.env }) {
|
|
185
|
+
super({ carrier, io: nodeIo(identity, carrier.filesDir, tor, carrier.logPath ?? null), rtc, stun, env, pro, compared, maxServe, onEvent, retryMs, torConnectMs, timer, fallbackMs, stallMs, ...(policy && { policy }) });
|
|
186
|
+
this.identity = identity; this.torCfg = tor;
|
|
187
|
+
}
|
|
236
188
|
}
|
|
237
189
|
|
|
238
190
|
// ---------------------------------------------------------------- Tor (design §5a)
|
|
@@ -373,13 +325,94 @@ export function streamChannel(sock, first = []) {
|
|
|
373
325
|
};
|
|
374
326
|
}
|
|
375
327
|
|
|
328
|
+
// The Tor path as transfer-engine.mjs's io.tor: the side that serves makes a one-shot onion; the other connects and proves the token.
|
|
329
|
+
function torOf(cfg) {
|
|
330
|
+
return {
|
|
331
|
+
caps: () => torCaps(cfg),
|
|
332
|
+
close(a) {
|
|
333
|
+
try { a.server?.close(); } catch {}
|
|
334
|
+
if (a.onion) { const o = a.onion; void torControl(cfg).then(async (c) => { try { await c.cmd(`DEL_ONION ${o}`); } finally { c.close(); } }, () => {}); a.onion = null; }
|
|
335
|
+
if (a.authAdded) { const o = a.authAdded; void torControl(cfg).then(async (c) => { try { await c.cmd(`ONION_CLIENT_AUTH_REMOVE ${o}`); } finally { c.close(); } }, () => {}); a.authAdded = null; }
|
|
336
|
+
},
|
|
337
|
+
async serve(e, side, r, a) {
|
|
338
|
+
if (!a.tor.serve) return;
|
|
339
|
+
const token = randomBytes(32), key = a.peerTor?.serve ? clientKey() : null;
|
|
340
|
+
a.path = 'tor';
|
|
341
|
+
const server = net.createServer();
|
|
342
|
+
a.server = server;
|
|
343
|
+
await new Promise((ok, no) => { server.once('error', no); server.listen(0, '127.0.0.1', ok); });
|
|
344
|
+
const local = server.address().port, port = 1024 + (randomBytes(2).readUInt16BE() % 60000);
|
|
345
|
+
const ctl = await torControl(cfg);
|
|
346
|
+
let onion;
|
|
347
|
+
try {
|
|
348
|
+
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}` : ''}`);
|
|
349
|
+
onion = /ServiceID=([a-z2-7]{56})/.exec(lines.join('\n'))?.[1] ?? fail('tor', 'tor: ADD_ONION gave no ServiceID');
|
|
350
|
+
} finally { ctl.close(); }
|
|
351
|
+
a.onion = onion;
|
|
352
|
+
server.on('connection', (sock) => {
|
|
353
|
+
// One stream, the one that proves the token first; any other is closed.
|
|
354
|
+
if (a.channel) { sock.destroy(); return; }
|
|
355
|
+
let got = Buffer.alloc(0);
|
|
356
|
+
const t = setTimeout(() => sock.destroy(), 30000);
|
|
357
|
+
const on = (d) => {
|
|
358
|
+
got = Buffer.concat([got, d]);
|
|
359
|
+
if (got.length < 4 + 33) return;
|
|
360
|
+
sock.pause(); sock.off('data', on); clearTimeout(t);
|
|
361
|
+
let f;
|
|
362
|
+
try { f = readFrame(new Uint8Array(got.subarray(4, 4 + 33))); } catch { sock.destroy(); return; }
|
|
363
|
+
if (got.readUInt32BE(0) !== 33 || f.type !== T.TOKEN || !Buffer.from(f.token).equals(token) || a.channel || e.attempts.get(r.id) !== a) { sock.destroy(); return; }
|
|
364
|
+
server.close();
|
|
365
|
+
const ch = streamChannel(sock, got.length > 37 ? [got.subarray(37)] : []);
|
|
366
|
+
a.channel = ch;
|
|
367
|
+
if (side === 'in') e.pull(r, a, ch); else e.serve(r, a, ch);
|
|
368
|
+
};
|
|
369
|
+
sock.on('data', on); sock.on('error', () => {});
|
|
370
|
+
});
|
|
371
|
+
await e.carrier.send(side === 'in' ? r.from : r.to, { typ: 'onion', id: r.id, attempt: a.attempt, onion, port, auth: key?.priv ?? null, token: token.toString('hex') }, { label: TRANSFER_LABEL, internal: TRANSFER_SEND, local: false });
|
|
372
|
+
e.emit('onion', { id: r.id });
|
|
373
|
+
},
|
|
374
|
+
async connect(e, side, r, x, a) {
|
|
375
|
+
if (!a || a.attempt !== x.attempt || a.channel || !a.tor.connect) return;
|
|
376
|
+
a.path = 'tor';
|
|
377
|
+
try {
|
|
378
|
+
if (x.auth !== null && a.tor.serve) {
|
|
379
|
+
const ctl = await torControl(cfg);
|
|
380
|
+
try { await ctl.cmd(`ONION_CLIENT_AUTH_ADD ${x.onion} x25519:${x.auth}`); a.authAdded = x.onion; } finally { ctl.close(); }
|
|
381
|
+
}
|
|
382
|
+
const sock = await socksConnect(cfg, `${x.onion}.onion`, x.port, e.torConnectMs);
|
|
383
|
+
if (e.attempts.get(r.id) !== a) { sock.destroy(); return; }
|
|
384
|
+
sock.write(enframe(frames.token(Buffer.from(x.token, 'hex'))));
|
|
385
|
+
const ch = streamChannel(sock);
|
|
386
|
+
a.channel = ch;
|
|
387
|
+
if (side === 'in') e.pull(r, a, ch); else e.serve(r, a, ch);
|
|
388
|
+
} catch (err) {
|
|
389
|
+
if (e.attempts.get(r.id) !== a) return;
|
|
390
|
+
e.attempts.delete(r.id); e.closeAttempt(a);
|
|
391
|
+
if (side === 'in') {
|
|
392
|
+
e.interrupt(r.id, 'tor', err.message);
|
|
393
|
+
await e.carrier.send(r.from, { typ: 'end', id: r.id, reason: 'no_path', attempt: a.attempt }, { label: TRANSFER_LABEL, internal: TRANSFER_SEND, local: false }).catch(() => {});
|
|
394
|
+
e.fail('in', r.id, 'no_path', `Tor: ${err.message}`);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
},
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
376
401
|
// ---------------------------------------------------------------- the direct path's library
|
|
377
402
|
|
|
378
403
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
379
|
-
/** sigelo-transfer
|
|
380
|
-
* sigelo-
|
|
404
|
+
/** Where sigelo-transfer may sit, seen from sigelo-contact's directory `from`: the repository's apps/transfer/ beside
|
|
405
|
+
* apps/contact/; beside sigelo-contact in one node_modules; inside it; or wherever Node resolves the name from there (every
|
|
406
|
+
* node_modules above: `npm i -g sigelo-agent sigelo-transfer` puts it two levels above sigelo-agent's own sigelo-contact). */
|
|
407
|
+
export function rtcDirs(from = HERE) {
|
|
408
|
+
const dirs = [join(from, '..', 'transfer'), join(from, '..', 'sigelo-transfer'), join(from, 'node_modules', 'sigelo-transfer')];
|
|
409
|
+
try { dirs.push(dirname(createRequire(join(from, 'transfer-node.mjs')).resolve('sigelo-transfer/package.json'))); } catch {}
|
|
410
|
+
return [...new Set(dirs.map((d) => resolve(d)))];
|
|
411
|
+
}
|
|
412
|
+
/** sigelo-transfer's rtc.mjs (rtcDirs, in order), or null: then transfers go over Tor only. Only a package named
|
|
413
|
+
* sigelo-transfer loads, and only with its DTLS checks in place (rtc.mjs refuses to load otherwise). */
|
|
381
414
|
export async function loadRtc() {
|
|
382
|
-
for (const d of
|
|
415
|
+
for (const d of rtcDirs()) {
|
|
383
416
|
try {
|
|
384
417
|
const m = JSON.parse(readFileSync(join(d, 'package.json'), 'utf8'));
|
|
385
418
|
if (m?.name !== 'sigelo-transfer') continue;
|
|
@@ -388,458 +421,38 @@ export async function loadRtc() {
|
|
|
388
421
|
}
|
|
389
422
|
return null;
|
|
390
423
|
}
|
|
391
|
-
|
|
392
|
-
|
|
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
|
-
}
|
|
424
|
+
|
|
425
|
+
// ---------------------------------------------------------------- voice messages recorded in the page (voice.mjs)
|
|
397
426
|
|
|
398
427
|
/**
|
|
399
|
-
*
|
|
400
|
-
*
|
|
428
|
+
* The page's recordings on this computer (apps/contact/page.mjs hooks.transfers.rec): the pieces into
|
|
429
|
+
* <identity>.voice/.rec/<rec>.part (0600), kept whole as <identity>.voice/<name> (0600, the directory 0700), then
|
|
430
|
+
* sent by path as any file; not under <identity>.files/, which sendable refuses (files received). read(saved): a
|
|
431
|
+
* voice message that landed, to play: only under this identity's files or recordings, at most 16 MiB.
|
|
401
432
|
*/
|
|
402
|
-
export
|
|
403
|
-
const
|
|
404
|
-
const
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
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
|
-
}
|
|
433
|
+
export function voiceFiles(identity) {
|
|
434
|
+
const base = resolve(identity).replace(/\.json$/, ''), dir = `${base}.voice`, recs = join(dir, '.rec'), files = `${base}.files`;
|
|
435
|
+
const partOf = (rec) => { if (!/^[0-9a-f]{32}$/.test(rec)) fail('usage', 'rec: 32 hex digits'); return join(recs, `${rec}.part`); };
|
|
436
|
+
return {
|
|
437
|
+
async write(rec, offset, bytes) {
|
|
438
|
+
mkdirSync(recs, { recursive: true, mode: 0o700 });
|
|
439
|
+
const fd = openSync(partOf(rec), offset === 0 ? 'w' : 'r+', 0o600);
|
|
440
|
+
try { writeSync(fd, bytes, 0, bytes.length, offset); } finally { closeSync(fd); }
|
|
441
|
+
},
|
|
442
|
+
async keep(rec, name) {
|
|
443
|
+
const from = partOf(rec);
|
|
444
|
+
if (!existsSync(from)) fail('voice', 'no recording sent for this rec (POST /api/transfers/voice-part first)');
|
|
445
|
+
const clean = String(name).replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').slice(-200) || 'voice.webm', dot = clean.lastIndexOf('.');
|
|
446
|
+
let to = join(dir, clean);
|
|
447
|
+
for (let i = 2; existsSync(to) && i < 1000; i++) to = join(dir, dot > 0 ? `${clean.slice(0, dot)} (${i})${clean.slice(dot)}` : `${clean} (${i})`);
|
|
448
|
+
renameSync(from, to);
|
|
449
|
+
return { path: to };
|
|
450
|
+
},
|
|
451
|
+
async read(saved) {
|
|
452
|
+
const p = typeof saved === 'string' ? resolve(saved) : '';
|
|
453
|
+
if (!(p.startsWith(files + '/') || p.startsWith(dir + '/')) || p.includes('/../')) fail('voice', 'not a voice message of this identity');
|
|
454
|
+
if (statSync(p).size > 16 * 2 ** 20) fail('voice', 'too large for a voice message');
|
|
455
|
+
return new Uint8Array(readFileSync(p));
|
|
456
|
+
},
|
|
457
|
+
};
|
|
840
458
|
}
|
|
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 {} };
|