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.

7.9 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// The phone's internet on this computer (shared/phonenet.js, #361): a stand-in for the phone's relay
// (PhoneNet.kt's TDN1 handshake), and this computer's proxy in front of it: HTTP CONNECT, a plain
// HTTP request and SOCKS5 reach a server through the "phone"; a wrong secret or a replayed hello
// is refused; the system proxy is set while on and put back when it stops, and after a crash.
// Run with: node --test shared/test/phonenet.test.js
'use strict';

const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const net = require('net');
const http = require('http');
const crypto = require('crypto');
const { EventEmitter } = require('events');
const { test } = require('node:test');

const { PhoneNet, mac } = require('../phonenet.js');

const tick = (ms = 20) => new Promise((r) => setTimeout(r, ms));

// The phone's relay as PhoneNet.kt does it.
function fakePhone() {
  const seen = new Set();
  const st = { token: '', opened: [] };
  const srv = net.createServer((c) => {
    let buf = '';
    const onData = (d) => {
      buf += d.toString('latin1');
      const n = buf.indexOf('\n');
      if (n < 0) return;
      c.removeListener('data', onData);
      const [tag, nonce, host, port, got] = buf.slice(0, n).split(' ');
      const rest = Buffer.from(buf.slice(n + 1), 'latin1');
      const want = st.token && mac(st.token, `c${nonce} ${host} ${port}`);
      if (tag !== 'TDN1' || got !== want || seen.has(nonce)) return void c.destroy();
      seen.add(nonce);
      st.opened.push(`${host}:${port}`);
      const up = net.connect(Number(port), host === 'localhost' ? '127.0.0.1' : host, () => {
        c.write('OK\n');
        if (rest.length) up.write(rest);
        c.pipe(up);
        up.pipe(c);
      });
      up.on('error', () => { c.end('ERR refused\n'); });
      c.on('error', () => {});
    };
    c.on('data', onData);
  });
  return new Promise((r) => srv.listen(0, '127.0.0.1', () => { st.port = srv.address().port; st.srv = srv; r(st); }));
}

function makeHub(phone) {
  const server = new EventEmitter();
  const sent = [];
  server.sendToClient = (m) => { sent.push(m); if (m.t === 'phonenet' && m.on) phone.token = m.token; };
  const hub = { settings: { phoneNet: true }, save() {}, server, phone: { name: 'Phone', address: '127.0.0.2', transport: 'ip' } };
  return { hub, sent, say: (m) => server.emit('t:phonenet.state', m, hub.phone) };
}

const site = () => new Promise((r) => {
  const s = http.createServer((req, res) => res.end(`hello ${req.url}`));
  s.listen(0, '127.0.0.1', () => r(s));
});

