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.

20.4 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith, Erdoğan Yeşil. GPL-3.0, see LICENSE.
// Host role (Linux ↔ Linux, Linux ↔ PC): HTTPS + WebSocket server on PORT: sessions,
// liveness, routing of authenticated messages. Copy of windows/mesh/server.js; the certificate comes
// from identity.js (PEM made by openssl).
//
// Many clients at once (mesh): `clients` maps deviceId -> ctx for every authenticated client.
// `current` is the primary client (setPrimary(), else the most recently authenticated one,
// preferring a non-Android client); features that talk to "the phone" keep using it.
//
// A client's session can move between sockets (hello {resume}): ctx.ws is the live socket,
// ctx.alt the fallback. A socket can carry a Bluetooth pipe (ws.transport 'ble', blepipe.js).
//
// Events:
//   'preauth' (ctx, msg)  — hello / pair.* before auth (hostpair.js handles them)
//   'client'  (ctx)       — a client got `welcome`
//   'message' (msg, ctx)  — any message from the authenticated client except ping/pong (peer.js routes)
//   'closed'  (ctx, unexpected) — a socket closed, with abnormal loss of a current session flagged
//   'forget'  (deviceId)  — the pairing was forgotten, even if its socket is already gone
//   'rtt'     (ctx)       — ctx.rttMs updated
//   'transport' (ctx)     — the session moved to another socket (hello {resume}) or back (ctx.transport)
//   'listening' / 'listenError' (err)
//   'phoneFree'           — a phone's hold on the session ended (kept for phone.js)
'use strict';

const https = require('https');
const { EventEmitter } = require('events');
const { WebSocketServer } = require('ws');
const P = require('../../shared/protocol.js');
const Quiet = require('../../shared/quiet.js'); // idle sessions stop pinging every second (#143)
const { LanePool } = require('../../shared/inputlane.js');

const ICE_OFFERS = new Set([P.T.RTC_OFFER, P.T.AUDIO_OFFER]);
const isLoopback = (a) => a === '127.0.0.1' || a === '::1';

// Dev only: listen elsewhere (a second copy on the same computer).
const LISTEN_PORT = Number(process.env.MACSHARE_DEV_PORT) || P.PORT;

// How often liveness is checked. A ping goes out only when nothing was sent for the interval.
const TICK_MS = 250;

class Server extends EventEmitter {
  // opts: key, cert; port (default PORT; 0 = any free port, see `port` after 'listening');
  //   now () -> ms (tests inject a fake clock); tick (false: no timer, call liveness() yourself).
  constructor({ key, cert, port, now, tick = true } = {}) {
    super();
    this.ilPool = new LanePool(); // the input lanes of the clients (shared/inputlane.js)
    this.clients = new Map(); // deviceId -> ctx, authenticated and connected
    this.sockets = new Set(); // every ctx, authed or not
    this.primaryId = null; // setPrimary()
    this.busyFlags = new Map(); // deviceId -> boolean from setBusy()
    this.authSeq = 0; // orders authentications (most recent first)
    this.phoneGrace = null; // always null: a phone no longer holds the session (kept for phone.js)
    this.blePorts = new Map(); // local ports of our own connections that carry a Bluetooth pipe (blepipe.js) -> last bytes
    this._now = now || (() => Date.now());
    this.tls = { key, cert }; // also the shared folder's server (shared/foldershare.js)
    this.https = https.createServer(this.tls);
    this.https.requestTimeout = 0; // not Node's 5-min cap on a whole request: fast files' PUTs (a phone's, a guest's) outlast it
    this.wss = new WebSocketServer({ server: this.https, maxPayload: P.MAX_PAYLOAD });
    // A phone's own screen (an iPhone's Share Screen, Android's Mirroring › Native): its upload here.
    this.https.on('request', (req, res) => {
      if (require('../../shared/phone-relay.js').ScreenHost.active?.request(req, res)) return; // a phone of ours (an iPhone on our cable, an Android phone connected here), watched from there
      if (require('../../shared/nativescreen.js').NativeScreen.request(req, res)) return;
      if (this.fxRequest && this.fxRequest(req, res)) return; // fast files of a session (session.js)
      if (this.driveRequest && this.driveRequest(req, res)) return; // TwinDesk Drive, while it's on (shared/drive-host.js createMesh)
      res.writeHead(404);
      res.end();
    });
    this.wss.on('connection', (ws, req) => this._onConnection(ws, req));
    this.wss.on('error', () => {}); // ws repeats the server's errors here; listenError below reports them
    this.https.on('error', (err) => this.emit('listenError', err)); // e.g. EADDRINUSE: another copy listens
    this.port = port !== undefined ? port : LISTEN_PORT;
    this.https.listen(this.port, '0.0.0.0', () => {
      this.port = this.https.address().port;
      this.emit('listening');
    });
    this.tick = tick ? setInterval(() => this.liveness(), TICK_MS) : null;
    this.unquiet = tick ? Quiet.onChange(() => this.liveness()) : null; // a hold reaches the other end at once
  }

