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.

18.8 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// The phone's internet on this computer (#361): the connected phone makes this computer's
// connections, so they leave through its mobile data or Wi-Fi and through a VPN running on it
// (NetBird, WireGuard, a work VPN), on the same Wi-Fi or the phone's hotspot. No hotspot, root or
// per-app proxy: while it's on, this computer's system proxy points at a small proxy here.
//
//   - Only a phone that says it can (phonenet.state {can: true} as its session starts: an older
//     phone never does, so nothing shows). Connection › Use the phone's internet
//     (settings.hub.phoneNet, off until switched on; one-to-one and Multi-device, via phonehub.js).
//   - Here: 127.0.0.1:<port>, HTTP (CONNECT and plain requests) and SOCKS5 on the same port. Each
//     connection is one TCP connection the phone opens (PhoneNet.kt): the names are looked up there,
//     so a VPN's private names and addresses work.
//   - The system proxy: Windows (the user's Internet settings, through the helper), Linux with
//     GNOME's settings (gsettings: GNOME, Cinnamon, Budgie, Pantheon, Unity). What was there is
//     kept in a file and put back when it stops, when the phone goes, or at the next start after a
//     crash. Elsewhere (the Mac, KDE, others) the card gives the address to set by hand.
//   - The phone's relay listens on its own networks; a connection proves it knows the session's
//     secret for that very host and port, once (a nonce): TDN1 <nonce> <host> <port> <HMAC>.
//     Apps that ignore the system proxy (some games, UDP) keep this computer's own network.
//
// computer -> phone: phonenet {on: true, token} | {on: false}
// phone -> computer: phonenet.state {can, state: 'off'|'on'|'error', why?, port, addrs: [IPv4], vpn}
//
// Events: 'change' (view).
'use strict';

const net = require('net');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { EventEmitter } = require('events');

const P = require('./protocol.js');

const T = { NET: P.T.PHONENET, STATE: P.T.PHONENET_STATE };
const PORTS = [31480, 31481, 31482, 0]; // this computer's proxy: the same one each time when free (a crash leaves it set)
const CONNECT_MS = 12_000;
const STATES = ['off', 'on', 'error'];
// Local addresses stay direct: Windows' Internet settings take wildcards, GNOME's CIDR ranges.
const BYPASS = ['localhost', '127.0.0.1', '::1', '*.local', '10.*', '192.168.*', '172.16.*', '169.254.*'];
const BYPASS_GNOME = ['localhost', '127.0.0.0/8', '::1', '*.local', '10.0.0.0/8', '192.168.0.0/16', '172.16.0.0/12', '169.254.0.0/16'];
const str = (v, n = 200) => (typeof v === 'string' ? v.slice(0, n) : '');
const mac = (key, s) => crypto.createHmac('sha256', key).update(s).digest('hex');
const HOST_RE = /^[A-Za-z0-9._:\-[\]]{1,253}$/;

// ---- the system proxy ----

