sigelo-contact 0.1.13 → 0.1.20

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.
Files changed (51) hide show
  1. package/README.md +13 -10
  2. package/call.mjs +727 -0
  3. package/carrier.mjs +1204 -137
  4. package/control.mjs +81 -22
  5. package/device.mjs +1 -1
  6. package/enrol.mjs +239 -43
  7. package/gen-carrier.mjs +4 -4
  8. package/gen-device.mjs +2 -2
  9. package/gen-envelope.mjs +3 -3
  10. package/gen-invite.mjs +3 -3
  11. package/gen-short.mjs +3 -3
  12. package/group.mjs +616 -0
  13. package/invite.mjs +63 -13
  14. package/kdf.mjs +1 -1
  15. package/link.mjs +24 -16
  16. package/package.json +49 -7
  17. package/page.mjs +1172 -70
  18. package/photo.mjs +37 -0
  19. package/platform-node.mjs +125 -18
  20. package/prekeys.mjs +10 -2
  21. package/public.mjs +93 -0
  22. package/relays.mjs +1 -1
  23. package/restore.mjs +3 -3
  24. package/rtc-web.mjs +95 -0
  25. package/short.mjs +31 -3
  26. package/store.mjs +147 -12
  27. package/test-carrier.mjs +138 -21
  28. package/test-device.mjs +1 -1
  29. package/test-enrol.mjs +157 -8
  30. package/test-envelope.mjs +16 -3
  31. package/test-file.mjs +5 -5
  32. package/test-group.mjs +413 -0
  33. package/test-invite.mjs +15 -2
  34. package/test-link.mjs +11 -8
  35. package/test-platform.mjs +5 -5
  36. package/test-presence.mjs +169 -0
  37. package/test-push.mjs +136 -0
  38. package/test-relay-lane.mjs +248 -0
  39. package/test-short.mjs +38 -12
  40. package/test-tier.mjs +6 -6
  41. package/test-transfer-web.mjs +246 -0
  42. package/test-transfer.mjs +463 -0
  43. package/test-voice.mjs +158 -0
  44. package/test-ws.mjs +5 -5
  45. package/transfer-engine.mjs +800 -0
  46. package/transfer-node.mjs +449 -0
  47. package/transfer-web.mjs +80 -0
  48. package/transfer.mjs +388 -0
  49. package/voice-web.mjs +113 -0
  50. package/voice.mjs +65 -0
  51. package/words-lock.mjs +115 -0
