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.

21.2 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Full KVM on Linux (docs/full-kvm.md): the system service, as root, from systemd
// (twindesk-fullkvm.service, written by install.sh). It runs the helper's uinput backend
// (linux-helper, MACSHARE_HELPER_BACKEND=uinput: evdev capture and uinput injection, below every
// display server), so the mesh's mouse and keyboard work on the lock screen, in polkit dialogs and,
// System-wide, at the login screen, and hands it to one client over /run/twindesk/kvm.sock:
//   - someone signed in on seat0: their TwinDesk (the socket is theirs, mode 0600);
//   - the login screen, System-wide: the machine node (headless.js), started here as the unprivileged
//     `twindesk` account, stopped when someone signs in (their app takes over).
// The socket carries the helper's own JSON lines, for the mouse-and-keyboard commands only: anything
// else is refused, so this root process never reads a file or runs anything for its client, and it
// has no network of its own (the native input lane stays off: the client's Node lane injects here).
// One helper per connection: a client that goes leaves nothing captured, grabbed or held.
// Biometric unlock (Unlock below, shared/fullkvm/unlock.js): the phone's fingerprint or Face ID unlocks
// seat0's lock screen (loginctl unlock-session) and, through pam_twindesk.so (/run/twindesk/unlock.sock,
// root's only), the login screen. The client relays the phone; this checks the signature itself.
//   ELECTRON_RUN_AS_NODE=1 <electron> linux/fullkvm/service.js   (or node)
'use strict';

const fs = require('fs');
const net = require('net');
const path = require('path');
const { spawn, execFile } = require('child_process');

const CONF = process.env.TWINDESK_FULLKVM_CONF || '/etc/twindesk/fullkvm.json';
const RUN = process.env.TWINDESK_FULLKVM_RUN || '/run/twindesk';
const SOCK = path.join(RUN, 'kvm.sock');
const MACHINE = '/var/lib/twindesk'; // the machine node's folder (System-wide)
const ACCOUNT = 'twindesk';
const ROOT = path.join(__dirname, '..', '..'); // the app: linux/, shared/, linux-helper/
const BIN = path.join(ROOT, 'linux-helper', 'bin', 'macshare-linuxhelper-multi');
const BIN_ONE = path.join(ROOT, 'linux-helper', 'bin', 'macshare-linuxhelper');
// What the helper and the machine node get as PATH. TWINDESK_FULLKVM_PATH (the NixOS module's unit sets it) goes first.
const PATH = [process.env.TWINDESK_FULLKVM_PATH, '/usr/sbin:/usr/bin:/sbin:/bin'].filter(Boolean).join(':');
const SEAT_MS = 1000;
const MAX_LINE = 256 * 1024;
// The helper's mouse-and-keyboard commands (linux-helper/src/main.c, its uinput branch).
const ALLOWED = new Set(['ping', 'keepalive', 'kvmConfig', 'screens', 'capture', 'place', 'armReturn', 'inject', 'pen', 'touch', 'releaseAll', 'watchRelease', 'moveTo', 'info',
  'dragCross']); // a file drag the user's helper caught on its strip (linux-helper/src/wlstrip.c)

const log = (...a) => console.log('[fullkvm]', ...a);
const UNLOCK_SOCK = path.join(RUN, 'unlock.sock');
const UNLOCK_DIR = process.env.TWINDESK_UNLOCK_DIR || '/etc/twindesk/unlock';