// What sets it here: {set(port) -> saved, restore(saved), manual} or null (by hand).
// winHelper: the Windows helper's request(cmd) -> reply (sysProxyGet / sysProxySet).
function systemProxy({ platform = process.platform, winHelper = null, run = null } = {}) {
  if (platform === 'win32' && winHelper) {
    return {
      async set(port) {
        const r = await winHelper({ cmd: 'sysProxyGet' });
        const prev = r && r.proxy;
        if (!prev) throw new Error('This TwinDesk helper can’t set the proxy (update TwinDesk)');
        await winHelper({ cmd: 'sysProxySet', enable: true, server: `127.0.0.1:${port}`, bypass: BYPASS.join(';') + ';<local>', pac: '' });
        return { win: prev };
      },
      async restore(saved) {
        const p = saved && saved.win;
        if (!p) return;
        await winHelper({ cmd: 'sysProxySet', enable: !!p.enable, server: str(p.server, 2000), bypass: str(p.bypass, 4000), pac: str(p.pac, 2000) });
      },
    };
  }
  if (platform === 'linux' && run && process.env.XDG_CURRENT_DESKTOP && !/KDE|LXQt/i.test(process.env.XDG_CURRENT_DESKTOP)) {
    const KEYS = [
      ['org.gnome.system.proxy', 'mode'], ['org.gnome.system.proxy', 'ignore-hosts'],
      ['org.gnome.system.proxy.http', 'host'], ['org.gnome.system.proxy.http', 'port'],
      ['org.gnome.system.proxy.https', 'host'], ['org.gnome.system.proxy.https', 'port'],
      ['org.gnome.system.proxy.socks', 'host'], ['org.gnome.system.proxy.socks', 'port'],
    ];
    const get = async (s, k) => {
      const r = await run('gsettings', ['get', s, k]);
      if (!r || r.code !== 0) throw new Error('gsettings isn’t there');
      return String(r.out || '').trim();
    };
    const put = (s, k, v) => run('gsettings', ['set', s, k, v]);
    return {
      async set(port) {
        const prev = {};
        for (const [s, k] of KEYS) prev[`${s} ${k}`] = await get(s, k);
        const hosts = '[' + BYPASS_GNOME.map((h) => `'${h}'`).join(', ') + ']';
        for (const s of ['org.gnome.system.proxy.http', 'org.gnome.system.proxy.https']) { await put(s, 'host', "'127.0.0.1'"); await put(s, 'port', String(port)); }
        await put('org.gnome.system.proxy.socks', 'host', "''"); // HTTP is enough; a SOCKS line here makes some apps skip HTTPS's
        await put('org.gnome.system.proxy', 'ignore-hosts', hosts);
        await put('org.gnome.system.proxy', 'mode', "'manual'");
        return { gs: prev };
      },
      async restore(saved) {
        const p = saved && saved.gs;
        if (!p) return;
        for (const [s, k] of KEYS) {
          const v = p[`${s} ${k}`];
          if (typeof v === 'string' && v.length < 4000) await put(s, k, v);
        }
      },
    };
  }
  return null;
}

// A command now, for gsettings: quick, and done before the app quits (no promise left behind).
function runSync(cmd, args) {
  try {
    const out = require('child_process').execFileSync(cmd, args, { timeout: 3000, stdio: ['ignore', 'pipe', 'ignore'] });
    return { code: 0, out: out.toString() };
  } catch {
    return { code: 1, out: '' };
  }
}

// ---- the relay ----

class PhoneNet extends EventEmitter {
  // hub: phonehub.js (settings, save, phone, server). sysProxy: systemProxy() or null.
  // stateFile: where the system proxy as it was is kept while it's changed.
  constructor(hub, { sysProxy = null, stateFile = '', log = (s) => console.log(`[phonenet] ${s}`) } = {}) {
    super();
    Object.assign(this, { hub, sysProxy, stateFile, log });
    this.can = false;
    this.phone = { state: 'off', why: '', port: 0, addrs: [], vpn: false };
    this.token = '';
    this.sent = false;
    this.server = null;
    this.port = 0;
    this.proxied = false; // the system proxy is ours now
    this.error = '';
    this.stats = { down: 0, up: 0, open: 0, failed: 0 };
    this.socks = new Set();
    this.busy = false;
    const on = (t, fn) => hub.server.on(`t:${t}`, (m, ctx) => ctx === hub.phone && fn(m));
    on(T.STATE, (m) => this._state(m));
    this._recover();
  }

  get enabled() {
    return this.hub.settings.phoneNet === true;
  }

  // A crash or a power cut left the proxy pointing here: put back what was there.
  _recover() {
    if (!this.stateFile || !this.sysProxy) return;
    let saved = null;
    try { saved = JSON.parse(fs.readFileSync(this.stateFile, 'utf8')); } catch { return; }
    this.log('putting back the system proxy as it was before the last run');
    this.sysProxy.restore(saved).then(() => { try { fs.unlinkSync(this.stateFile); } catch {} }, (e) => this.log(`couldn’t put back the proxy: ${e.message}`));
  }

  // ---- the session ----

  started() {
    this.can = false;
    this.sent = false;
    this.phone = { state: 'off', why: '', port: 0, addrs: [], vpn: false };
    this.error = '';
    this.emit('change');
  }

  stopped() {
    this.can = false;
    this._stop('session ended');
    this.emit('change');
  }