  // The primary client: setPrimary()'s device while it is connected; else the most recently
  // authenticated one, a non-Android client first. null when nobody is connected.
  get current() {
    if (this.primaryId) {
      const c = this.clients.get(this.primaryId);
      if (c) return c;
    }
    let best = null;
    for (const c of this.clients.values()) {
      if (!best) best = c;
      else if ((P.isPhoneOs(best.os)) !== (P.isPhoneOs(c.os))) {
        if (!P.isPhoneOs(c.os)) best = c;
      } else if (c.authSeq > best.authSeq) best = c;
    }
    return best;
  }

  // The client that is the primary one (null: the most recently authenticated again).
  setPrimary(deviceId) {
    this.primaryId = deviceId || null;
  }

  // A busy client (driving, driven, or selected) is pinged every PING_MS; the others every
  // IDLE_PING_MS. Default: the primary client is busy.
  setBusy(deviceId, flag) {
    if (flag == null) this.busyFlags.delete(deviceId); // null: back to the default (the primary client)
    else this.busyFlags.set(deviceId, !!flag);
  }

  _isBusy(ctx) {
    const flag = this.busyFlags.get(ctx.deviceId);
    return flag === undefined ? ctx === this.current : flag;
  }

  _onConnection(ws, req) {
    const now = this._now();
    const ctx = {
      ws,
      authed: false,
      deviceId: null,
      name: null,
      os: null,
      authSeq: 0,
      address: (req.socket.remoteAddress || '').replace(/^::ffff:/, ''),
      connectedAt: now,
      lastRx: now,
      lastTx: now,
      rttMs: null,
      // 'ble': through a Bluetooth pipe (our own connection from 127.0.0.1), else the network
      transport: 'ip',
      alt: null, // the session's other socket, if it moved (resume): the fallback
    };
    if (isLoopback(ctx.address) && this.blePorts.has(req.socket.remotePort)) ctx.transport = 'ble';
    Object.assign(ws, { ctx, lastRx: now, lastTx: now, transport: ctx.transport, address: ctx.address, blePort: ctx.transport === 'ble' ? req.socket.remotePort : 0 });
    // At most 16 sockets from one address that haven't authenticated (a LAN peer can't open
    // thousands and hold each for UNAUTH_TIMEOUT_MS): past that the oldest goes, never the new one,
    // so a phone retrying on flaky Wi-Fi always gets in. Our own Bluetooth/wired pipes are loopback.
    if (!isLoopback(ctx.address)) {
      const waiting = [];
      for (const c of this.sockets) if (!c.authed && c.address === ctx.address) waiting.push(c);
      if (waiting.length >= 16) waiting[0].ws.terminate(); // a Set keeps insertion order: the oldest
    }
    this.sockets.add(ctx);
    ws.on('message', (data, isBinary) => this._onMessage(ws.ctx, data, isBinary, ws));
    ws.on('close', (code, reason) => this._onSocketClose(ws, code, String(reason || '')));
    ws.on('error', (err) => console.error(`[server] socket ${ws.address}: ${err.message}`));
    // Once open, ws destroys the socket on a TCP error without passing it on (the close says only
    // 1006): its code (ECONNRESET, ETIMEDOUT, EPIPE…) is kept for the close's line (#327).
    if (ws._socket) ws._socket.on('error', (err) => { ws.sockErr = err.code || err.message; });
  }