// Its own output, the last RING_MAX bytes (Debug › Logs › Full KVM service, docs/debug.md): systemd's
// journal or OpenRC's log file is root's, so the user's app asks for it here (serviceLog), which reads
// nothing from disk. Offsets count from the service's start; what's older than the ring is gone.
const RING_MAX = 1024 * 1024;
const PIECE = 128 * 1024;
let ring = Buffer.alloc(0);
let ringEnd = 0; // bytes written since start
for (const stream of [process.stdout, process.stderr]) {
  const write = stream.write.bind(stream);
  stream.write = (chunk, ...rest) => {
    try {
      const b = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
      ring = Buffer.concat([ring, b]);
      if (ring.length > RING_MAX) ring = ring.subarray(ring.length - RING_MAX);
      ringEnd += b.length;
    } catch (_) { /* the log goes on */ }
    return write(chunk, ...rest);
  };
}
function serviceLog(msg) {
  const start = ringEnd - ring.length;
  let from = Number(msg.from);
  if (!Number.isFinite(from) || from < start || from > ringEnd) from = start;
  const len = Math.max(0, Math.min(PIECE, Number(msg.len) || PIECE, ringEnd - from));
  const data = ring.subarray(from - start, from - start + len).toString('base64');
  return { id: msg.id, ok: true, size: ringEnd, from, data };
}

function readConf() {
  try {
    const c = JSON.parse(fs.readFileSync(CONF, 'utf8'));
    return { mode: c && c.mode === 'system' ? 'system' : 'simple' };
  } catch (_) {
    return { mode: 'simple' };
  }
}

function run(cmd, args) {
  return new Promise((resolve) => execFile(cmd, args, { timeout: 3000 }, (err, out) => resolve(err ? '' : String(out))));
}

// Who seat0 belongs to now: { kind: 'user', uid } (signed in: the lock screen too, it is their
// session), { kind: 'greeter' } (the login screen) or { kind: 'none' }.
async function seatOwner() {
  const sid = (await run('loginctl', ['show-seat', 'seat0', '-p', 'ActiveSession', '--value'])).trim();
  if (!sid) return { kind: 'none' };
  const props = {};
  for (const line of (await run('loginctl', ['show-session', sid, '-p', 'User', '-p', 'Class', '-p', 'State'])).split('\n')) {
    const i = line.indexOf('=');
    if (i > 0) props[line.slice(0, i)] = line.slice(i + 1).trim();
  }
  if (props.Class === 'greeter') return { kind: 'greeter', sid };
  const uid = Number(props.User);
  if (props.Class === 'user' && Number.isInteger(uid) && uid > 0) return { kind: 'user', uid, sid };
  return { kind: 'none' };
}

function accountIds() {
  try {
    const line = fs.readFileSync('/etc/passwd', 'utf8').split('\n').find((l) => l.startsWith(ACCOUNT + ':'));
    const f = line.split(':');
    return { uid: Number(f[2]), gid: Number(f[3]) };
  } catch (_) {
    return null;
  }
}

const same = (a, b) => a.kind === b.kind && a.uid === b.uid;

class Service {
  constructor() {
    this.conf = readConf();
    this.owner = { kind: 'none' };
    this.client = null; // { sock, helper }
    this.node = null; // the machine node's process
    this.server = null;
    this.unlock = new Unlock(this);
  }

  start() {
    fs.mkdirSync(RUN, { recursive: true, mode: 0o755 });
    try { fs.unlinkSync(SOCK); } catch (_) { /* none left */ }
    const old = process.umask(0o177); // born 0600 root: nobody connects before it is given to its owner
    this.server = net.createServer((sock) => this._accept(sock));
    this.server.listen(SOCK, () => {
      process.umask(old);
      log(`listening on ${SOCK} (${this.conf.mode})`);
      this._seat();
    });
    this.server.on('error', (e) => { log('socket:', e.message); process.exit(1); });
    setInterval(() => this._seat(), SEAT_MS);
    this.unlock.start();
    for (const sig of ['SIGTERM', 'SIGINT']) process.on(sig, () => this.stop());
    process.on('SIGHUP', () => { this.conf = readConf(); log('mode', this.conf.mode); this._apply(true); });
  }

  stop() {
    this._drop();
    this._stopNode();
    try { fs.unlinkSync(SOCK); } catch (_) { /* gone */ }
    try { fs.unlinkSync(UNLOCK_SOCK); } catch (_) { /* gone */ }
    process.exit(0);
  }