  _state(m) {
    const was = this.can;
    this.can = m.can === true;
    const addrs = Array.isArray(m.addrs) ? m.addrs.filter((a) => typeof a === 'string' && net.isIPv4(a)).slice(0, 8) : [];
    this.phone = {
      state: STATES.includes(m.state) ? m.state : 'off', why: str(m.why),
      port: Number.isInteger(m.port) && m.port > 0 && m.port < 65536 ? m.port : 0, addrs, vpn: m.vpn === true,
    };
    if (this.can && !was) this.log('the phone can share its internet');
    this.sync();
    this.emit('change');
  }

  // From the window: {a: 'set', on}.
  act(a, r = {}) {
    if (a !== 'set') return;
    this.hub.settings.phoneNet = !!r.on;
    this.hub.save();
    this.error = '';
    this.sync();
    this.emit('change');
  }

  sync() {
    const ctx = this.hub.phone;
    const want = !!(this.enabled && ctx && this.can);
    if (!want) {
      if (this.sent || this.server || this.proxied) this._stop(this.enabled ? 'the phone went' : 'switched off');
      return;
    }
    if (ctx.transport === 'ble') return this._err('The phone is connected through Bluetooth: its internet needs the same Wi-Fi or its hotspot');
    if (!this.sent) {
      this.token = crypto.randomBytes(32).toString('hex');
      this.sent = true;
      this.hub.server.sendToClient({ t: T.NET, on: true, token: this.token });
      this.log(`asked ${ctx.name || 'the phone'} to share its internet`);
    }
    if (this.phone.state === 'on' && this.phone.port && !this.busy && (!this.server || !this.proxied)) {
      this.busy = true;
      this._start().catch((e) => this._err(e.message)).then(() => { this.busy = false; this.emit('change'); });
    }
  }

  _err(e) {
    if (this.error === e) return;
    this.error = e;
    if (e) this.log(e);
    this.emit('change');
  }

  async _start() {
    await this._listen();
    if (!this.enabled || !this.hub.phone) return;
    if (this.sysProxy && !this.proxied) {
      const saved = await this.sysProxy.set(this.port);
      if (this.stateFile) {
        try { fs.mkdirSync(path.dirname(this.stateFile), { recursive: true }); fs.writeFileSync(this.stateFile, JSON.stringify(saved)); } catch {}
      }
      this.saved = saved;
      this.proxied = true;
      this.log(`this computer's proxy is 127.0.0.1:${this.port} now`);
    }
    this.error = '';
  }

  async _listen() {
    if (this.server) return;
    for (const p of PORTS) {
      try {
        await new Promise((resolve, reject) => {
          const srv = net.createServer((sock) => this._accept(sock));
          srv.once('error', reject);
          srv.listen(p, '127.0.0.1', () => {
            srv.removeListener('error', reject);
            srv.on('error', (e) => this.log(`proxy: ${e.message}`));
            this.server = srv;
            this.port = srv.address().port;
            resolve();
          });
        });
        return;
      } catch (e) {
        if (p === 0) throw e;
      }
    }
  }

  // Where the phone is: the session's own address first (unless it's the cable's 127.0.0.1),
  // then the addresses it gave.
  _targets() {
    const ctx = this.hub.phone;
    const out = [];
    const a = ctx && typeof ctx.address === 'string' ? ctx.address.replace(/^::ffff:/, '') : '';
    if (a && net.isIPv4(a) && !a.startsWith('127.')) out.push(a);
    for (const x of this.phone.addrs) if (!out.includes(x)) out.push(x);
    return out;
  }