  _onSocketClose(ws, code, reason) {
    const ctx = ws.ctx;
    if (ws.detached) return;
    if (ctx.authed) { // which path went, and how (1000/1001: closed on purpose there; 1006: the connection dropped)
      const path = ws.transport === 'ble' ? 'Bluetooth' : ws.address;
      const heard = ws.lastRx ? `, last heard ${((Date.now() - ws.lastRx) / 1000).toFixed(1)} s before` : '';
      console.log(`[server] ${ctx.name}: ${ctx.alt === ws ? 'fallback' : 'session'} socket on ${path} closed (${code || '?'}${reason ? ` ${reason}` : ''}${ws.sockErr ? `, ${ws.sockErr}` : ''}) after ${Math.round((Date.now() - ctx.connectedAt) / 1000)} s${heard}`);
    }
    if (ctx.alt === ws) {
      ctx.alt = null;
      return this.emit('transport', ctx);
    }
    if (ctx.ws !== ws) return;
    // The session's socket went, its other one is still there: carry on through that one.
    const alt = ctx.alt;
    if (alt && alt.readyState === alt.OPEN) {
      ctx.alt = null;
      Object.assign(ctx, { ws: alt, transport: alt.transport, address: alt.address });
      console.log(`[server] ${ctx.name}: back on ${alt.transport === 'ble' ? 'Bluetooth' : alt.address}`);
      return this.emit('transport', ctx);
    }
    this.sockets.delete(ctx);
    const wasCurrent = !!ctx.authed && this.clients.get(ctx.deviceId) === ctx;
    if (wasCurrent) this.clients.delete(ctx.deviceId);
    this.ilPool.drop(ctx); // its input lane (shared/inputlane.js)
    this.emit('closed', ctx, wasCurrent && code === 1006 && !ctx.expectedClose && !ctx.released && !this.closed);
  }

  // hello {resume}: the session's guest reached us another way (the network, once both are on one,
  // or Bluetooth). The new socket becomes the session's, the old one stays as the fallback.
  _resume(tmp, msg) {
    const c = [...this.clients.values()].find((x) => x.resumeKey && x.resumeKey === msg.resume && x.deviceId === msg.id);
    if (!c) {
      return this.fail(tmp, P.E.BAD_MESSAGE, 'Nothing to resume');
    }
    this.sockets.delete(tmp);
    const ws = tmp.ws;
    if (c.alt) { // already moved once: the newest path replaces the current one
      c.ws.detached = true;
      c.ws.terminate();
    } else {
      c.alt = c.ws;
    }
    ws.ctx = c;
    Object.assign(c, { ws, transport: ws.transport, address: ws.address });
    ws.send(JSON.stringify({ t: P.T.WELCOME, v: P.PROTOCOL_VERSION, resumed: true }));
    console.log(`[server] ${c.name}: moved to ${ws.transport === 'ble' ? 'Bluetooth' : ws.address}`);
    this.emit('transport', c);
  }

  _onMessage(ctx, data, isBinary, ws) {
    const now = this._now();
    ctx.lastRx = now;
    if (ws) ws.lastRx = now;
    let msg;
    try {
      if (isBinary) throw new Error('binary');
      msg = JSON.parse(data.toString('utf8'));
      if (!msg || typeof msg !== 'object' || typeof msg.t !== 'string') throw new Error('no t');
    } catch (e) {
      return this.fail(ctx, P.E.BAD_MESSAGE, 'Expected a JSON object with a "t" field');
    }

    if (!ctx.authed) {
      if (this.asleep && msg.t === P.T.HELLO) return this.fail(ctx, P.E.ASLEEP, 'Asleep'); // a dark wake: not for a session
      if (msg.t === P.T.HELLO && typeof msg.resume === 'string') return this._resume(ctx, msg);
      if (msg.t === P.T.HELLO || msg.t.startsWith('pair.')) return this.emit('preauth', ctx, msg);
      return this.fail(ctx, P.E.BAD_MESSAGE, `"${msg.t}" is not allowed before welcome`);
    }
    if (ws && Quiet.seen(ws, msg)) return; // `idle {on}`: the other end's side of a quiet link

    if (msg.t === P.T.PING) return this.send(ctx, { t: P.T.PONG, ts: msg.ts });
    if (msg.t === P.T.BYE) { // Disconnect there: nothing to wait for
      ctx.released = true;
      if (ctx.alt) { // the whole session goes, its fallback path too
        const alt = ctx.alt;
        ctx.alt = null;
        alt.detached = true;
        alt.close();
      }
      return ctx.ws.close();
    }
    if (msg.t === P.T.PONG) {
      if (typeof msg.ts === 'number' && ws === ctx.ws) { // the session's socket only, not the fallback's
        ctx.rttMs = Math.max(0, this._now() - msg.ts);
        this.emit('rtt', ctx);
      }
      return;
    }
    // Battery alerts need the original authenticated context, before the hub routes the message.
    if (msg.t === P.T.PHONE_INFO && ws && !ws.detached && (ws === ctx.ws || ws === ctx.alt)) {
      this.emit(`t:${P.T.PHONE_INFO}`, msg, ctx);
    }
    this.emit('message', msg, ctx, ws); // session.js routes it by type
  }

