Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

19.8 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Tests for fast files v2 (shared/fx2.js, shared/fx2-engine.js, its glue in shared/fastfile.js): a host and
// a guest in one process, each with its own files engine and real HTTPS, files both ways in ranges,
// receivers that only get adopt(), a bad hash, and every fallback to fx.
// Run with: node shared/test/fx2.js
'use strict';

const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const https = require('https');
const crypto = require('crypto');
const { execFileSync, fork } = require('child_process');
const P = require('../protocol.js');
const { FastFiles, receiverHook } = require('../fastfile.js');
const { Fx2 } = require('../fx2.js');
const { Engine, plan, PATH, HEADER } = require('../fx2-engine.js');

const T = P.T;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fx2-'));
execFileSync('openssl', ['req', '-x509', '-newkey', 'rsa:2048', '-nodes', '-days', '1', '-subj', '/CN=test',
  '-keyout', path.join(dir, 'key.pem'), '-out', path.join(dir, 'cert.pem')], { stdio: 'ignore' });
const key = fs.readFileSync(path.join(dir, 'key.pem'));
const cert = fs.readFileSync(path.join(dir, 'cert.pem'));
const fp = P.normFingerprint(new crypto.X509Certificate(cert).fingerprint256);
const token = P.randomHex(16);

const file = (name, bytes) => {
  const p = path.join(dir, name);
  fs.writeFileSync(p, crypto.randomBytes(bytes));
  return p;
};
const until = async (cond, what = 'condition', ms = 15000) => {
  const t = Date.now();
  while (!cond()) {
    if (Date.now() - t > ms) throw new Error(`timed out: ${what}`);
    await new Promise((r) => setTimeout(r, 5));
  }
};

// A receiver like the apps': its files (accepted before any byte), fx2's hook, and file.chunk /
// file.end for the fx way.
function receiver(name) {
  const r = { files: new Map(), done: new Map(), chunks: new Map(), ends: new Map() };
  r.accept = (id, size) => {
    const tmp = path.join(dir, `${name}-${id}.part`);
    const f = { id, tmp, size, got: 0, seq: 0, out: fs.createWriteStream(tmp, { flags: 'wx' }) };
    r.files.set(id, f);
    return f;
  };
  r.hook = receiverHook({
    find: (id) => r.files.get(id),
    end: (f) => f.out.end(() => { r.files.delete(f.id); r.done.set(f.id, { ok: true, verified: f.verified, data: fs.readFileSync(f.tmp) }); }),
    fail: (f, why) => { f.out.destroy(); r.files.delete(f.id); r.done.set(f.id, { ok: false, why }); },
  });
  r.deliver = (m) => {
    if (m.t === T.FILE_CHUNK) {
      const f = r.files.get(m.id);
      assert.ok(f && !f.fx2, `${name}: a chunk for ${m.id} comes only the fx way`);
      f.out.write(m.data);
      f.seq++;
      f.got += m.data.length;
      r.chunks.set(m.id, (r.chunks.get(m.id) || 0) + 1);
    }
    if (m.t === T.FILE_END) {
      r.ends.set(m.id, m);
      const f = r.files.get(m.id);
      if (f) f.out.end(() => { r.files.delete(m.id); r.done.set(m.id, { ok: true, verified: false, data: fs.readFileSync(f.tmp) }); });
    }
  };
  return r;
}

