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.

8.8 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Apple's developer disk image, for an iPhone's input through the USB cable (iOS 26 and later: the
// remote input comes from it; ios-control mounts it, `--ddi DIR`). Xcode puts it on a Mac it's
// installed on and mounts it itself; a computer without Xcode needs it from somewhere, once:
//   1. a Mac's own Xcode (/Library/Developer/DeveloperDiskImages/iOS_DDI/Restore), used as it is;
//   2. the copy kept here (userData/ios-ddi) from an earlier time;
//   3. a Mac of the mesh that has Xcode: it sends its copy over the session, in parts
//      (ios.ddi.want {id} → ios.ddi.part {id, path, off, data (base64), size} … → ios.ddi.done {id, files}
//      or ios.ddi.none {id});
//   4. the community copy of Apple's files on GitHub (doronz88/DeveloperDiskImage, as pymobiledevice3
//      and iphone-control use), its five files.
// They are Apple's files: never shipped with TwinDesk, only fetched on the computer that needs them.
'use strict';

const fs = require('fs');
const path = require('path');
const https = require('https');
const crypto = require('crypto');
const P = require('./protocol.js');

const T = P.T;
const XCODE = '/Library/Developer/DeveloperDiskImages/iOS_DDI/Restore';
const MIRROR = 'https://raw.githubusercontent.com/doronz88/DeveloperDiskImage/main/PersonalizedImages/Xcode_iOS_DDI_Cryptex';
const MIRROR_FILES = ['BuildManifest.plist', 'Image.dmg', 'Image.dmg.trustcache', 'Image.dmg.cryptex_info', 'Image.dmg.root_hash'];
const READY = '.ready'; // written once a copy is complete
const PART = 64 * 1024;
const MAX_TOTAL = 200 * 1024 * 1024;
const MESH_MS = 120000;

// Every file under dir, relative, with / between folders.
function filesOf(dir, rel = '') {
  const out = [];
  for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
    const r = rel ? `${rel}/${e.name}` : e.name;
    if (e.isDirectory()) out.push(...filesOf(dir, r));
    else if (e.isFile() && !e.name.startsWith('.')) out.push(r);
  }
  return out;
}

// A path from another device: relative, inside dir, nothing odd.
function safe(dir, rel) {
  if (typeof rel !== 'string' || !rel || rel.length > 200 || rel.includes('\\') || rel.split('/').some((p) => !p || p === '.' || p === '..')) return null;
  const full = path.join(dir, rel);
  return full.startsWith(path.join(dir, path.sep)) || full.startsWith(dir + path.sep) ? full : null;
}

class IosDdi {
  // hub: the mesh hub (bus, sessions); dir: where a copy is kept (userData/ios-ddi); xcode() (tests):
  // this computer's Xcode copy, or ''
  constructor({ hub, dir, xcode = IosDdi.xcode }) {
    this.hub = hub;
    this.dir = dir;
    this.xcode = xcode;
    this.busy = null;
    this.incoming = new Map(); // id -> {tmp, resolve, timer, got}
    hub.bus.on(T.IOS_DDI_WANT, (m, from) => this._serve(m, from));
    hub.bus.on(T.IOS_DDI_PART, (m, from) => this._part(m, from));
    hub.bus.on(T.IOS_DDI_DONE, (m, from) => this._done(m, from));
    hub.bus.on(T.IOS_DDI_NONE, (m) => this._none(m));
  }

  static xcode() {
    return process.platform === 'darwin' && fs.existsSync(path.join(XCODE, 'BuildManifest.plist')) ? XCODE : '';
  }

  _kept() {
    return fs.existsSync(path.join(this.dir, READY)) && fs.existsSync(path.join(this.dir, 'BuildManifest.plist')) ? this.dir : '';
  }

  // The image's directory, fetched if needed (once at a time), or '' when there's none to be had.
  ensure() {
    const have = this.xcode() || this._kept();
    if (have) return Promise.resolve(have);
    if (!this.busy) {
      this.busy = (async () => {
        try {
          for (const mac of this._macs()) {
            if (await this._fromMac(mac)) return this.dir;
          }
          if (await this._fromMirror()) return this.dir;
          return '';
        } finally { this.busy = null; }
      })();
    }
    return this.busy;
  }

  _macs() {
    const out = [];
    for (const s of this.hub.sessions.list()) if (s.connected && s.peerOs === P.OS.MAC && s.transport !== 'ble') out.push(s.id);
    return out;
  }

  _fresh(tmp) {
    fs.rmSync(tmp, { recursive: true, force: true });
    fs.mkdirSync(tmp, { recursive: true });
  }

  // The finished copy in tmp becomes the kept one.
  _adopt(tmp) {
    fs.rmSync(this.dir, { recursive: true, force: true });
    fs.renameSync(tmp, this.dir);
    fs.writeFileSync(path.join(this.dir, READY), new Date().toISOString());
  }

  // ---- from a Mac of the mesh ----