  // Pings the sockets that have been silent for their interval, closes the ones silent too long.
  // Each of a session's sockets is checked on its own (a quiet fallback goes; the session lives on).
  // Called by the timer; tests call it with a fake clock.
  liveness(now = this._now()) {
    for (const ctx of this.sockets) {
      if (ctx.authed) {
        const busy = this._isBusy(ctx);
        for (const ws of [ctx.ws, ctx.alt]) {
          if (!ws) continue;
          const primary = ws === ctx.ws; // the session's own socket: its times are the client's (ctx)
          const ble = ws.transport === 'ble';
          // through Bluetooth a big message takes seconds: bytes still arriving count as a sign of life
          let rx = Math.max(primary ? ctx.lastRx || 0 : ws.lastRx || 0, (ws.blePort && this.blePorts.get(ws.blePort)) || 0);
          // Quiet links (shared/quiet.js): both ends idle, a ping every few minutes. Not through Bluetooth;
          // never the input partner's link (setBusy true).
          if (!ble && ws.readyState === ws.OPEN) {
            const q = Quiet.tick(ws, now, rx, (m) => this._raw(ws, m), this.busyFlags.get(ctx.deviceId) === true);
            if (q.quiet) {
              if (q.dead) { console.log(`[server] ${ctx.name || ctx.address} silent on a quiet link, closing`); ws.terminate(); }
              else if (q.ping) { ws.lastPing = now; this._raw(ws, { t: P.T.PING, ts: now }); }
              continue;
            }
            rx = q.rx;
          }
          const timeout = busy ? (ble ? P.BLE_TIMEOUT_MS : P.TIMEOUT_MS) : (ble ? P.BLE_TIMEOUT_MS : P.IDLE_TIMEOUT_MS);
          const every = busy ? P.PING_MS : P.IDLE_PING_MS;
          const tx = primary ? ctx.lastTx || 0 : ws.lastTx || 0;
          if (now - rx > timeout) {
            console.log(`[server] ${ctx.name || ctx.address} silent for ${timeout} ms on ${ble ? 'Bluetooth' : ws.address}, closing`);
            ws.terminate();
          } else if (ws.readyState === ws.OPEN && (busy ? now - (ws.lastPing || 0) >= every : now - tx >= every)) {
            // A busy link pings on its own every PING_MS (both ends measure the round trip, which the
            // window shows); an idle one only when nothing was sent for IDLE_PING_MS.
            ws.lastPing = now;
            if (primary) this.send(ctx, { t: P.T.PING, ts: now });
            else this._raw(ws, { t: P.T.PING, ts: now });
          }
        }
      } else if (now - ctx.connectedAt > P.UNAUTH_TIMEOUT_MS) {
        ctx.ws.terminate();
      }
    }
  }

  _raw(ws, msg) {
    ws.send(JSON.stringify(msg));
    ws.lastTx = this._now();
  }

  send(ctx, msg) {
    if (!ctx || ctx.ws.readyState !== ctx.ws.OPEN) return;
    // A phone on the USB cable: its WebRTC goes through the relay too (wired.js).
    if (ctx.ice && ICE_OFFERS.has(msg.t)) msg = { ...msg, ice: ctx.ice };
    // Cursor › Mouse and keyboard over Bluetooth: the pointer and keys on that socket (shared/bleinput.js; null: off).
    const ws = this.bleInput ? this.bleInput.route(ctx.ws, ctx.alt, msg) : ctx.ws;
    Quiet.sent(ws, msg);
    this._raw(ws, msg);
    ctx.lastTx = ws.lastTx;
  }

  // Send to the primary client, if any.
  sendToClient(msg) {
    this.send(this.current, msg);
  }

  // Send an error and close the socket(s) of that client.
  fail(ctx, code, message) {
    ctx.expectedClose = true;
    console.log(`[server] ${ctx.name || ctx.address}${ctx.transport === 'ble' ? ' (Bluetooth)' : ''}: ${code}: ${message}`);
    this.send(ctx, { t: P.T.ERROR, code, message });
    if (ctx.alt) { // the whole session goes, not just this path of it
      const alt = ctx.alt;
      ctx.alt = null;
      alt.detached = true;
      alt.close();
    }
    ctx.ws.close();
  }

