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.

17.1 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Mesh managers (docs/mesh.md "Mesh managers"): one computer of the mesh as its admin device. It locks,
// sleeps, restarts, shuts down and wakes the computers that accepted it, and unlocks with Windows Hello or
// Touch ID those that also accepted Biometric unlock.
//
// Who may be what:
//   - A manager: a computer running TwinDesk Professional (the Full KVM build), or a Mac. Turned on there (Mesh
//     manager mode, after a warning). The standard build on Windows and Linux shows it grayed out.
//   - Managed: any computer, any edition. It's added only when it accepts, on its own screen.
//   - Biometric unlock: per managed computer, off until turned on on the manager, and then only once that
//     computer accepts the risk. Only a computer running TwinDesk Professional can be unlocked (a Mac never is).
//   - Phones are never managers and never managed here.
// A manager gets no terminal or files (the Terminal page asks for those). Every grant can be revoked on
// the managed computer; a manager turning its mode off drops everything it was granted.
//
// Wire (the hub's bus; new types, an older TwinDesk ignores them):
//   mgr.dev   {mgr, pro, can, grants, asks, locked, wakes}  pool: this computer's part (mgr: manager mode on;
//             grants / asks: {managerId: {power?, unlock?}})
//   mgr.offer {perm, on}        direct, manager → computer: add it (power) or offer Biometric unlock; off withdraws
//   mgr.cmd   {rid, do}         direct, manager → computer ; mgr.res {rid, ok, why} back
// Offers and commands come only on the manager's own session, never relayed by another computer.
//
//   const m = meshMgr({ bus, mesh, selfId, name(), settings(), save(), isPhone(id), devices() → [{id, name, online}],
//     canManage (Pro or a Mac), pro (this computer can be unlocked: Pro, not a Mac),
//     local: {can() → {lock, sleep, restart, shutdown}, do(act)}, wake(id) → bool, wakes() → [ids], locked?() → bool, onChange() })
//   m.view()                          state.mgr (shared/ui-meshmgr.js)
//   manager: m.setOn(on) ; m.pick(id, on) ; m.setUnlock(id, on) ; m.act(to, do) → Promise {ok, why}
//   managed: m.answer(mgr, perm, yes) ; m.revoke(mgr)
//   m.mayUnlock(id)                   unlock-host.js: may that computer unlock this one
//   m.tick()                          with every state push
'use strict';

const { Pool } = require('./mesh.js');

const T = { DEV: 'mgr.dev', OFFER: 'mgr.offer', CMD: 'mgr.cmd', RES: 'mgr.res' };
const PERMS = ['power', 'unlock'];
const POWER = ['lock', 'sleep', 'restart', 'shutdown'];
const ACTS = ['wake', ...POWER];
const MAX = 10; // the mesh's devices (it stays at ten)
const REPUBLISH_MS = 60000;
const REPLY_MS = 8000;
const AFTER_MS = 1500; // sleep, restart, shut down: after the answer has gone out
const ID = /^[A-Za-z0-9_-]{1,64}$/;
const str = (v, n) => (typeof v === 'string' ? v.slice(0, n) : '');

function cleanPerms(p) {
  const out = {};
  for (const k of PERMS) if (p && p[k] === true) out[k] = true;
  return out;
}

function cleanGrants(g) {
  const out = {};
  if (g && typeof g === 'object') {
    for (const [id, p] of Object.entries(g)) {
      if (!ID.test(id) || Object.keys(out).length >= MAX) continue;
      const c = cleanPerms(p);
      if (Object.keys(c).length) out[id] = c;
    }
  }
  return out;
}

function cleanCan(c) {
  const out = {};
  if (c && typeof c === 'object') for (const k of POWER) if (c[k] === true) out[k] = true;
  return out;
}