  // One connection through the phone to host:port: a socket already past the phone's OK.
  dial(host, port) {
    return new Promise((resolve, reject) => {
      const targets = this._targets();
      const token = this.token;
      if (!token || !this.phone.port || !targets.length) return reject(new Error('the phone isn’t sharing'));
      if (!HOST_RE.test(host) || !(port > 0 && port < 65536)) return reject(new Error('bad address'));
      let i = 0;
      const next = (why) => {
        if (i >= targets.length) return reject(new Error(why || 'the phone didn’t answer'));
        const ip = targets[i++];
        const s = net.connect({ host: ip, port: this.phone.port });
        let buf = '';
        let done = false;
        const timer = setTimeout(() => fail('timed out'), CONNECT_MS);
        const fail = (w) => { if (done) return; done = true; clearTimeout(timer); s.destroy(); w && /^ERR/.test(w) ? reject(new Error(w.slice(4) || 'refused')) : next(w); };
        s.setNoDelay(true);
        s.on('error', (e) => fail(e.code || e.message));
        s.on('connect', () => {
          const nonce = crypto.randomBytes(16).toString('hex');
          s.write(`TDN1 ${nonce} ${host} ${port} ${mac(token, `c${nonce} ${host} ${port}`)}\n`);
        });
        const onData = (d) => {
          buf += d.toString('latin1');
          const n = buf.indexOf('\n');
          if (n < 0) { if (buf.length > 200) fail('bad answer'); return; }
          const line = buf.slice(0, n).trim();
          if (line !== 'OK') return fail(line.startsWith('ERR') ? line : `ERR ${line.slice(0, 80)}`);
          done = true;
          clearTimeout(timer);
          s.removeListener('data', onData);
          s.removeAllListeners('error');
          const rest = Buffer.from(buf.slice(n + 1), 'latin1');
          if (rest.length) s.unshift(rest);
          resolve(s);
        };
        s.on('data', onData);
        s.on('close', () => fail('closed'));
      };
      next();
    });
  }

  // ---- the proxy here ----

  _accept(sock) {
    sock.setNoDelay(true);
    sock.on('error', () => {});
    this.socks.add(sock);
    sock.on('close', () => this.socks.delete(sock));
    sock.once('data', (d) => {
      if (d[0] === 5) return this._socks(sock, d);
      this._http(sock, d);
    });
  }

  _pipe(a, b) {
    this.stats.open++;
    this.socks.add(b);
    a.on('data', (d) => { this.stats.up += d.length; });
    b.on('data', (d) => { this.stats.down += d.length; });
    b.on('error', () => {});
    a.pipe(b);
    b.pipe(a);
    const end = () => { a.destroy(); b.destroy(); };
    a.on('close', end);
    b.on('close', () => { this.socks.delete(b); end(); });
  }

  _fail() {
    this.stats.failed++;
  }

  // SOCKS5, no authentication (127.0.0.1 only): CONNECT by name, IPv4 or IPv6.
  _socks(sock, first) {
    let buf = first;
    let step = 0;
    const onData = (d) => { buf = Buffer.concat([buf, d]); go(); };
    const go = () => {
      if (step === 0) {
        if (buf.length < 2 || buf.length < 2 + buf[1]) return;
        buf = buf.subarray(2 + buf[1]);
        sock.write(Buffer.from([5, 0]));
        step = 1;
      }
      if (step === 1) {
        if (buf.length < 5) return;
        if (buf[1] !== 1) { sock.end(Buffer.from([5, 7, 0, 1, 0, 0, 0, 0, 0, 0])); return; } // CONNECT only
        let host = '';
        let off = 4;
        if (buf[3] === 1) { if (buf.length < 10) return; host = [...buf.subarray(4, 8)].join('.'); off = 8; }
        else if (buf[3] === 3) { const n = buf[4]; if (buf.length < 5 + n + 2) return; host = buf.subarray(5, 5 + n).toString('latin1'); off = 5 + n; }
        else if (buf[3] === 4) { if (buf.length < 22) return; const h = buf.subarray(4, 20).toString('hex'); host = h.match(/.{4}/g).join(':'); off = 20; }
        else { sock.destroy(); return; }
        const port = buf.readUInt16BE(off);
        const rest = buf.subarray(off + 2);
        step = 2;
        sock.removeListener('data', onData);
        sock.pause();
        this.dial(host, port).then((up) => {
          sock.write(Buffer.from([5, 0, 0, 1, 0, 0, 0, 0, 0, 0]));
          if (rest.length) up.write(rest);
          sock.resume();
          this._pipe(sock, up);
        }, () => { this._fail(); sock.end(Buffer.from([5, 4, 0, 1, 0, 0, 0, 0, 0, 0])); });
      }
    };
    sock.on('data', onData);
    go();
  }