async function pair(opts = {}) {
  const host = { rx: receiver('host') };
  const guest = { rx: receiver('guest') };
  host.fx2 = opts.hostFx2 === false ? null : new Fx2({ tls: { key, cert } });
  guest.fx2 = opts.guestFx2 === false ? null : new Fx2();
  // As the peers do: a session needs the engines (they start on demand).
  if (host.fx2) host.fx2.need('session', true);
  if (guest.fx2) guest.fx2.need('session', true);
  if (host.fx2) assert.ok(await (host.fx2.whenReady(5000) || true), 'the host’s engine listens');
  const wire = (to) => (m) => setImmediate(() => { if (!to.fx.incoming(m)) to.rx.deliver(m); });
  // welcome's fx2 only when the guest's hello said fx2 and the host has an engine (as server.js does)
  const fx2On = !!(host.fx2 && guest.fx2);
  // Unencrypted file transfers (opts.plain: both allow it): the host's plain token, the guest's offer.
  host.fx = new FastFiles({
    session: () => ({ host: true, token, plainToken: host.plainToken || '', transport: 'ip', address: '127.0.0.1', fx2: fx2On }),
    deliver: (m) => host.rx.deliver(m), send: wire(guest), fx2: host.fx2,
  });
  guest.fx = new FastFiles({
    session: () => ({ host: false, token, transport: 'ip', address: '127.0.0.1', port: host.port, fp, fx2: fx2On, fx2Port: opts.fx2Port || (host.fx2 ? host.fx2.port : 0), plain: guest.plain || null }),
    deliver: (m) => guest.rx.deliver(m), send: wire(host), fx2: guest.fx2,
  });
  if (opts.plain) {
    host.fx.setPlain(true);
    guest.fx.setPlain(true);
    await until(() => host.fx.plainPort > 0 && (!host.fx2 || host.fx2.plainPort > 0), 'plain servers listen');
    // As server.js and link.js do: the offer in welcome, parsed by the guest.
    const ctx = { fx: token, fxPlainWanted: true };
    const welcome = host.fx.plainOffer(ctx);
    host.plainToken = ctx.fxPlain; // the host's session keeps it (server.js ctx.fxPlain)
    guest.plain = FastFiles.parsePlain(welcome);
    assert.ok(guest.plain && guest.plain.token === ctx.fxPlain, 'the plain offer parses');
    if (opts.plain === 'token') guest.plain.token = token; // the session's token must not work there
  }
  host.fx.receiver(host.rx.hook);
  guest.fx.receiver(guest.rx.hook);
  host.fx.reset();
  guest.fx.reset();
  host.send = wire(guest);
  guest.send = wire(host);
  await new Promise((resolve) => {
    host.server = https.createServer({ key, cert }, (req, res) => { if (!host.fx.request(req, res)) { res.writeHead(404); res.end(); } });
    host.server.listen(0, '127.0.0.1', resolve);
  });
  host.port = host.server.address().port;
  const close = () => {
    host.fx.reset(); guest.fx.reset(); host.server.close();
    if (host.fx2) host.fx2.close();
    if (guest.fx2) guest.fx2.close();
  };
  return { host, guest, close };
}

// As the apps do: offer (the receiver accepts), fx.send, then file.end with endFields.
async function send(from, to, id, p, end = (m) => m) {
  const size = fs.statSync(p).size;
  to.rx.accept(id, size);
  let counted = 0;
  const sha256 = await from.fx.send(id, p, size, (n) => { counted += n; });
  assert.strictEqual(counted, size, 'onBytes adds up');
  from.send(end({ t: T.FILE_END, id, sha256, ...from.fx.endFields(id) }));
}

async function arrived(to, id, p) {
  await until(() => to.rx.done.has(id), `${id} arrives`);
  const d = to.rx.done.get(id);
  assert.ok(d.ok, `${id}: ok (${d.why || ''})`);
  assert.ok(d.data.equals(fs.readFileSync(p)), `${id}: the same bytes`);
  return d;
}