  async _seat() {
    const now = await seatOwner();
    if (same(now, this.owner)) return;
    log('seat0:', now.kind === 'user' ? 'uid ' + now.uid : now.kind);
    this.owner = now;
    this._apply(false);
  }

  // The socket goes to the seat's owner; whoever had it is dropped (and lets go of everything).
  _apply(confChanged) {
    const o = this.owner;
    const system = this.conf.mode === 'system';
    let uid = 0;
    if (o.kind === 'user') uid = o.uid;
    else if (o.kind === 'greeter' && system) { const a = accountIds(); if (a) uid = a.uid; }
    if (uid !== this.uid || confChanged) {
      this._drop();
      try { fs.chownSync(SOCK, uid, -1); fs.chmodSync(SOCK, 0o600); } catch (e) { log('chown:', e.message); }
      this.uid = uid;
    }
    if (o.kind === 'greeter' && system) this._startNode();
    else this._stopNode();
  }

  _accept(sock) {
    // The file mode already said who may connect; one client at a time, the newest wins.
    this._drop();
    const bin = fs.existsSync(BIN) ? BIN : BIN_ONE;
    const env = { PATH, LANG: 'C.UTF-8', MACSHARE_HELPER_BACKEND: 'uinput' };
    const helper = spawn(bin, [], { stdio: ['pipe', 'pipe', 'pipe'], env });
    const c = { sock, helper, inBuf: '', outBuf: '' };
    this.client = c;
    log('client connected, helper', helper.pid);
    helper.stdout.setEncoding('utf8');
    helper.stdout.on('data', (d) => { if (this.client === c) sock.write(d); });
    helper.stderr.on('data', (d) => log('helper:', String(d).trim()));
    helper.stdin.on('error', () => {});
    helper.on('exit', (code) => {
      log('helper exited', code);
      if (this.client === c) this._drop();
    });
    sock.setEncoding('utf8');
    sock.on('data', (d) => this._fromClient(c, d));
    sock.on('error', () => {});
    sock.on('close', () => { if (this.client === c) this._drop(); });
  }

  _fromClient(c, d) {
    c.inBuf += d;
    if (c.inBuf.length > MAX_LINE) { log('line too long: dropped'); return this._drop(); }
    let i;
    while ((i = c.inBuf.indexOf('\n')) >= 0) {
      const line = c.inBuf.slice(0, i).trim();
      c.inBuf = c.inBuf.slice(i + 1);
      if (!line) continue;
      let msg;
      try { msg = JSON.parse(line); } catch (_) { continue; }
      if (!msg || typeof msg !== 'object' || Array.isArray(msg)) continue;
      if (msg.cmd === 'serviceLog') { c.sock.write(JSON.stringify(serviceLog(msg)) + '\n'); continue; } // its own log, answered here
      if (Unlock.CMDS.has(msg.cmd)) { this.unlock.fromClient(c, msg).then((r) => { if (r && msg.id !== undefined && this.client === c) c.sock.write(JSON.stringify({ id: msg.id, ...r }) + '\n'); }); continue; }
      if (!ALLOWED.has(msg.cmd)) {
        if (msg.id !== undefined) c.sock.write(JSON.stringify({ id: msg.id, ok: false, error: 'not allowed through Full KVM' }) + '\n');
        continue;
      }
      c.helper.stdin.write(JSON.stringify(msg) + '\n');
    }
  }

  // An event for the client (Biometric unlock), if there is one.
  toClient(obj) {
    const c = this.client;
    if (c) try { c.sock.write(JSON.stringify(obj) + '\n'); } catch (_) { /* gone */ }
    return !!c;
  }

  // The client goes: its helper gets EOF, releases every key and button, ungrabs and exits.
  _drop() {
    const c = this.client;
    if (!c) return;
    this.client = null;
    this.unlock.clientGone();
    try { c.helper.stdin.end(); } catch (_) { /* gone */ }
    setTimeout(() => { try { c.helper.kill('SIGKILL'); } catch (_) { /* gone */ } }, 2000).unref();
    try { c.sock.destroy(); } catch (_) { /* gone */ }
    log('client dropped');
  }