// What's kept (multi.json; the Mac's settings): manager mode off, nobody picked, nothing granted.
function normalize(m) {
  m = m && typeof m === 'object' ? m : {};
  const named = (g) => {
    const out = {};
    if (g && typeof g === 'object') {
      for (const [id, p] of Object.entries(g)) {
        if (!ID.test(id) || !p || typeof p !== 'object' || Object.keys(out).length >= MAX) continue;
        const c = cleanPerms(p);
        if (Object.keys(c).length) out[id] = { name: str(p.name, 64), ...c, at: Number(p.at) || 0 };
      }
    }
    return out;
  };
  const picked = {};
  if (m.picked && typeof m.picked === 'object') for (const [id, p] of Object.entries(m.picked)) if (ID.test(id) && Object.keys(picked).length < MAX) picked[id] = { unlock: !!(p && p.unlock) };
  return { on: m.on === true, picked, grants: named(m.grants), asks: named(m.asks) };
}

class MeshMgr {
  constructor(o) {
    Object.assign(this, { onChange: () => {}, wake: () => false, wakes: () => [], locked: () => false, canManage: false, pro: false }, Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined)));
    this.pool = new Pool({ name: 'mgr', selfId: this.selfId, peers: () => this._peers() });
    this.by = new Map(); // computer id → its mgr.dev
    this.waiting = new Map(); // rid → {to, resolve, timer}
    this.sentKey = '';
    this.sentAt = 0;
    this.last = '';
    this.bus.on(T.DEV, (m, from) => this._heardDev(m, from));
    this.bus.on(T.OFFER, (m, from) => this._heardOffer(m || {}, from));
    this.bus.on(T.CMD, (m, from) => this._heardCmd(m || {}, from));
    this.bus.on(T.RES, (m, from) => this._heardRes(m || {}, from));
    this.bus.onPeer('welcome', (id) => { this.sentKey = ''; this.tick(); this._reoffer(id); });
    this.bus.onPeer('closed', () => this.onChange());
    if (!this.canManage && this.cfg.on) { this.cfg.on = false; this.save(); } // a build that can't (any more)
  }

  get cfg() {
    const s = this.settings();
    if (!s.mgr || this._clean !== s.mgr) { s.mgr = normalize(s.mgr); this._clean = s.mgr; } // once per settings object
    return s.mgr;
  }

  _save() {
    this.save();
    this.sentKey = '';
    this.tick();
    this.onChange();
  }

  _peers() {
    return this.mesh.peers().filter((e) => e.mesh && !this.isPhone(e.id)).map((e) => ({ id: e.id, mesh: true, pool: true, send: (msg) => e.send(msg) }));
  }

  _direct(id) {
    return !!(this.bus.connectedIds && this.bus.connectedIds().includes(id)) && !this.isPhone(id);
  }

  _nameOf(id) {
    if (id === this.selfId) return str(this.name(), 64);
    const d = (this.devices() || []).find((x) => x.id === id);
    return (d && str(d.name, 64)) || id.slice(0, 8);
  }

  // ---- this computer as a manager ----

  setOn(on) {
    const c = this.cfg;
    if (on && !this.canManage) return false;
    if (!on) for (const id of Object.keys(c.picked)) this._send(id, 'power', false); // everything it was granted goes
    c.on = !!on;
    if (!on) c.picked = {};
    console.log('[mgr] mesh manager mode ' + (on ? 'on' : 'off') + ' here');
    this._save();
    return true;
  }

  // Add a computer (it's asked to accept), or let it go.
  pick(id, on) {
    const c = this.cfg;
    if (!c.on || !ID.test(String(id || '')) || id === this.selfId || this.isPhone(id)) return false;
    if (on) {
      if (!c.picked[id] && Object.keys(c.picked).length >= MAX) return false;
      c.picked[id] = { unlock: false };
      this._send(id, 'power', true);
    } else {
      delete c.picked[id];
      this._send(id, 'power', false);
    }
    this._save();
    return true;
  }

  // Biometric unlock for a computer it manages: off by default; on asks that computer to accept the risk.
  setUnlock(id, on) {
    const c = this.cfg;
    const p = c.picked[id];
    if (!c.on || !p) return false;
    if (on && !((this.by.get(id) || {}).pro && this._granted(id, 'power'))) return false; // TwinDesk Professional there, and added
    p.unlock = !!on;
    this._send(id, 'unlock', !!on);
    this._save();
    return true;
  }

  _send(id, perm, on) {
    if (this._direct(id)) this.bus.send(id, { t: T.OFFER, perm, on });
  }

  // A computer that connects again hears what this manager still asks of it (an offer lost while it was away).
  _reoffer(id) {
    const c = this.cfg;
    const p = c.on && c.picked[id];
    if (!p) return;
    if (!this._granted(id, 'power')) this._send(id, 'power', true);
    if (p.unlock && !this._granted(id, 'unlock')) this._send(id, 'unlock', true);
  }

  _granted(to, perm) {
    const s = this.by.get(to);
    return !!(s && s.grants && s.grants[this.selfId] && s.grants[this.selfId][perm]);
  }

  _asked(to, perm) {
    const s = this.by.get(to);
    return !!(s && s.asks && s.asks[this.selfId] && s.asks[this.selfId][perm]);
  }

  act(to, act) {
    const done = (r) => { this.last = r.ok ? '' : r.why; this.onChange(); return r; };
    if (!this.cfg.on) return Promise.resolve(done({ ok: false, why: 'notmgr' }));
    if (!ACTS.includes(act)) return Promise.resolve(done({ ok: false, why: 'unknown' }));
    if (!this._granted(to, 'power')) return Promise.resolve(done({ ok: false, why: 'revoked' }));
    if (act === 'wake') {
      if (this._direct(to)) return Promise.resolve(done({ ok: false, why: 'nothing' }));
      return Promise.resolve(done(this.wake(to) ? { ok: true } : { ok: false, why: 'nothing' }));
    }
    if (!this._direct(to)) return Promise.resolve(done({ ok: false, why: 'offline' }));
    const rid = 'm' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
    console.log('[mgr] asking ' + this._nameOf(to) + ' to ' + act);
    return new Promise((resolve) => {
      const timer = setTimeout(() => { this.waiting.delete(rid); resolve(done({ ok: false, why: 'timeout' })); }, REPLY_MS);
      this.waiting.set(rid, { to, timer, resolve: (r) => resolve(done(r)) });
      this.bus.send(to, { t: T.CMD, rid, do: act });
    });
  }

  // ---- this computer as a managed one ----

  answer(mgr, perm, yes) {
    const c = this.cfg;
    const a = c.asks[mgr];
    if (!a || !a[perm]) return false;
    delete a[perm];
    if (!PERMS.some((p) => a[p])) delete c.asks[mgr];
    if (yes) {
      if (perm === 'unlock' && !(c.grants[mgr] && c.grants[mgr].power)) return this._save(), false;
      c.grants[mgr] = { ...(c.grants[mgr] || {}), name: this._nameOf(mgr), [perm]: true, at: Date.now() };
      console.log('[mgr] ' + this._nameOf(mgr) + ' accepted here as a mesh manager: ' + perm);
    }
    this._save();
    return true;
  }

  revoke(mgr) {
    const c = this.cfg;
    if (!c.grants[mgr] && !c.asks[mgr]) return false;
    delete c.grants[mgr];
    delete c.asks[mgr];
    console.log('[mgr] ' + this._nameOf(mgr) + ' revoked here');
    this._save();
    return true;
  }

  _may(mgr, perm) {
    const g = this.cfg.grants[mgr];
    return !!(g && g[perm] && (this.by.get(mgr) || {}).mgr);
  }

  // unlock-host.js: this computer may be unlocked by that one (accepted, on its own direct session).
  mayUnlock(id) {
    return this.pro && this._may(id, 'unlock') && this._direct(id);
  }

  // ---- what goes out ----

  _mine() {
    const c = this.cfg;
    return {
      mgr: c.on, pro: !!this.pro, can: cleanCan(this.local.can()), grants: cleanGrants(c.grants), asks: cleanGrants(c.asks),
      locked: !!this.locked(), ...(c.on ? { wakes: (this.wakes() || []).filter((x) => ID.test(x)).slice(0, MAX) } : {}),
    };
  }

  tick() {
    const ours = this._mine();
    const key = JSON.stringify(ours);
    if (key !== this.sentKey || Date.now() - this.sentAt >= REPUBLISH_MS) {
      const changed = key !== this.sentKey;
      this.sentKey = key;
      this.sentAt = Date.now();
      this.pool.publish({ t: T.DEV, ...ours });
      if (changed) this.onChange();
    }
  }

  // ---- heard ----

  _heardDev(m, from) {
    if (this.isPhone(from)) return;
    const r = this.pool.receive(from, m);
    if (!r.fresh || !r.msg || typeof r.msg.o !== 'string' || r.msg.o === this.selfId) return;
    const o = r.msg.o;
    const was = this.by.get(o);
    this.by.set(o, {
      mgr: m.mgr === true, pro: m.pro === true, can: cleanCan(m.can), grants: cleanGrants(m.grants), asks: cleanGrants(m.asks), locked: m.locked === true,
      wakes: Array.isArray(m.wakes) ? m.wakes.filter((x) => typeof x === 'string' && ID.test(x)).slice(0, MAX) : [], at: Date.now(),
    });
    // A manager that turned its mode off: what it was granted or asked here goes.
    const c = this.cfg;
    if (m.mgr !== true && (c.grants[o] || c.asks[o])) { delete c.grants[o]; delete c.asks[o]; console.log('[mgr] ' + this._nameOf(o) + ' is no longer a mesh manager'); this._save(); return; }
    if (!was || JSON.stringify(was) !== JSON.stringify(this.by.get(o))) this.onChange();
  }

  _heardOffer(m, from) {
    if (this.isPhone(from) || !ID.test(String(from || ''))) return;
    const perm = m.perm;
    if (!PERMS.includes(perm)) return;
    const c = this.cfg;
    if (m.on !== true) { // withdrawn: always taken, the grant too (power takes unlock with it)
      const drop = perm === 'power' ? PERMS : [perm];
      let changed = false;
      for (const g of [c.asks, c.grants]) {
        if (!g[from]) continue;
        for (const p of drop) if (g[from][p]) { delete g[from][p]; changed = true; }
        if (!PERMS.some((p) => g[from][p])) delete g[from];
      }
      if (changed) this._save();
      return;
    }
    if (perm === 'unlock' && !this.pro) return; // nothing to unlock here (the standard build, a Mac)
    if (perm === 'unlock' && !(c.grants[from] && c.grants[from].power)) return;
    if (c.grants[from] && c.grants[from][perm]) return;
    if (!c.asks[from] && Object.keys(c.asks).length >= MAX) return;
    c.asks[from] = { ...(c.asks[from] || {}), name: this._nameOf(from), [perm]: true, at: Date.now() };
    console.log('[mgr] ' + this._nameOf(from) + ' asks to ' + (perm === 'power' ? 'manage this computer' : 'unlock this computer') + ': waiting for an answer here');
    this._save();
  }

  async _heardCmd(m, from) {
    const rid = str(m.rid, 40);
    const reply = (ok, why) => this.bus.send(from, { t: T.RES, rid, ok: !!ok, ...(why ? { why } : {}) });
    const act = m.do;
    if (this.isPhone(from)) return reply(false, 'revoked');
    if (!POWER.includes(act)) return reply(false, 'unknown');
    if (!this._may(from, 'power')) return reply(false, 'revoked');
    if (!cleanCan(this.local.can())[act]) return reply(false, 'cant');
    console.log('[mgr] ' + act + ' from ' + this._nameOf(from) + ' (mesh manager)');
    reply(true);
    const go = () => Promise.resolve(this.local.do(act)).catch((e) => console.log('[mgr] ' + act + ': ' + e.message));
    if (act === 'lock') go();
    else setTimeout(go, AFTER_MS);
  }

  _heardRes(m, from) {
    const w = this.waiting.get(str(m.rid, 40));
    if (!w || w.to !== from) return;
    clearTimeout(w.timer);
    this.waiting.delete(m.rid);
    w.resolve({ ok: m.ok === true, why: str(m.why, 20) });
  }

  // ---- the pages ----

  view() {
    const c = this.cfg;
    const others = (this.devices() || []).filter((d) => d && d.id && d.id !== this.selfId && !this.isPhone(d.id)).slice(0, MAX);
    const state = (id, perm) => (this._granted(id, perm) ? 'accepted' : this._asked(id, perm) ? 'offered' : '');
    const wakers = new Set(this.wakes() || []);
    return {
      canManage: !!this.canManage, // TwinDesk Professional or a Mac: else the switch is grayed out
      pro: !!this.pro,
      on: c.on,
      // Managed here: offers waiting for an answer, and who manages this computer.
      asks: Object.entries(c.asks).map(([id, a]) => ({ id, name: this._nameOf(id), perms: PERMS.filter((p) => a[p]) })),
      grants: Object.entries(c.grants).map(([id, g]) => ({ id, name: this._nameOf(id), perms: PERMS.filter((p) => g[p]) })),
      // Manager mode: every other computer, whether it's picked, accepted, can be unlocked, and its state.
      computers: c.on ? others.map((d) => {
        const s = this.by.get(d.id) || {};
        const direct = this._direct(d.id);
        const p = c.picked[d.id];
        return {
          id: d.id, name: str(d.name, 64) || d.id.slice(0, 8), online: !!d.online, direct, said: this.by.has(d.id),
          pro: !!s.pro, picked: !!p, wantUnlock: !!(p && p.unlock), power: state(d.id, 'power'), unlock: state(d.id, 'unlock'),
          locked: !!s.locked, can: direct && this._granted(d.id, 'power') ? { ...(s.can || {}) } : {},
          wake: !direct && this._granted(d.id, 'power') && wakers.has(d.id),
        };
      }) : [],
      result: this.last,
    };
  }

  stop() {
    for (const w of this.waiting.values()) clearTimeout(w.timer);
    this.waiting.clear();
  }
}