  // HTTP: CONNECT host:port, or a plain request with its whole URL (passed on as one request:
  // Connection: close, so the next one comes on a new connection, perhaps to another host).
  _http(sock, first) {
    let buf = first;
    const onData = (d) => {
      buf = Buffer.concat([buf, d]);
      if (buf.length > 65536) { sock.destroy(); return; }
      go();
    };
    const go = () => {
      const end = buf.indexOf('\r\n\r\n');
      if (end < 0) return;
      sock.removeListener('data', onData);
      sock.pause();
      const head = buf.subarray(0, end).toString('latin1');
      const rest = buf.subarray(end + 4);
      const lines = head.split('\r\n');
      const [method, target, version] = lines[0].split(' ');
      if (method === 'CONNECT') {
        const m = /^\[?([^\]]+?)\]?:(\d{1,5})$/.exec(target || '');
        if (!m) { sock.end('HTTP/1.1 400 Bad Request\r\n\r\n'); return; }
        this.dial(m[1], Number(m[2])).then((up) => {
          sock.write('HTTP/1.1 200 Connection established\r\n\r\n');
          if (rest.length) up.write(rest);
          sock.resume();
          this._pipe(sock, up);
        }, (e) => { this._fail(); sock.end(`HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nThrough the phone: ${e.message}\n`); });
        return;
      }
      let url;
      try { url = new URL(target); } catch { sock.end('HTTP/1.1 400 Bad Request\r\n\r\n'); return; }
      if (url.protocol !== 'http:') { sock.end('HTTP/1.1 400 Bad Request\r\n\r\n'); return; }
      const keep = lines.slice(1).filter((l) => !/^(proxy-connection|connection|keep-alive|proxy-authorization):/i.test(l));
      const out = [`${method} ${url.pathname}${url.search} ${version || 'HTTP/1.1'}`, ...keep, 'Connection: close', '', ''].join('\r\n');
      const host = url.hostname.replace(/^\[|\]$/g, '');
      this.dial(host, Number(url.port) || 80).then((up) => {
        up.write(Buffer.concat([Buffer.from(out, 'latin1'), rest]));
        sock.resume();
        this._pipe(sock, up);
      }, (e) => { this._fail(); sock.end(`HTTP/1.1 502 Bad Gateway\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\nThrough the phone: ${e.message}\n`); });
    };
    sock.on('data', onData);
    go();
  }

  // ---- off ----

  _stop(why) {
    if (this.sent && this.hub.phone) this.hub.server.sendToClient({ t: T.NET, on: false });
    if (this.sent || this.server || this.proxied) this.log(`stopped: ${why} (${Math.round(this.stats.down / 1e6)} MB down, ${Math.round(this.stats.up / 1e6)} MB up)`);
    this.sent = false;
    this.token = '';
    this._unproxy();
    for (const s of this.socks) s.destroy();
    this.socks.clear();
    if (this.server) { this.server.close(); this.server = null; this.port = 0; }
  }

  _unproxy() {
    if (!this.proxied) return;
    this.proxied = false;
    const saved = this.saved;
    this.saved = null;
    const p = this.sysProxy ? this.sysProxy.restore(saved) : Promise.resolve();
    p.then(() => { if (this.stateFile) try { fs.unlinkSync(this.stateFile); } catch {} }, (e) => this.log(`couldn’t put back the proxy: ${e.message}`));
    this.log('the system proxy is as it was');
  }

  close() {
    this._stop('closing');
  }

  get view() {
    const ph = this.phone;
    return {
      can: this.can, on: this.enabled,
      // 'off' | 'starting' | 'on' | 'error'
      state: !this.enabled || !this.can ? 'off' : this.error || ph.state === 'error' ? 'error' : this.server && ph.state === 'on' ? 'on' : 'starting',
      why: ph.state === 'error' ? ph.why : this.error,
      vpn: ph.vpn, port: this.port, manual: !this.sysProxy,
      down: this.stats.down, up: this.stats.up, open: this.socks.size,
    };
  }
}

module.exports = { PhoneNet, systemProxy, runSync, T, mac };