  // The machine node (System-wide, the login screen): the mesh without anyone's app, as `twindesk`.
  _startNode() {
    if (this.node) return;
    const a = accountIds();
    const script = path.join(ROOT, 'shared', 'fullkvm', 'headless.js');
    if (!a || !fs.existsSync(script) || !fs.existsSync(path.join(MACHINE, 'device.json'))) {
      log('System-wide: no machine node (', !a ? 'no account' : !fs.existsSync(script) ? 'no headless.js' : 'nothing copied to ' + MACHINE, ')');
      return;
    }
    const env = { PATH, LANG: 'C.UTF-8', HOME: MACHINE, ELECTRON_RUN_AS_NODE: '1', TWINDESK_MACHINE_DIR: MACHINE, TWINDESK_KVM_SOCK: SOCK };
    const node = spawn(process.execPath, [script], { uid: a.uid, gid: a.gid, cwd: MACHINE, env, stdio: ['ignore', 'pipe', 'pipe'] });
    this.node = node;
    log('machine node started', node.pid);
    node.stdout.on('data', (d) => process.stdout.write('[node] ' + d));
    node.stderr.on('data', (d) => process.stderr.write('[node] ' + d));
    node.on('exit', (code) => {
      if (this.node !== node) return;
      this.node = null;
      log('machine node exited', code);
      if (this.owner.kind === 'greeter' && this.conf.mode === 'system') setTimeout(() => this._apply(false), 3000);
    });
  }

  _stopNode() {
    const node = this.node;
    if (!node) return;
    this.node = null;
    node.kill('SIGTERM');
    setTimeout(() => { try { node.kill('SIGKILL'); } catch (_) { /* gone */ } }, 3000).unref();
    log('machine node stopped');
  }
}

// ---- Biometric unlock (docs/full-kvm.md) ----

// The person's account: name ↔ uid, from /etc/passwd or NSS (getent).
async function passwdLine(key) {
  try {
    const line = fs.readFileSync('/etc/passwd', 'utf8').split('\n').find((l) => { const f = l.split(':'); return f[0] === String(key) || f[2] === String(key); });
    if (line) return line.split(':');
  } catch (_) { /* NSS then */ }
  const out = (await run('getent', ['passwd', String(key)])).trim();
  return out ? out.split('\n')[0].split(':') : null;
}

class Unlock {
  constructor(svc) {
    this.svc = svc;
    this.U = require(path.join(ROOT, 'shared', 'fullkvm', 'unlock.js'));
    this.ch = new this.U.Challenges();
    this.reach = new Set(); // the enrolled phones the client can reach now (unlockReach)
    this.ask = true; // the login screen asks the phone by itself (unlockReach's ask; off: only the phone's Unlock)
    this.waits = new Map(); // nonce → { user, done(ok) }: pam_twindesk asking
    this.approved = new Map(); // user → until: the phone said yes before the login screen asked (one use)
    this.cool = new Map(); // user → until: declined or not answered: the password, without waiting
    this.limit = new this.U.Limiter(); // 5 failures in 15 min: no unlocking for 15 min
    this.server = null;
    this.passwd = passwdLine; // tests replace these three
    this.unlockSession = (sid) => run('loginctl', ['unlock-session', sid]);
  }

  // Each person's keys: /etc/twindesk/unlock/<uid>.keys (install.sh unlock-add writes them as root).
  keysOf(uid) {
    try { return this.U.parseKeyLines(fs.readFileSync(path.join(UNLOCK_DIR, uid + '.keys'), 'utf8')).keys; } catch (_) { return []; }
  }

  allKeys() {
    const all = [];
    let names = [];
    try { names = fs.readdirSync(UNLOCK_DIR); } catch (_) { /* nobody enrolled */ }
    for (const f of names) {
      const m = /^(\d+)\.keys$/.exec(f);
      if (m) for (const k of this.keysOf(Number(m[1]))) all.push({ uid: Number(m[1]), key: k });
    }
    return all;
  }