@@ -0,0 +1,449 @@
1
+ // SPDX-License-Identifier: MIT
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
+ //
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, 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()
19
+ //
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
+ // 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. 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
+ 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, resolve } from 'node:path';
38
+ import { fileURLToPath, pathToFileURL } from 'node:url';
39
+ import { TRANSFER_SEND, contactDir } from './carrier.mjs';
40
+ import { fail } from './kdf.mjs';
41
+ import { sendable, transact } from './platform-node.mjs';
42
+ import * as E from './transfer-engine.mjs';
43
+ import { CHUNK, MAX_SIZE, T, TRANSFER_LABEL, chunkLength, chunksOf, deframer, enframe, frames, readFrame } from './transfer.mjs';
44
+
45
+ export const { FILE_V, contactOf, directFor, trustOf } = E;
46
+ export { TRANSFER_LABEL };
47
+ const TOR_CONNECT_MS = 120_000, TOR_PROBE_MS = 1500;
48
+
49
+ export const transfersPath = (identity) => identity.replace(/\.json$/, '') + '.transfers.json';
50
+ const writeAtomic = (file, bytes) => { const tmp = `${file}.tmp`; rmSync(tmp, { force: true }); writeFileSync(tmp, bytes, { mode: 0o600, flag: 'wx' }); renameSync(tmp, file); };
51
+ const folder = (d) => mkdirSync(d, { recursive: true, mode: 0o700 });
52
+ const datasync = (fd) => { try { fdatasyncSync(fd); } catch {} };
53
+ const u8 = (b) => new Uint8Array(b.buffer, b.byteOffset, b.length);
54
+
55
+ // ---------------------------------------------------------------- this machine's io (transfer-engine.mjs)
56
+
57
+ const ios = new Map();
58
+ /** The io of an identity file, its carrier's files directory (filesDir: carrier.filesDir, or <identity>.files). */
59
+ export function nodeIo(identity, filesDir = identity.replace(/\.json$/, '') + '.files', torCfg = null, logPath = null) {
60
+ const key = `${identity}\n${filesDir}\n${torCfg ? JSON.stringify(torCfg) : ''}\n${logPath ?? ''}`;
61
+ if (ios.has(key)) return ios.get(key);
62
+ const file = transfersPath(identity), dir = join(filesDir, '.transfer');
63
+ const partOf = (id) => join(dir, `${id}.part`), haveOf = (id) => join(dir, `${id}.have`), listOf = (id, side) => join(dir, `${id}.${side}.list`);
64
+ const io = {
65
+ flushEach: 8,
66
+ lock: (fn) => transact(file, fn, 'sigelo transfer'),
67
+ read: () => (existsSync(file) ? readFileSync(file, 'utf8') : null),
68
+ write: (text) => writeAtomic(file, text),
69
+ have: {
70
+ read: (id) => { try { return u8(readFileSync(haveOf(id))); } catch { return null; } },
71
+ write: (id, bits) => { if (bits === null) rmSync(haveOf(id), { force: true }); else { folder(dir); writeAtomic(haveOf(id), bits); } },
72
+ },
73
+ list: {
74
+ read: (id, side) => { try { return u8(readFileSync(listOf(id, side))); } catch { return null; } },
75
+ write: (id, side, bytes) => { folder(dir); writeAtomic(listOf(id, side), bytes); },
76
+ drop: (id, side) => rmSync(listOf(id, side), { force: true }),
77
+ },
78
+ part: {
79
+ exists: (id) => existsSync(partOf(id)),
80
+ drop: (id) => rmSync(partOf(id), { force: true }),
81
+ async open(id) {
82
+ folder(dir);
83
+ closeSync(openSync(partOf(id), 'a', 0o600));
84
+ const fd = openSync(partOf(id), 'r+');
85
+ return {
86
+ async write(b, pos) { let o = 0; while (o < b.length) o += writeSync(fd, b, o, b.length - o, pos + o); },
87
+ async flush() { datasync(fd); },
88
+ async close() { try { closeSync(fd); } catch {} },
89
+ };
90
+ },
91
+ sha256: (id) => new Promise((ok, no) => {
92
+ const h = createHash('sha256');
93
+ createReadStream(partOf(id)).on('data', (d) => h.update(d)).on('end', () => ok(h.digest('hex'))).on('error', no);
94
+ }),
95
+ },
96
+ free() { folder(dir); const st = statfsSync(dir); return st.bavail * st.bsize; },
97
+ async land(r, c) {
98
+ const to = join(filesDir, contactDir(c));
99
+ folder(to);
100
+ for (let i = 0; i < 64; i++) {
101
+ const p = join(to, `${r.sha256.slice(0, 8)}-${i === 0 ? '' : `${i + 1}-`}${r.name}`);
102
+ try { linkSync(partOf(r.id), p); unlinkSync(partOf(r.id)); return p; } catch (e) {
103
+ if (e.code === 'EEXIST') continue;
104
+ if (!existsSync(p)) { renameSync(partOf(r.id), p); return p; }
105
+ }
106
+ }
107
+ fail('file_exists', `64 files of that name and hash are in ${to} already`);
108
+ },
109
+ async prepare({ path }) {
110
+ const f = sendable(path, { base: identity.replace(/\.json$/, ''), files: filesDir, log: logPath }, MAX_SIZE);
111
+ const { hashes, whole } = await hashFile(f.real, f.size);
112
+ // The file must still be the one hashed.
113
+ const s2 = statSync(f.real);
114
+ if (s2.size !== f.size || s2.mtimeMs !== f.mtimeMs) fail('file_changed', `${path} changed while it was read: send it again`);
115
+ return { file: f.real, name: f.name, size: f.size, mtimeMs: f.mtimeMs, hashes, whole };
116
+ },
117
+ async changed(r) { let st; try { st = statSync(r.file); } catch { return true; } return st.size !== r.size || st.mtimeMs !== r.mtimeMs; },
118
+ async source(r) {
119
+ const fh = await openFile(r.file, 'r');
120
+ return {
121
+ async read(i) {
122
+ const s = await fh.stat();
123
+ if (s.size !== r.size || s.mtimeMs !== r.mtimeMs) fail('file_changed', `${r.file} changed`);
124
+ const len = chunkLength(r.size, i), buf = Buffer.alloc(len);
125
+ const { bytesRead } = await fh.read(buf, 0, len, i * CHUNK);
126
+ if (bytesRead !== len) fail('file_changed', `${r.file} is shorter`);
127
+ return u8(buf);
128
+ },
129
+ close: () => fh.close(),
130
+ };
131
+ },
132
+ tor: torCfg ? torOf(torCfg) : null,
133
+ };
134
+ ios.set(key, io);
135
+ return io;
136
+ }
137
+ async function hashFile(file, size) {
138
+ const n = chunksOf(size), hashes = new Uint8Array(n * 32), whole = createHash('sha256'), fh = await openFile(file, 'r'), buf = Buffer.alloc(CHUNK);
139
+ try {
140
+ for (let i = 0; i < n; i++) {
141
+ const len = chunkLength(size, i);
142
+ const { bytesRead } = await fh.read(buf, 0, len, i * CHUNK);
143
+ if (bytesRead !== len) fail('file_changed', `${file} is shorter than it was`);
144
+ const b = buf.subarray(0, len);
145
+ hashes.set(createHash('sha256').update(b).digest(), i * 32);
146
+ whole.update(b);
147
+ }
148
+ } finally { await fh.close(); }
149
+ return { hashes, whole: whole.digest('hex') };
150
+ }
151
+ const ioOf = (o) => nodeIo(o.identity, o.carrier?.filesDir, null, o.carrier?.logPath ?? null);
152
+
153
+ // ---------------------------------------------------------------- the verbs (transfer-engine.mjs's, on this machine)
154
+
155
+ /** Load, purge, change (fn), save, under the file's lock. → fn's result. */
156
+ export const state = (identity, now, fn) => E.state(nodeIo(identity), now, fn);
157
+ export const send = (o) => E.send({ ...o, io: ioOf(o) });
158
+ export const prepare = (o) => E.prepare({ ...o, io: ioOf(o) });
159
+ export const sendTo = (o) => E.sendTo({ ...o, io: ioOf(o) });
160
+ export const fanOut = (o) => E.fanOut({ ...o, io: ioOf(o) });
161
+ export const accept = (o) => E.accept({ ...o, io: ioOf(o) });
162
+ /** A verb's resume: a stopped transfer offered again, a stuck one too (the engine makes the offer; only what .have lacks is asked). */
163
+ export const resume = (o) => E.resume({ ...o, io: ioOf(o) });
164
+ /** The sender's Retry: the file offered afresh under a new id, the old transfer cancelled. */
165
+ export const retry = (o) => E.retry({ ...o, io: ioOf(o) });
166
+ export const decline = (o) => E.decline({ ...o, io: ioOf(o) });
167
+ export const cancel = (o) => E.cancel({ ...o, io: ioOf(o) });
168
+ export const forget = (o) => E.forget({ ...o, io: ioOf(o) });
169
+ export const list = (o) => E.list({ ...o, io: ioOf(o) });
170
+ export const setDirect = (o) => E.setDirect({ ...o, io: ioOf(o) });
171
+ export const setAuto = (o) => E.setAuto({ ...o, io: ioOf(o) });
172
+ export const settings = ({ identity, patch, now }) => E.settings({ io: nodeIo(identity), patch, ...(now !== undefined && { now }) });
173
+ /** The STUN servers for a transfer with contact c: SIGELO_STUN, else this agent's relay host and the contact's, port 3478. */
174
+ export const stunFor = (carrier, c, env = process.env) => E.stunFor(carrier, c, env);
175
+ /**
176
+ * Without an engine (a CLI inbox, transfer list): the manifests and ends the carrier kept, taken and
177
+ * filed; offers, answers and onions stay for the engine of the next session. → the files now asked.
178
+ */
179
+ export const intake = ({ carrier, identity, compared }) => E.intake({ carrier, io: nodeIo(identity, carrier.filesDir), compared });
180
+
181
+ /** The engine on this machine: E.Engine over nodeIo, with Tor when a tor daemon is configured. */
182
+ export class Engine extends E.Engine {
183
+ constructor({ carrier, identity, rtc = loadRtc, tor = torConfig(), stun = null, pro, compared, maxServe, onEvent, retryMs, torConnectMs = TOR_CONNECT_MS, timer, fallbackMs, stallMs }) {
184
+ super({ carrier, io: nodeIo(identity, carrier.filesDir, tor, carrier.logPath ?? null), rtc, stun, env: process.env, pro, compared, maxServe, onEvent, retryMs, torConnectMs, timer, fallbackMs, stallMs });
185
+ this.identity = identity; this.torCfg = tor;
186
+ }
187
+ }
188
+
189
+ // ---------------------------------------------------------------- Tor (design §5a)
190
+
191
+ /** SIGELO_TOR → { control: [host, port], socks: [host, port], password } | null ("off"). */
192
+ export function torConfig(env = process.env) {
193
+ const v = (env.SIGELO_TOR ?? '').trim();
194
+ if (v === 'off') return null;
195
+ const [c, s] = (v || '127.0.0.1:9051,127.0.0.1:9050').split(',').map((x) => x.trim());
196
+ const hp = (x, d) => { const m = /^(.+):(\d{1,5})$/.exec(x ?? ''); return m ? [m[1], Number(m[2])] : d; };
197
+ return { control: hp(c, ['127.0.0.1', 9051]), socks: hp(s, ['127.0.0.1', 9050]), password: env.SIGELO_TOR_PASSWORD ?? null };
198
+ }
199
+ const connectTcp = (host, port, ms) => new Promise((ok, no) => {
200
+ const s = net.connect({ host, port });
201
+ const t = setTimeout(() => { s.destroy(); no(Object.assign(new Error(`tor: ${host}:${port} did not answer`), { check: 'tor' })); }, ms);
202
+ s.once('connect', () => { clearTimeout(t); ok(s); });
203
+ s.once('error', (e) => { clearTimeout(t); no(Object.assign(new Error(`tor: ${host}:${port}: ${e.code ?? e.message}`), { check: 'tor' })); });
204
+ });
205
+ /** An authenticated control connection: cmd(line) → the reply's lines (2xx), else throws check tor. */
206
+ export async function torControl(cfg, ms = TOR_PROBE_MS) {
207
+ const s = await connectTcp(cfg.control[0], cfg.control[1], ms);
208
+ let buf = '', waiting = [];
209
+ const replies = [];
210
+ s.setEncoding('utf8');
211
+ s.on('data', (d) => {
212
+ buf += d;
213
+ let i;
214
+ while ((i = buf.indexOf('\r\n')) >= 0) {
215
+ const line = buf.slice(0, i); buf = buf.slice(i + 2);
216
+ replies.push(line);
217
+ if (/^\d{3} /.test(line)) { const lines = replies.splice(0); const w = waiting.shift(); w?.(lines); }
218
+ }
219
+ });
220
+ s.on('error', () => {});
221
+ const cmd = (line) => new Promise((ok, no) => {
222
+ const t = setTimeout(() => no(Object.assign(new Error(`tor: no answer to ${line.split(' ')[0]}`), { check: 'tor' })), 15000);
223
+ waiting.push((lines) => {
224
+ clearTimeout(t);
225
+ const last = lines.at(-1);
226
+ if (!last.startsWith('2')) no(Object.assign(new Error(`tor: ${line.split(' ')[0]}: ${last}`), { check: 'tor' })); else ok(lines);
227
+ });
228
+ s.write(`${line}\r\n`);
229
+ });
230
+ try {
231
+ const info = (await cmd('PROTOCOLINFO 1')).join('\n');
232
+ const methods = /METHODS=([A-Z,]+)/.exec(info)?.[1].split(',') ?? [], cookieFile = /COOKIEFILE="((?:[^"\\]|\\.)*)"/.exec(info)?.[1]?.replace(/\\(.)/g, '$1');
233
+ let cookie = null;
234
+ if (cookieFile && (methods.includes('SAFECOOKIE') || methods.includes('COOKIE'))) { try { cookie = readFileSync(cookieFile); } catch {} }
235
+ if (methods.includes('NULL')) await cmd('AUTHENTICATE');
236
+ else if (cookie && methods.includes('SAFECOOKIE')) {
237
+ const cn = randomBytes(32), r = (await cmd(`AUTHCHALLENGE SAFECOOKIE ${cn.toString('hex')}`)).join(' ');
238
+ const sh = /SERVERHASH=([0-9A-Fa-f]{64})/.exec(r)?.[1], sn = /SERVERNONCE=([0-9A-Fa-f]{64})/.exec(r)?.[1];
239
+ if (!sh || !sn) fail('tor', 'tor: AUTHCHALLENGE answer unreadable');
240
+ const msg = Buffer.concat([cookie, cn, Buffer.from(sn, 'hex')]);
241
+ 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');
242
+ await cmd(`AUTHENTICATE ${createHmac('sha256', 'Tor safe cookie authentication controller-to-server hash').update(msg).digest('hex')}`);
243
+ } else if (cookie && methods.includes('COOKIE')) await cmd(`AUTHENTICATE ${cookie.toString('hex')}`);
244
+ else if (cfg.password !== null && methods.includes('HASHEDPASSWORD')) await cmd(`AUTHENTICATE "${cfg.password.replace(/[\\"]/g, '\\$&')}"`);
245
+ else fail('tor', `tor: cannot authenticate to the control port (methods ${methods.join(',') || 'none'}; set SIGELO_TOR_PASSWORD, or make the cookie readable)`);
246
+ } catch (e) { s.destroy(); throw e; }
247
+ return { cmd, close: () => { try { s.end('QUIT\r\n'); } catch {} s.destroy(); } };
248
+ }
249
+ /** What this side can do with Tor: { serve: a control port that authenticates, connect: a SOCKS port that answers }. */
250
+ export async function torCaps(cfg) {
251
+ if (!cfg) return { serve: false, connect: false };
252
+ const serve = await torControl(cfg).then((c) => { c.close(); return true; }, () => false);
253
+ const connect = await connectTcp(cfg.socks[0], cfg.socks[1], TOR_PROBE_MS).then((s) => { s.destroy(); return true; }, () => false);
254
+ return { serve, connect };
255
+ }
256
+ 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; };
257
+ /** A fresh x25519 client key for onion client authorization: { pub (base32, ADD_ONION's), priv (base64, ONION_CLIENT_AUTH_ADD's) }. */
258
+ export function clientKey() {
259
+ const { publicKey, privateKey } = generateKeyPairSync('x25519');
260
+ const x = Buffer.from(publicKey.export({ format: 'jwk' }).x, 'base64url'), d = Buffer.from(privateKey.export({ format: 'jwk' }).d, 'base64url');
261
+ return { pub: b32(x), priv: d.toString('base64') };
262
+ }
263
+ /** The base32 public key of a base64 x25519 private key (the fake tor of the tests checks client auth with it). */
264
+ export function clientPub(priv) {
265
+ const der = Buffer.concat([Buffer.from('302e020100300506032b656e04220420', 'hex'), Buffer.from(priv, 'base64')]);
266
+ return b32(Buffer.from(createPublicKey(createPrivateKey({ key: der, format: 'der', type: 'pkcs8' })).export({ format: 'jwk' }).x, 'base64url'));
267
+ }
268
+ /** SOCKS5 CONNECT to host:port through tor, tried until ms passed (a new onion takes 10 to 60 s to be reachable). */
269
+ export async function socksConnect(cfg, host, port, ms = TOR_CONNECT_MS) {
270
+ const until = Date.now() + ms;
271
+ for (;;) {
272
+ try { return await socksOnce(cfg, host, port); } catch (e) {
273
+ if (Date.now() + 3000 > until) throw e;
274
+ await new Promise((r) => setTimeout(r, 3000));
275
+ }
276
+ }
277
+ }
278
+ async function socksOnce(cfg, host, port) {
279
+ const s = await connectTcp(cfg.socks[0], cfg.socks[1], 10000);
280
+ // Everything the proxy sent, read n bytes at a time; what follows the reply is the stream's (kept for it).
281
+ let acc = Buffer.alloc(0), want = null, gone = false;
282
+ const onData = (d) => { acc = Buffer.concat([acc, d]); want?.(); };
283
+ const onClose = () => { gone = true; want?.(); };
284
+ s.on('data', onData); s.once('close', onClose);
285
+ const read = (n) => new Promise((ok, no) => {
286
+ const t = setTimeout(() => { want = null; no(Object.assign(new Error('tor: SOCKS gave no answer'), { check: 'tor' })); }, 60000);
287
+ want = () => {
288
+ if (acc.length >= n) { clearTimeout(t); want = null; const x = acc.subarray(0, n); acc = acc.subarray(n); ok(x); }
289
+ else if (gone) { clearTimeout(t); want = null; no(Object.assign(new Error('tor: SOCKS closed'), { check: 'tor' })); }
290
+ };
291
+ want();
292
+ });
293
+ try {
294
+ s.write(Buffer.from([5, 1, 0]));
295
+ const g = await read(2);
296
+ if (g[0] !== 5 || g[1] !== 0) fail('tor', 'tor: SOCKS refused the greeting');
297
+ const h = Buffer.from(host);
298
+ s.write(Buffer.concat([Buffer.from([5, 1, 0, 3, h.length]), h, Buffer.from([port >> 8, port & 255])]));
299
+ const r = await read(4);
300
+ if (r[1] !== 0) fail('tor', `tor: SOCKS could not reach ${host} (reply ${r[1]})`);
301
+ await read(r[3] === 1 ? 6 : r[3] === 4 ? 18 : (await read(1))[0] + 2);
302
+ s.pause(); s.off('data', onData); s.off('close', onClose);
303
+ s.removeAllListeners('error'); s.on('error', () => {});
304
+ if (acc.length) s.unshift(acc); // before any 'data' listener: read again by the stream's own
305
+ return s;
306
+ } catch (e) { s.destroy(); throw e; }
307
+ }
308
+ /** A net.Socket as transfer.mjs's channel: frames behind a u32 length. */
309
+ export function streamChannel(sock, first = []) {
310
+ const on = { frame: [], low: [], close: [] }, take = deframer();
311
+ let closed = false;
312
+ const shut = () => { if (closed) return; closed = true; for (const f of on.close) { try { f(); } catch {} } };
313
+ 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); };
314
+ // Paused by whoever handed it over: nothing is read before the frame handlers are on.
315
+ setImmediate(() => { for (const d of first) feed(d); sock.on('data', feed); sock.resume(); });
316
+ sock.on('drain', () => { for (const f of on.low) f(); });
317
+ sock.on('close', shut);
318
+ sock.on('error', () => {});
319
+ return {
320
+ send(f) { if (closed) throw new Error('closed'); sock.write(enframe(f)); },
321
+ buffered: () => sock.writableLength,
322
+ close() { sock.destroy(); shut(); },
323
+ on(e, fn) { on[e].push(fn); },
324
+ };
325
+ }
326
+
327
+ // 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.
328
+ function torOf(cfg) {
329
+ return {
330
+ caps: () => torCaps(cfg),
331
+ close(a) {
332
+ try { a.server?.close(); } catch {}
333
+ 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; }
334
+ 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; }
335
+ },
336
+ async serve(e, side, r, a) {
337
+ if (!a.tor.serve) return;
338
+ const token = randomBytes(32), key = a.peerTor?.serve ? clientKey() : null;
339
+ a.path = 'tor';
340
+ const server = net.createServer();
341
+ a.server = server;
342
+ await new Promise((ok, no) => { server.once('error', no); server.listen(0, '127.0.0.1', ok); });
343
+ const local = server.address().port, port = 1024 + (randomBytes(2).readUInt16BE() % 60000);
344
+ const ctl = await torControl(cfg);
345
+ let onion;
346
+ try {
347
+ 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}` : ''}`);
348
+ onion = /ServiceID=([a-z2-7]{56})/.exec(lines.join('\n'))?.[1] ?? fail('tor', 'tor: ADD_ONION gave no ServiceID');
349
+ } finally { ctl.close(); }
350
+ a.onion = onion;
351
+ server.on('connection', (sock) => {
352
+ // One stream, the one that proves the token first; any other is closed.
353
+ if (a.channel) { sock.destroy(); return; }
354
+ let got = Buffer.alloc(0);
355
+ const t = setTimeout(() => sock.destroy(), 30000);
356
+ const on = (d) => {
357
+ got = Buffer.concat([got, d]);
358
+ if (got.length < 4 + 33) return;
359
+ sock.pause(); sock.off('data', on); clearTimeout(t);
360
+ let f;
361
+ try { f = readFrame(new Uint8Array(got.subarray(4, 4 + 33))); } catch { sock.destroy(); return; }
362
+ 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; }
363
+ server.close();
364
+ const ch = streamChannel(sock, got.length > 37 ? [got.subarray(37)] : []);
365
+ a.channel = ch;
366
+ if (side === 'in') e.pull(r, a, ch); else e.serve(r, a, ch);
367
+ };
368
+ sock.on('data', on); sock.on('error', () => {});
369
+ });
370
+ 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 });
371
+ e.emit('onion', { id: r.id });
372
+ },
373
+ async connect(e, side, r, x, a) {
374
+ if (!a || a.attempt !== x.attempt || a.channel || !a.tor.connect) return;
375
+ a.path = 'tor';
376
+ try {
377
+ if (x.auth !== null && a.tor.serve) {
378
+ const ctl = await torControl(cfg);
379
+ try { await ctl.cmd(`ONION_CLIENT_AUTH_ADD ${x.onion} x25519:${x.auth}`); a.authAdded = x.onion; } finally { ctl.close(); }
380
+ }
381
+ const sock = await socksConnect(cfg, `${x.onion}.onion`, x.port, e.torConnectMs);
382
+ if (e.attempts.get(r.id) !== a) { sock.destroy(); return; }
383
+ sock.write(enframe(frames.token(Buffer.from(x.token, 'hex'))));
384
+ const ch = streamChannel(sock);
385
+ a.channel = ch;
386
+ if (side === 'in') e.pull(r, a, ch); else e.serve(r, a, ch);
387
+ } catch (err) {
388
+ if (e.attempts.get(r.id) !== a) return;
389
+ e.attempts.delete(r.id); e.closeAttempt(a);
390
+ if (side === 'in') {
391
+ e.interrupt(r.id, 'tor', err.message);
392
+ 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(() => {});
393
+ e.fail('in', r.id, 'no_path', `Tor: ${err.message}`);
394
+ }
395
+ }
396
+ },
397
+ };
398
+ }
399
+
400
+ // ---------------------------------------------------------------- the direct path's library
401
+
402
+ const HERE = dirname(fileURLToPath(import.meta.url));
403
+ /** sigelo-transfer's rtc.mjs, from beside sigelo-contact (an install's node_modules, or the repository's
404
+ * apps/transfer/, beside apps/contact/), or null: then transfers go over Tor only. Only a package named sigelo-transfer loads. */
405
+ export async function loadRtc() {
406
+ for (const d of [join(HERE, '..', 'transfer'), join(HERE, '..', 'sigelo-transfer'), join(HERE, 'node_modules', 'sigelo-transfer')]) {
407
+ try {
408
+ const m = JSON.parse(readFileSync(join(d, 'package.json'), 'utf8'));
409
+ if (m?.name !== 'sigelo-transfer') continue;
410
+ return await import(pathToFileURL(join(d, 'rtc.mjs')).href);
411
+ } catch {}
412
+ }
413
+ return null;
414
+ }
415
+
416
+ // ---------------------------------------------------------------- voice messages recorded in the page (voice.mjs)
417
+
418
+ /**
419
+ * The page's recordings on this computer (apps/contact/page.mjs hooks.transfers.rec): the pieces into
420
+ * <identity>.voice/.rec/<rec>.part (0600), kept whole as <identity>.voice/<name> (0600, the directory 0700), then
421
+ * sent by path as any file; not under <identity>.files/, which sendable refuses (files received). read(saved): a
422
+ * voice message that landed, to play: only under this identity's files or recordings, at most 16 MiB.
423
+ */
424
+ export function voiceFiles(identity) {
425
+ const base = resolve(identity).replace(/\.json$/, ''), dir = `${base}.voice`, recs = join(dir, '.rec'), files = `${base}.files`;
426
+ const partOf = (rec) => { if (!/^[0-9a-f]{32}$/.test(rec)) fail('usage', 'rec: 32 hex digits'); return join(recs, `${rec}.part`); };
427
+ return {
428
+ async write(rec, offset, bytes) {
429
+ mkdirSync(recs, { recursive: true, mode: 0o700 });
430
+ const fd = openSync(partOf(rec), offset === 0 ? 'w' : 'r+', 0o600);
431
+ try { writeSync(fd, bytes, 0, bytes.length, offset); } finally { closeSync(fd); }
432
+ },
433
+ async keep(rec, name) {
434
+ const from = partOf(rec);
435
+ if (!existsSync(from)) fail('voice', 'no recording sent for this rec (POST /api/transfers/voice-part first)');
436
+ const clean = String(name).replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').slice(-200) || 'voice.webm', dot = clean.lastIndexOf('.');
437
+ let to = join(dir, clean);
438
+ for (let i = 2; existsSync(to) && i < 1000; i++) to = join(dir, dot > 0 ? `${clean.slice(0, dot)} (${i})${clean.slice(dot)}` : `${clean} (${i})`);
439
+ renameSync(from, to);
440
+ return { path: to };
441
+ },
442
+ async read(saved) {
443
+ const p = typeof saved === 'string' ? resolve(saved) : '';
444
+ if (!(p.startsWith(files + '/') || p.startsWith(dir + '/')) || p.includes('/../')) fail('voice', 'not a voice message of this identity');
445
+ if (statSync(p).size > 16 * 2 ** 20) fail('voice', 'too large for a voice message');
446
+ return new Uint8Array(readFileSync(p));
447
+ },
448
+ };
449
+ }
@@ -0,0 +1,80 @@
1
+ // SPDX-License-Identifier: MIT
2
+ // Transfers in a page that holds its own identity (the phone app, design/transfer.md §10): the io of
3
+ // transfer-engine.mjs over the platform's files (the records, the chunk bitmaps and lists: small) and
4
+ // the shell's big-file bridge (the bytes: never in the page's storage, never a Blob held whole).
5
+ //
6
+ // const io = webIo({ files, big, base, profile }) files: the platform's (sync read/write/remove);
7
+ // big: platform.big (below); base: 'app/me.local'
8
+ // const X = webTransfers(io) the verbs with { carrier } as transfer-node.mjs's take them
9
+ //
10
+ // big (apps/web/platform-android.mjs, SigeloBridge "big-*"): every call names this profile.
11
+ // pick({images}) → { doc, name, size, mtime } | null the system's document picker (images: pictures only); the grant kept (a resume after a restart reads it)
12
+ // hash(doc) → { size, mtime, sha256, hashes } in the shell (each 1 MiB chunk and the whole), hashes: bytes
13
+ // stat(doc) → { size, mtime } read(doc, offset, length, { size, mtime }) → bytes (a range; file_changed when either moved)
14
+ // write(part, offset, bytes); flush(part); sha256(part) → hex; drop(part); free() → bytes
15
+ // land(part, name) → { uri, name } the partial moved into the phone's Downloads (MediaStore, pending until whole)
16
+ // part: the transfer id. Partials live in the app's private storage until they land.
17
+ import { CHUNK, chunkLength } from './transfer.mjs';
18
+ import { fail } from './kdf.mjs';
19
+ import * as E from './transfer-engine.mjs';
20
+
21
+ const enc = new TextEncoder(), dec = new TextDecoder();
22
+
23
+ export function webIo({ files, big, base = 'app/me.local', flushEach = 1 }) {
24
+ const file = `${base}.transfers.json`, dir = `${base}.files/.transfer/`;
25
+ let freeBytes = Infinity;
26
+ const refresh = () => { void big.free().then((n) => { if (Number.isFinite(n)) freeBytes = n; }, () => {}); };
27
+ refresh();
28
+ return {
29
+ flushEach,
30
+ lock: (fn) => fn(), // one owner per identity (platform.owner): this page alone writes it
31
+ read: () => { const b = files.read(file); return b === null ? null : dec.decode(b); },
32
+ write: (text) => files.write(file, enc.encode(text)),
33
+ have: {
34
+ read: (id) => files.read(`${dir}${id}.have`),
35
+ write: (id, bits) => { if (bits === null) files.remove(`${dir}${id}.have`); else files.write(`${dir}${id}.have`, Uint8Array.from(bits)); },
36
+ },
37
+ list: {
38
+ read: (id, side) => files.read(`${dir}${id}.${side}.list`),
39
+ write: (id, side, bytes) => files.write(`${dir}${id}.${side}.list`, Uint8Array.from(bytes)),
40
+ drop: (id, side) => files.remove(`${dir}${id}.${side}.list`),
41
+ },
42
+ part: {
43
+ async open(id) {
44
+ return { write: (b, pos) => big.write(id, pos, b), flush: () => big.flush(id), close: async () => { refresh(); } };
45
+ },
46
+ drop: (id) => { void big.drop(id).catch(() => {}); },
47
+ sha256: (id) => big.sha256(id),
48
+ },
49
+ free: () => { refresh(); return freeBytes; },
50
+ async land(r) { const x = await big.land(r.id, r.name); refresh(); return x.uri; },
51
+ async prepare({ doc }) {
52
+ if (typeof doc !== 'string' || doc === '') fail('usage', 'doc: a file picked on this phone');
53
+ const h = await big.hash(doc);
54
+ return { file: doc, name: h.name, size: h.size, mtimeMs: h.mtime, hashes: h.hashes, whole: h.sha256 };
55
+ },
56
+ async changed(r) { try { const s = await big.stat(r.file); return s.size !== r.size || s.mtime !== r.mtimeMs; } catch { return true; } },
57
+ async source(r) {
58
+ return {
59
+ read: (i) => big.read(r.file, i * CHUNK, chunkLength(r.size, i), { size: r.size, mtime: r.mtimeMs }),
60
+ close: async () => {},
61
+ };
62
+ },
63
+ tor: null, // no Tor on the phone (a later build: Orbot's SOCKS port)
64
+ };
65
+ }
66
+
67
+ /** The verbs over io, taking what transfer-node.mjs's take (identity is ignored: the io names the files). */
68
+ export function webTransfers(io, { compared = () => false, rtc = null } = {}) {
69
+ const w = (f) => (o) => f({ ...o, io });
70
+ return {
71
+ io,
72
+ send: w(E.send), accept: w(E.accept), resume: w(E.resume), retry: w(E.retry), decline: w(E.decline), cancel: w(E.cancel), forget: w(E.forget),
73
+ list: w(E.list), setDirect: w(E.setDirect), setAuto: w(E.setAuto), settings: ({ patch, now } = {}) => E.settings({ io, patch, ...(now !== undefined && { now }) }),
74
+ prepare: w(E.prepare), sendTo: w(E.sendTo), fanOut: w(E.fanOut), contactOf: E.contactOf, trustOf: E.trustOf,
75
+ intake: ({ carrier }) => E.intake({ carrier, io, compared }),
76
+ torCaps: async () => ({ serve: false, connect: false }), torConfig: () => null,
77
+ loadRtc: async () => rtc,
78
+ Engine: E.Engine,
79
+ };
80
+ }