  _fromMac(mac) {
    const id = crypto.randomBytes(8).toString('hex');
    const tmp = `${this.dir}.part-${id}`;
    try { this._fresh(tmp); } catch (e) { console.log('[ios] the developer disk image:', e.message); return Promise.resolve(false); }
    return new Promise((resolve) => {
      const timer = setTimeout(() => this._finish(id, false), MESH_MS);
      this.incoming.set(id, { tmp, resolve, timer, got: 0, from: mac });
      console.log(`[ios] asking ${mac} for the developer disk image`);
      this.hub.bus.send(mac, { t: T.IOS_DDI_WANT, id });
    });
  }

  _part(m, from) {
    const r = this.incoming.get(String(m.id || ''));
    if (!r || r.from !== from) return;
    const file = safe(r.tmp, m.path);
    const off = Number(m.off);
    const data = typeof m.data === 'string' ? Buffer.from(m.data, 'base64') : null;
    if (!file || !data || !Number.isInteger(off) || off < 0 || (r.got += data.length) > MAX_TOTAL) return this._finish(m.id, false);
    try {
      fs.mkdirSync(path.dirname(file), { recursive: true });
      const fd = fs.openSync(file, off === 0 ? 'w' : 'r+');
      fs.writeSync(fd, data, 0, data.length, off);
      fs.closeSync(fd);
    } catch (_) { this._finish(m.id, false); }
  }

  _done(m, from) {
    const r = this.incoming.get(String(m.id || ''));
    if (!r || r.from !== from) return;
    const ok = Array.isArray(m.files) && m.files.length > 0 && m.files.every((f) => {
      const file = safe(r.tmp, f && f.path);
      try { return !!file && fs.statSync(file).size === Number(f.size); } catch (_) { return false; }
    });
    this._finish(m.id, ok);
  }

  _none(m) { this._finish(String(m.id || ''), false); }

  _finish(id, ok) {
    const r = this.incoming.get(id);
    if (!r) return;
    this.incoming.delete(id);
    clearTimeout(r.timer);
    try {
      if (ok) this._adopt(r.tmp);
      else fs.rmSync(r.tmp, { recursive: true, force: true });
    } catch (_) { ok = false; }
    console.log(`[ios] the developer disk image from ${r.from}: ${ok ? 'kept' : 'not had'}`);
    r.resolve(ok);
  }

  // A Mac with Xcode sends its copy to a device that asks (one at a time per asker, paced).
  async _serve(m, from) {
    const id = String(m.id || '');
    const dir = this.xcode();
    if (!dir || !/^[0-9a-f]{16}$/.test(id)) return this.hub.bus.send(from, { t: T.IOS_DDI_NONE, id });
    console.log(`[ios] sending the developer disk image to ${from}`);
    const files = [];
    try {
      for (const rel of filesOf(dir)) {
        const buf = fs.readFileSync(path.join(dir, rel));
        for (let off = 0; off < buf.length || off === 0; off += PART) {
          if (!this.hub.bus.send(from, { t: T.IOS_DDI_PART, id, path: rel, off, data: buf.subarray(off, off + PART).toString('base64') })) throw new Error('the session closed');
          if ((off / PART) % 16 === 15) await new Promise((r) => setTimeout(r, 5)); // the session's other messages go too
          if (buf.length === 0) break;
        }
        files.push({ path: rel, size: buf.length });
      }
      this.hub.bus.send(from, { t: T.IOS_DDI_DONE, id, files });
    } catch (e) {
      console.log('[ios] the developer disk image:', e.message);
      this.hub.bus.send(from, { t: T.IOS_DDI_NONE, id });
    }
  }

  // ---- from GitHub ----

  async _fromMirror() {
    const tmp = `${this.dir}.part-mirror`;
    try {
      this._fresh(tmp);
      console.log(`[ios] downloading the developer disk image from ${MIRROR}`);
      for (const name of MIRROR_FILES) await download(`${MIRROR}/${name}`, path.join(tmp, name));
      this._adopt(tmp);
      return true;
    } catch (e) {
      console.log('[ios] the developer disk image download:', e.message);
      fs.rmSync(tmp, { recursive: true, force: true });
      return false;
    }
  }
}

function download(url, to, hops = 5) {
  return new Promise((resolve, reject) => {
    https.get(url, { timeout: 60000 }, (res) => {
      if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location && hops > 0) {
        res.resume();
        return resolve(download(new URL(res.headers.location, url).href, to, hops - 1));
      }
      if (res.statusCode !== 200) { res.resume(); return reject(new Error(`${url}: ${res.statusCode}`)); }
      const out = fs.createWriteStream(to);
      res.pipe(out);
      out.on('finish', resolve);
      out.on('error', reject);
      res.on('error', reject);
    }).on('error', reject).on('timeout', function () { this.destroy(new Error('timed out')); });
  });
}

module.exports = { IosDdi, XCODE, MIRROR };