  // The keys the client may know of: the seat's person's own, or (the machine node at the login screen) everyone's.
  visible() {
    const o = this.svc.owner;
    if (o.kind === 'user') return this.keysOf(o.uid).map((key) => ({ uid: o.uid, key }));
    if (o.kind === 'greeter') return this.allKeys();
    return [];
  }

  start() {
    try { fs.unlinkSync(UNLOCK_SOCK); } catch (_) { /* none left */ }
    const old = process.umask(0o177); // root's only: the greeter's and lock screen's PAM run as root
    this.server = net.createServer((sock) => this._pam(sock));
    this.server.listen(UNLOCK_SOCK, () => process.umask(old));
    this.server.on('error', (e) => log('unlock socket:', e.message));
  }

  clientGone() {
    this.reach.clear();
    for (const [nonce, w] of this.waits) { this.waits.delete(nonce); w.done(false); }
  }

  // pam_twindesk.so: {"user","service"}\n → {"wait":"<phone>"}\n … {"ok":true|false}\n
  _pam(sock) {
    let buf = '';
    let asked = false;
    sock.setEncoding('utf8');
    sock.on('error', () => {});
    sock.on('data', async (d) => {
      if (asked) return;
      buf += d;
      if (buf.length > 4096) return sock.destroy();
      const i = buf.indexOf('\n');
      if (i < 0) return;
      asked = true;
      let q = null;
      try { q = JSON.parse(buf.slice(0, i)); } catch (_) { /* no */ }
      const reply = (o) => { try { sock.write(JSON.stringify(o) + '\n'); } catch (_) { /* gone */ } };
      const user = q && typeof q.user === 'string' && this.U.USER.test(q.user) ? q.user : '';
      const pw = user ? await this.passwd(user) : null;
      const uid = pw ? Number(pw[2]) : -1;
      if (!(uid > 0)) return reply({ ok: false }) || sock.end(); // never root
      if (this.limit.locked(user)) { reply({ ok: false }); return sock.end(); }
      const t = Date.now();
      if ((this.approved.get(user) || 0) > t) { this.approved.delete(user); log('unlock: ' + user + ', approved on the phone before'); reply({ ok: true }); return sock.end(); }
      if ((this.cool.get(user) || 0) > t || !this.ask) { reply({ ok: false }); return sock.end(); }
      const keys = this.keysOf(uid).filter((k) => this.reach.has(k.id));
      if (!keys.length) { reply({ ok: false }); return sock.end(); }
      const why = this.svc.owner.kind === 'greeter' ? 'login' : 'lock';
      const nonce = this.ch.make(user, why);
      let over = false;
      const done = (ok) => {
        if (over) return;
        over = true;
        clearTimeout(timer);
        this.waits.delete(nonce);
        this.ch.drop(nonce);
        if (!ok) { this.cool.set(user, Date.now() + 60 * 1000); this.limit.fail(user); }
        this.svc.toClient({ event: 'unlockEnd', nonce, ok });
        reply({ ok });
        sock.end();
      };
      const timer = setTimeout(() => { log('unlock: no answer from the phone'); done(false); }, 25 * 1000);
      this.waits.set(nonce, { user, uid, done });
      sock.on('close', () => { if (!over) { over = true; clearTimeout(timer); this.waits.delete(nonce); this.ch.drop(nonce); this.svc.toClient({ event: 'unlockEnd', nonce, ok: false }); } });
      if (!this.svc.toClient({ event: 'unlockAsk', nonce, user, why, keys: keys.map((k) => k.id) })) return done(false);
      log('unlock: ' + user + ' (' + (q.service || '?') + '), asking ' + keys.map((k) => k.name).join(', '));
      reply({ wait: keys.map((k) => k.name).join(', ') });
    });
  }