// Windows, Linux and the Mac: from a mesh hub (*/mesh/hub.js) and this computer's parts.
function onHub({ hub, mesh, selfId, name, settings, save, devLocal, wake, wakes, locked, onChange }) {
  const P = require('./protocol.js');
  const pro = process.platform !== 'darwin' && require('./edition.js').fullKvm(); // TwinDesk Professional: the Full KVM build
  const peer = (id) => (hub.sessions && hub.sessions.get(id)) || null;
  return new MeshMgr({
    bus: hub.bus, mesh, selfId, name, settings, save, onChange, wake, wakes, locked, pro,
    canManage: pro || process.platform === 'darwin',
    isPhone: (id) => { const s = peer(id); if (s) return P.isPhoneOs(s.peerOs); const d = hub.peers({ indirect: true }).find((x) => x.id === id); return !!d && P.isPhoneOs(d.os); },
    devices: () => hub.peers({ indirect: true }).filter((d) => !P.isPhoneOs(d.os)).map((d) => ({ id: d.id, name: d.name, online: !!d.connected || d.state === 'via' })),
    local: {
      can: () => ({ ...devLocal.can(), ...devLocal.powerCan({ fullKvm: pro }) }),
      do: (act) => (act === 'lock' || act === 'sleep' ? devLocal.do({ do: act }) : devLocal.power(act)),
    },
  });
}

module.exports = { MeshMgr, meshMgr: (o) => new MeshMgr(o), onHub, normalize, T, PERMS, ACTS };