  // Mark ctx authenticated. A client with the same device id replaces the older socket of that
  // device only; other devices are untouched.
  authenticate(ctx, who, welcome) {
    const { deviceId, name, os } = who;
    ctx.pendingId = deviceId;
    // The files engine (fx2, shared/meshfx.js) starts on demand and its port goes in this welcome:
    // when it isn't listening yet the welcome waits for it, a few tens of ms, never long.
    const wait = ctx.fxWanted && ctx.fx2Wanted && !ctx.fx2Waited && this.fx2Wait ? this.fx2Wait(1500) : null;
    if (wait) {
      ctx.fx2Waited = true;
      const go = () => { if (!ctx.authed && this.sockets.has(ctx) && ctx.ws.readyState === ctx.ws.OPEN) this.authenticate(ctx, who, welcome); };
      return void wait.then(go, go);
    }
    const old = this.clients.get(deviceId);
    if (old && old !== ctx) {
      this.clients.delete(deviceId);
      this.fail(old, P.E.REPLACED, 'Another connection from a paired device replaced this one');
    }
    ctx.authed = true;
    ctx.deviceId = deviceId;
    ctx.name = name;
    ctx.os = os;
    ctx.authSeq = ++this.authSeq;
    ctx.ice = this.iceFor ? this.iceFor(ctx) : null; // a phone through adb reverse: the relay's RTCConfiguration
    ctx.resumeKey = P.randomHex(16);
    this.clients.set(deviceId, ctx);
    // The input lane (shared/inputlane.js): a lane of its own, when its hello asked, over the network only.
    const il = ctx.ilWanted && ctx.transport !== 'ble' ? this.ilPool.offer(ctx, ctx.ilWanted, ctx.address) : null;
    ctx.fx = ctx.fxWanted ? P.randomHex(16) : ''; // fast files: this session's token (session.js routes its requests)
    ctx.fx2 = ctx.fx && ctx.fx2Wanted && this.fx2Port ? this.fx2Port() || 0 : 0; // its files engine's port
    this.send(ctx, { ...welcome, resume: ctx.resumeKey, ...(il ? { il } : {}), ...(ctx.fx ? { fx: ctx.fx } : {}), ...(ctx.fx2 ? { fx2: { port: ctx.fx2 } } : {}) });
    this.emit('client', ctx);
  }

  // Phones no longer hold the session: computers are never refused because of one.
  phoneHolds() {
    return false;
  }

  // Kept for phone.js and the app's phone code; no grace period is started any more.
  _phoneGrace() {}

  endPhoneGrace() {
    clearTimeout(this.graceTimer);
    if (!this.phoneGrace) return;
    this.phoneGrace = null;
    this.emit('phoneFree');
  }

  // Disconnect a client on purpose (a phone or a computer): it doesn't resume or reconnect by itself,
  // and the other side may connect at once. Default: the primary client.
  release(ctx = this.current) {
    if (ctx) {
      ctx.released = true;
      this.fail(ctx, P.E.RELEASED, 'The computer disconnected');
      setTimeout(() => ctx.ws.terminate(), 1000); // an older app never answers the close
    }
    this.endPhoneGrace();
  }

  // Disconnect a phone on purpose (ctx: its client; default the primary client, when it is a phone).
  releasePhone(ctx = this.current) {
    if (ctx && P.isPhoneOs(ctx.os)) {
      ctx.released = true;
      this.fail(ctx, P.E.RELEASED, 'The computer disconnected the phone');
      setTimeout(() => ctx.ws.terminate(), 1000); // an older phone app never answers the close
    }
    this.endPhoneGrace();
  }

  // The computer is going to sleep (powerMonitor 'suspend'): the session ends with `asleep`, and
  // until it wakes for real ('resume') hellos are refused. A dark wake (Power Nap, network upkeep)
  // answers for a few seconds now and then: a guest let in then only went silent again, every ~20 s.
  // Every connected device's session ends (mesh); returns their ids, which mesh/sleepwake.js invites
  // back on waking.
  sleep(on) {
    this.asleep = !!on;
    if (!on) return [];
    const ids = [];
    for (const c of [...this.clients.values()]) {
      c.released = true; // no phone grace: it's told why
      this.fail(c, P.E.ASLEEP, 'Went to sleep');
      if (c.deviceId) ids.push(c.deviceId);
    }
    return ids;
  }

  // Close every socket that belongs to a device id (used by Forget).
  closeDevice(deviceId, code, message) {
    this.emit('forget', deviceId);
    for (const ctx of this.sockets) if (ctx.deviceId === deviceId) this.fail(ctx, code, message);
  }

  close() {
    this.closed = true;
    clearInterval(this.tick);
    if (this.unquiet) this.unquiet();
    this.ilPool.close();
    clearTimeout(this.graceTimer);
    for (const ctx of this.sockets) {
      if (ctx.alt) ctx.alt.terminate();
      ctx.ws.terminate();
    }
    this.wss.close();
    this.https.close();
  }
}

module.exports = { Server };