  // The client's commands (answered here, like serviceLog).
  async fromClient(c, msg) {
    const U = this.U;
    switch (msg.cmd) {
      case 'unlockInfo': {
        const o = this.svc.owner;
        const locked = o.kind === 'greeter' || (o.kind === 'user' && await this._locked(o.sid));
        return { ok: true, pam: fs.existsSync(UNLOCK_SOCK), seat: o.kind, locked, keys: this.visible().map(({ key }) => ({ id: key.id, name: key.name, kind: key.kind, added: key.added, fp: this.U.fingerprint(key.pub) })) };
      }
      case 'unlockReach': {
        const ids = Array.isArray(msg.keys) ? msg.keys.filter((k) => typeof k === 'string' && U.KEY_ID.test(k)).slice(0, 64) : [];
        this.reach = new Set(ids);
        this.ask = msg.ask !== false;
        return null;
      }
      case 'unlockChallenge': { // the phone's Unlock button: a nonce for the person whose key it is
        const v = this.visible().find((x) => x.key.id === msg.key);
        if (!v) return { ok: false, error: 'this phone isn’t set up to unlock this computer' };
        const pw = await this.passwd(v.uid);
        if (!pw) return { ok: false, error: 'no such account' };
        const user = pw[0];
        if (this.limit.locked(user)) return { ok: false, error: 'Too many tries: wait 15 minutes' };
        const wait = [...this.waits.entries()].find(([, w]) => w.user === user);
        if (wait) return { ok: true, nonce: wait[0], user };
        const o = this.svc.owner;
        if (o.kind === 'user' && !(await this._locked(o.sid))) return { ok: false, error: 'not locked' };
        if (o.kind === 'none') return { ok: false, error: 'not locked' };
        return { ok: true, nonce: this.ch.make(user, o.kind === 'greeter' ? 'login' : 'lock'), user };
      }
      case 'unlockSign': {
        const nonce = String(msg.nonce || '');
        const c0 = this.ch.peek(nonce);
        if (!c0) return { ok: false, error: 'expired' };
        const v = this.visible().find((x) => x.key.id === msg.key);
        const pw = v ? await this.passwd(v.uid) : null;
        if (!v || !pw || pw[0] !== c0.user || !U.verify(v.key.pub, c0.user, nonce, String(msg.sig || ''))) {
          log('unlock: a signature that isn’t right, from ' + (v ? v.key.name : 'an unknown key'));
          this.limit.fail(c0.user);
          return { ok: false, error: 'not verified' };
        }
        this.ch.take(nonce);
        log('unlock: ' + c0.user + ', confirmed on ' + v.key.name);
        const w = this.waits.get(nonce) || [...this.waits.values()].find((x) => x.user === c0.user);
        this.cool.delete(c0.user);
        this.limit.ok(c0.user);
        if (w) { w.done(true); return { ok: true, how: 'pam' }; }
        const o = this.svc.owner;
        if (o.kind === 'user' && o.uid === v.uid && await this._locked(o.sid)) {
          await this.unlockSession(o.sid);
          return { ok: true, how: 'session' };
        }
        if (o.kind === 'greeter') { this.approved.set(c0.user, Date.now() + 30 * 1000); return { ok: true, how: 'next' }; } // choose the account on the login screen
        return { ok: false, error: 'not locked' };
      }
      case 'unlockNo': { // the phone said no (or couldn't): the password, at once
        const w = this.waits.get(String(msg.nonce || ''));
        if (w) w.done(false);
        return null;
      }
      default: return null;
    }
  }

  async _locked(sid) {
    if (!sid) return false;
    return (await run('loginctl', ['show-session', sid, '-p', 'LockedHint', '--value'])).trim() === 'yes';
  }
}
Unlock.CMDS = new Set(['unlockInfo', 'unlockReach', 'unlockChallenge', 'unlockSign', 'unlockNo']);

function main() {
  if (process.getuid && process.getuid() !== 0) { console.error('the Full KVM service runs as root'); process.exit(1); }
  new Service().start();
}

if (require.main === module) main();

module.exports = { ALLOWED, Service, Unlock, readConf, main }; // main: from the installed boot file (install.sh)