test('through the phone: CONNECT, plain HTTP and SOCKS5; the proxy set and put back', async () => {
  const phone = await fakePhone();
  const web = await site();
  const webPort = web.address().port;
  const calls = [];
  const sysProxy = { set: async (p) => { calls.push(['set', p]); return { was: 'direct' }; }, restore: async (s) => { calls.push(['restore', s.was]); } };
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'phonenet-'));
  const stateFile = path.join(dir, 'proxy.json');
  const { hub, sent, say } = makeHub(phone);
  const pn = new PhoneNet(hub, { sysProxy, stateFile, log: () => {} });
  pn.started();
  say({ can: true, state: 'off' });
  assert.strictEqual(sent[0].t, 'phonenet');
  assert.ok(sent[0].on && /^[0-9a-f]{64}$/.test(sent[0].token));
  // 127.0.0.2 doesn't answer here: the address the phone gave is tried next.
  say({ can: true, state: 'on', port: phone.port, addrs: ['127.0.0.1'], vpn: true });
  for (let i = 0; i < 50 && !pn.proxied; i++) await tick();
  assert.ok(pn.proxied);
  assert.deepStrictEqual(calls, [['set', pn.port]]);
  assert.ok(fs.existsSync(stateFile));
  assert.strictEqual(pn.view.state, 'on');
  assert.strictEqual(pn.view.vpn, true);

  // A plain request with its whole URL.
  const plain = await new Promise((resolve, reject) => {
    http.get({ host: '127.0.0.1', port: pn.port, path: `http://localhost:${webPort}/a?b=1`, headers: { Host: `localhost:${webPort}` } }, (res) => {
      let b = ''; res.on('data', (d) => { b += d; }); res.on('end', () => resolve(b));
    }).on('error', reject);
  });
  assert.strictEqual(plain, 'hello /a?b=1');

  // CONNECT, then HTTP inside the tunnel.
  const tunneled = await new Promise((resolve, reject) => {
    const s = net.connect(pn.port, '127.0.0.1', () => s.write(`CONNECT localhost:${webPort} HTTP/1.1\r\nHost: localhost:${webPort}\r\n\r\n`));
    let b = '';
    let sentInner = false;
    s.on('data', (d) => {
      b += d;
      if (!sentInner && b.includes('\r\n\r\n')) { assert.ok(b.startsWith('HTTP/1.1 200')); sentInner = true; b = ''; s.write(`GET /t HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n`); }
    });
    s.on('end', () => resolve(b));
    s.on('error', reject);
  });
  assert.ok(tunneled.endsWith('hello /t'));

  // SOCKS5 by name.
  const socks = await new Promise((resolve, reject) => {
    const s = net.connect(pn.port, '127.0.0.1', () => s.write(Buffer.from([5, 1, 0])));
    let step = 0;
    let b = Buffer.alloc(0);
    s.on('data', (d) => {
      b = Buffer.concat([b, d]);
      if (step === 0 && b.length >= 2) {
        assert.deepStrictEqual([...b.subarray(0, 2)], [5, 0]);
        b = b.subarray(2); step = 1;
        const name = Buffer.from('localhost');
        const port = Buffer.alloc(2); port.writeUInt16BE(webPort);
        s.write(Buffer.concat([Buffer.from([5, 1, 0, 3, name.length]), name, port]));
      }
      if (step === 1 && b.length >= 10) {
        assert.strictEqual(b[1], 0);
        b = b.subarray(10); step = 2;
        s.write('GET /s HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n');
      }
    });
    s.on('end', () => resolve(b.toString()));
    s.on('error', reject);
  });
  assert.ok(socks.endsWith('hello /s'));
  assert.ok(pn.view.down > 0 && pn.view.up > 0);

  // A wrong secret and a replayed hello get nothing.
  const refused = (line) => new Promise((resolve) => {
    const s = net.connect(phone.port, '127.0.0.1', () => s.write(line));
    s.on('data', () => { resolve(false); s.destroy(); });
    s.on('close', () => resolve(true));
    s.on('error', () => resolve(true));
  });
  const nonce = crypto.randomBytes(16).toString('hex');
  assert.strictEqual(await refused(`TDN1 ${nonce} localhost ${webPort} ${mac('f'.repeat(64), `c${nonce} localhost ${webPort}`)}\n`), true);
  const good = `TDN1 ${nonce} localhost ${webPort} ${mac(phone.token, `c${nonce} localhost ${webPort}`)}\n`;
  assert.strictEqual(await refused(good), false);
  assert.strictEqual(await refused(good), true, 'the same hello again');

  // Switched off: the phone told, the proxy put back, the file gone.
  pn.act('set', { on: false });
  await tick(50);
  assert.deepStrictEqual(sent[sent.length - 1], { t: 'phonenet', on: false });
  assert.deepStrictEqual(calls[calls.length - 1], ['restore', 'direct']);
  assert.ok(!fs.existsSync(stateFile));
  assert.strictEqual(pn.server, null);
  web.closeAllConnections();
  web.close();
  phone.srv.close();
});

test('a crash left the proxy changed: put back at the next start', async () => {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'phonenet-'));
  const stateFile = path.join(dir, 'proxy.json');
  fs.writeFileSync(stateFile, JSON.stringify({ was: 'pac' }));
  const got = [];
  const { hub } = makeHub({});
  new PhoneNet(hub, { sysProxy: { set: async () => ({}), restore: async (s) => { got.push(s.was); } }, stateFile, log: () => {} });
  await tick(30);
  assert.deepStrictEqual(got, ['pac']);
  assert.ok(!fs.existsSync(stateFile));
});

test('the phone over Bluetooth or a phone that can’t: nothing asked', async () => {
  const { hub, sent, say } = makeHub({});
  const pn = new PhoneNet(hub, { log: () => {} });
  pn.started();
  say({ can: false });
  assert.strictEqual(sent.length, 0);
  assert.strictEqual(pn.view.state, 'off');
  hub.phone.transport = 'ble';
  say({ can: true, state: 'off' });
  assert.strictEqual(sent.length, 0);
  assert.strictEqual(pn.view.state, 'error');
});