(async () => {
  // The ranges.
  assert.deepStrictEqual(plan(0), [{ i: 0, off: 0, len: 0 }]);
  assert.deepStrictEqual(plan(8 * 1024 * 1024).length, 1, 'up to 8 MB: one range');
  const pl = plan(30 * 1024 * 1024 + 7);
  assert.strictEqual(pl.length, 4, 'bigger: 4 ranges');
  assert.strictEqual(pl.reduce((s, r) => s + r.len, 0), 30 * 1024 * 1024 + 7);
  for (let i = 1; i < pl.length; i++) assert.strictEqual(pl[i].off, pl[i - 1].off + pl[i - 1].len);

  {
    const { host, guest, close } = await pair();
    try {
      assert.ok(guest.fx.usable2() && host.fx.usable2(), 'fx2 on both');
      // Guest → host (PUT ranges): a big one, a small one, an empty one.
      const big = file('g-big.bin', 30 * 1024 * 1024 + 7);
      const small = file('g-small.bin', 5000);
      const empty = file('g-empty.bin', 0);
      const t0 = Date.now();
      await Promise.all([send(guest, host, 'a', big), send(guest, host, 'b', small), send(guest, host, 'c', empty)]);
      for (const [id, p] of [['a', big], ['b', small], ['c', empty]]) {
        const d = await arrived(host, id, p);
        assert.ok(d.verified, `${id}: adopted (the hashes checked by fastfile.js)`);
      }
      console.log(`  guest → host, 30 MB in 4 ranges: ${Date.now() - t0} ms`);
      assert.strictEqual(host.rx.chunks.size, 0, 'no file.chunk');
      assert.strictEqual(host.rx.ends.size, 0, 'file.end never reaches the receiver');
      // Host → guest (file.pull {fx2} + GET ranges).
      const hb = file('h-big.bin', 20 * 1024 * 1024 + 3);
      const hs = file('h-small.bin', 777);
      await Promise.all([send(host, guest, 'h1', hb), send(host, guest, 'h2', hs)]);
      assert.ok((await arrived(guest, 'h1', hb)).verified);
      assert.ok((await arrived(guest, 'h2', hs)).verified);
      assert.strictEqual(guest.rx.chunks.size, 0, 'no file.chunk');
      // A hash that doesn't match: the file fails.
      const bad = file('bad.bin', 10 * 1024 * 1024);
      await send(guest, host, 'x', bad, (m) => ({ ...m, fx2: m.fx2.map((h, i) => (i ? h : 'f'.repeat(64))) }));
      await until(() => host.rx.done.has('x'), 'x settles');
      assert.deepStrictEqual(host.rx.done.get('x'), { ok: false, why: 'checksum mismatch' });
      // Many small ones at once.
      const many = Array.from({ length: 64 }, (_, i) => file(`m${i}.bin`, 100 + i));
      await Promise.all(many.map((p, i) => send(guest, host, `m${i}`, p)));
      for (let i = 0; i < many.length; i++) await arrived(host, `m${i}`, many[i]);
      // Cancel mid-way: nothing more arrives, the next file still goes.
      const c1 = file('cancel.bin', 40 * 1024 * 1024);
      host.rx.accept('k', 40 * 1024 * 1024);
      const pk = guest.fx.send('k', c1, 40 * 1024 * 1024, () => {});
      await until(() => host.rx.files.get('k') && host.rx.files.get('k').fx2, 'k targeted');
      guest.fx.cancel('k');
      host.fx.incoming({ t: T.FILE_CANCEL, id: 'k' });
      await assert.rejects(pk, /Cancelled/);
      await send(guest, host, 'after', small);
      await arrived(host, 'after', small);
    } finally {
      close();
    }
  }

  // The guest's engine can't reach the host's (wrong port): before any byte, so this file and the
  // rest go the fx way.
  {
    const { host, guest, close } = await pair({ fx2Port: 1 });
    try {
      const p = file('fb1.bin', 3 * 1024 * 1024);
      await send(guest, host, 'f1', p);
      const d = await arrived(host, 'f1', p);
      assert.strictEqual(d.verified, false, 'the fx way: chunks, its own checksum');
      assert.ok(host.rx.chunks.get('f1') > 0);
      assert.ok(guest.fx.broken2 && !guest.fx.usable2(), 'fx2 off for the rest of the session');
      // Host → guest: the guest's GET fails before any byte, it says file.pull {failed, fx2}: fx.
      const q = file('fb2.bin', 2 * 1024 * 1024);
      await send(host, guest, 'f2', q);
      const e = await arrived(guest, 'f2', q);
      assert.strictEqual(e.verified, false);
      assert.ok(host.fx.broken2, 'the host too');
    } finally {
      close();
    }
  }

  // An app without fx2 (an older one): welcome has no fx2, everything goes the fx way.
  for (const opts of [{ guestFx2: false }, { hostFx2: false }]) {
    const { host, guest, close } = await pair(opts);
    try {
      assert.ok(!guest.fx.usable2() && !host.fx.usable2(), 'no fx2');
      const k = Object.keys(opts)[0];
      const p = file(`old-${k}.bin`, 1024 * 1024);
      await send(guest, host, `${k}1`, p);
      assert.strictEqual((await arrived(host, `${k}1`, p)).verified, false);
      await send(host, guest, `${k}2`, p);
      assert.strictEqual((await arrived(guest, `${k}2`, p)).verified, false);
    } finally {
      close();
    }
  }

  // Unencrypted file transfers (fxPlain): fx2 and fx, both ways, over plain HTTP.
  {
    const { host, guest, close } = await pair({ plain: true });
    try {
      let plainReqs = 0;
      const realReq = require('http').request;
      require('http').request = function (...a) { plainReqs++; return realReq.apply(this, a); };
      const big = file('p-big.bin', 20 * 1024 * 1024 + 1);
      await send(guest, host, 'p1', big);
      assert.ok((await arrived(host, 'p1', big)).verified, 'fx2 over plain HTTP, the hashes checked');
      await send(host, guest, 'p2', big);
      assert.ok((await arrived(guest, 'p2', big)).verified);
      require('http').request = realReq;
      // The engine's requests go from its own module: count what the plain servers took instead.
      assert.ok(host.fx2.plainPort > 0);
      // A bad hash is still caught.
      const bad = file('p-bad.bin', 9 * 1024 * 1024);
      await send(guest, host, 'p3', bad, (m) => ({ ...m, fx2: m.fx2.map((h, i) => (i ? h : 'f'.repeat(64))) }));
      await until(() => host.rx.done.has('p3'), 'p3 settles');
      assert.deepStrictEqual(host.rx.done.get('p3'), { ok: false, why: 'checksum mismatch' });
      void plainReqs;
    } finally {
      close();
    }
  }
  // fx over plain HTTP (an app without fx2, a phone): the guest's PUT and GET, verified by file.end.
  {
    const { host, guest, close } = await pair({ plain: true, guestFx2: false });
    try {
      const http = require('http');
      let plainReqs = 0;
      const realReq = http.request;
      http.request = function (...a) { plainReqs++; return realReq.apply(this, a); };
      const p = file('pfx.bin', 3 * 1024 * 1024 + 5);
      await send(guest, host, 'q1', p);
      assert.strictEqual((await arrived(host, 'q1', p)).verified, false, 'the fx way');
      await send(host, guest, 'q2', p);
      await arrived(guest, 'q2', p);
      http.request = realReq;
      assert.strictEqual(plainReqs, 2, 'both went over plain HTTP');
      assert.ok(host.rx.chunks.get('q1') > 0 && guest.rx.chunks.get('q2') > 0);
    } finally {
      close();
    }
  }
  // The plain servers take only the plain token: the session's is refused (403 before any byte),
  // and the file goes over TLS, as file.chunk would after that.
  {
    const { host, guest, close } = await pair({ plain: 'token', guestFx2: false });
    try {
      const p = file('ptok.bin', 1024 * 1024);
      host.rx.accept('t1', 1024 * 1024);
      await assert.rejects(guest.fx.send('t1', p, 1024 * 1024, () => {}), (e) => e.early && /403/.test(e.message));
      assert.ok(guest.fx.broken, 'refused on the plain server before a byte: the apps send it, and the rest, as file.chunk');
    } finally {
      close();
    }
  }
  // Turned off on the host: no offer, and its plain servers close.
  {
    const { host, close } = await pair({ plain: true });
    try {
      const ctx = { fx: token, fxPlainWanted: true };
      host.fx.setPlain(false);
      assert.deepStrictEqual(host.fx.plainOffer(ctx), {});
      assert.strictEqual(ctx.fxPlain, '');
      assert.strictEqual(host.fx.plainPort, 0);
      assert.deepStrictEqual(host.fx.plainOffer({ fx: token }), {}, 'a guest that didn’t ask gets none');
    } finally {
      close();
    }
  }

  // On demand: nothing runs until something needs it; it stops when nothing does, never during a
  // session or a job; a new start gets the server, the plain server and the tokens back.
  {
    const h = new Fx2({ tls: { key, cert }, idleMs: 50 });
    assert.strictEqual(h.state, 'stopped', 'not started by itself');
    h.setTokens([token]);
    h.setPlain(true);
    assert.strictEqual(h.state, 'stopped', 'settings alone don’t start it');
    const w = h.whenReady(5000);
    assert.ok(w && typeof w.then === 'function', 'a wait while it starts');
    assert.strictEqual(await w, true, 'it listens, its plain server too');
    assert.ok(h.port > 0 && h.plainPort > 0);
    assert.strictEqual(h.whenReady(), null, 'no wait once it listens');
    await until(() => h.state === 'stopped', 'stops when nothing needs it', 2000);
    assert.strictEqual(h.port, 0);
    h.need('session', true);
    await until(() => h.port > 0 && h.plainPort > 0, 'starts again for a session');
    await new Promise((r) => setTimeout(r, 200));
    assert.notStrictEqual(h.state, 'stopped', 'never stops during a session');
    // The tokens came back with it: a range request with the session's token isn't refused for it.
    const code = await new Promise((resolve) => {
      const req = https.request({ host: '127.0.0.1', port: h.port, path: '/twindesk/fx2/x?i=0&off=0&len=1&total=1', method: 'GET', rejectUnauthorized: false, headers: { 'x-twindesk-fx': token } }, (res) => { res.resume(); resolve(res.statusCode); });
      req.on('error', () => resolve(0));
      req.end();
    });
    assert.strictEqual(code, 404, 'the token works after a restart (404: no such file, not 403)');
    h.need('session', false);
    await until(() => h.state === 'stopped', 'stops after the session', 2000);
    // A job starts it (a guest's put/pull) and keeps it up until it settles.
    const g = new Fx2({ idleMs: 50 });
    const pf = file('lazy.bin', 1000);
    const job = g.put('lz', pf, 1000, { host: '127.0.0.1', port: 1, token, fp });
    assert.notStrictEqual(g.state, 'stopped', 'a job starts it');
    await assert.rejects(job, (e) => e.early, 'nothing listens there: early, the fx way');
    await until(() => g.state === 'stopped', 'stops after the job', 2000);
    h.close();
    g.close();
  }

  // A PUT killed while it waits for 'target' does not wedge the id: its range frees, the file
  // fails, and a retry of the same id gets a fresh 'want' instead of a stale 409.
  {
    const posts = [];
    const engine = new Engine((m) => posts.push(m));
    engine.handle({ op: 'listen', tls: { key, cert } });
    await until(() => engine.port > 0, 'the engine listens');
    engine.handle({ op: 'tokens', list: [token] });
    const put = (id) => https.request({
      host: '127.0.0.1', port: engine.port, method: 'PUT', agent: false, rejectUnauthorized: false,
      path: `${PATH}${id}?i=0&off=0&len=5000&total=5000`,
      headers: { [HEADER]: token, 'content-length': 5000 },
    });
    const first = put('w');
    first.on('error', () => {});
    first.write(crypto.randomBytes(5000));
    await until(() => posts.some((m) => m.ev === 'want' && m.id === 'w'), 'want posted');
    first.destroy();
    await until(() => posts.some((m) => m.ev === 'failed' && m.id === 'w'), 'the file fails');
    assert.strictEqual(engine.incoming.size, 0, 'nothing left of w');
    // 'target' arriving late is a no-op now; a retry starts over.
    const target = path.join(dir, 'w.bin');
    engine.handle({ op: 'target', id: 'w', path: target });
    posts.length = 0;
    const body = crypto.randomBytes(5000);
    const status = new Promise((resolve) => {
      const second = put('w');
      second.on('response', (res) => { res.resume(); res.on('end', () => resolve(res.statusCode)); });
      second.on('error', () => resolve(0));
      second.end(body);
    });
    await until(() => posts.some((m) => m.ev === 'want' && m.id === 'w'), 'want again');
    engine.handle({ op: 'target', id: 'w', path: target });
    assert.strictEqual(await status, 200, 'the retried PUT is taken');
    await until(() => posts.some((m) => m.ev === 'done' && m.id === 'w'), 'w completes');
    assert.ok(fs.readFileSync(target).equals(body), 'the bytes arrived');
    // The idle reaper drops a file nobody finishes and a served file nobody GETs.
    engine.incoming.set('stale', { size: 1, path: 'x', fd: null, hashes: [undefined], left: 1, queue: [], reqs: new Set(), busy: new Set(), got: 0, touched: 0 });
    engine.handle({ op: 'serve', id: 's1', path: target, size: 5000 });
    engine.serving.get('s1').touched = 0;
    posts.length = 0;
    engine._reap();
    assert.ok(!engine.incoming.has('stale') && !engine.serving.has('s1'), 'idle entries reaped');
    assert.strictEqual(posts.filter((m) => m.ev === 'failed').length, 2, 'both reported failed');
    engine.handle({ op: 'reset' });
    engine.server.close();
  }

  // The engine as a process of its own (a utility process in the app; a forked node here).
  {
    const child = fork(path.join(__dirname, '..', 'fx2-engine.js'), [], { stdio: 'ignore' });
    const port = await new Promise((resolve) => {
      child.on('message', (m) => m.ev === 'port' && resolve(m.port));
      child.send({ op: 'listen', tls: { key: key.toString(), cert: cert.toString() } });
    });
    assert.ok(port > 0, 'the forked engine listens');
    child.kill();
  }

  // Windows lets the folder go only once every file in it is closed: a failed transfer's stream can
  // stay open until the process ends, so the cleanup there is best-effort (the temp folder).
  try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch (e) { if (process.platform !== 'win32') throw e; }
  console.log('fx2: ok');
  process.exit(0);
})().catch((e) => {
  console.error(e);
  process.exit(1);
});