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.

26.1 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// settings.json: defaults and validation. Every value from
// disk or from the UI goes through normalize(), so main never stores anything out of range.
const P = require('../shared/protocol.js');
const { normRoutes } = require('../shared/sound-route.js');
const CL = require('../shared/cursorlock.js');
const Portals = require('../shared/cursor-portals.js');
// Cursor portals per paired device id: each list as shared/cursor-portals.js accepts it, the rest dropped.
const portalsByPeer = (v) => Object.fromEntries(Object.entries(v && typeof v === 'object' ? v : {})
  .map(([id, rules]) => [id, Portals.normalize(rules)]).filter(([, rules]) => rules).slice(0, 50));
const Crossing = require('../shared/crossing.js');
const { savedLanguage } = require('../shared/i18n.js');
const Look = require('../shared/look.js');
const { normalizeFolder } = require('../shared/received.js');

// The keys that can be held to move a window to the other computer (the helper grabs with them).
const MOVE_KEYS = ['ControlRight', 'ControlLeft', 'ShiftRight', 'ShiftLeft', 'AltRight', 'AltLeft', 'MetaRight', 'MetaLeft'];

const TABS = ['phone', 'overview', 'connection', 'mirror', 'papps', 'calls', 'messages', 'media', 'pfiles', 'mac-pc', 'pc-mac', 'cursor', 'keyboard', 'activity', 'clipboard', 'notifications', 'files', 'mount', 'terminal', 'audio', 'camera', 'remote', 'deck', 'apps', 'rezume', 'multi', 'debug', 'web', 'airplay', 'iossign', 'general', 'about'];

const OLD_TABS = { display: 'mac-pc', receive: 'mac-pc', share: 'pc-mac' }; // older names

const bool = (v, d) => (typeof v === 'boolean' ? v : d);
// Which Bluetooth device each phone is (shared/phonehub.js): {phone's id: device id}, a few.
const btDevices = (v) => Object.fromEntries(Object.entries(v && typeof v === 'object' ? v : {})
  .filter(([k, id]) => typeof k === 'string' && k.length <= 100 && typeof id === 'string' && id).slice(-20).map(([k, id]) => [k, id.slice(0, 400)])); // Windows' device ids are long
// A phone's hotspot as typed once, per phone: {deviceId: {ssid, pass (safeStorage, base64)}}.
const hotspots = (v) => {
  const out = {};
  if (!v || typeof v !== 'object') return out;
  for (const [id, h] of Object.entries(v).slice(0, 20)) {
    if (h && typeof h.ssid === 'string' && typeof h.pass === 'string') out[id.slice(0, 64)] = { ssid: h.ssid.slice(0, 32), pass: h.pass.slice(0, 2000) };
  }
  return out;
};
// A global shortcut (Electron accelerator): Ctrl, Alt or the Windows key, plus one key.
const KEY = /^(?:(?:Control|Alt|Shift|Super)\+){1,4}(?:[A-Z0-9]|F(?:[1-9]|1[0-9]|2[0-4])|Space|Tab|Backspace|Delete|Enter|Up|Down|Left|Right)$/;
const accel = (v, d) => (typeof v === 'string' && KEY.test(v) && /Control|Alt|Super/.test(v) ? v : d);
const num = (v, d, min, max) => (Number.isFinite(Number(v)) && v !== null && v !== '' ? Math.min(max, Math.max(min, Number(v))) : d);

function normalize(s) {
  s = s || {};
  // Every feature is off until it's turned on: a setting a file doesn't hold is off, whatever wrote
  // the file (an old version, the mesh, a half-written one).
  const kvm = s.kvm || {};
  const keys = s.keys || {};
  const c = s.clipboard || {};
  const ui = s.ui || {};
  const mon = s.monitor || {};
  const audio = s.audio || {};
  const term = s.terminal || {};
  const files = s.files || {};
  const pcs = s.pcScreen || {};
  const pca = s.pcApps || {};
  const mca = s.macApps || {};
  const setup = s.setup || {};
  const appS = s.app || {};
  const up = s.updates || {};
  const nf = s.notifs || {};
  const wk = s.wake || {};
  const ph = s.phone || {};
  const mt = s.mount || {};
  const dr = s.drive || {};
  const hub = s.hub || {};
  const nt = s.net || {};
  return {
    rev: 12, // settings revision (upgrades in normalize, like the Mac's store.js)
    kvm: {
      jumps: require('../shared/jumpkeys.js').clean(kvm.jumps), // Multi-device jump shortcuts (shared/jumpkeys.js)
      mouse: bool(kvm.mouse, false),
      keyboard: bool(kvm.keyboard, false),
      driveOther: bool(kvm.driveOther, true),
      beDriven: bool(kvm.beDriven, true),
      resistancePx: Math.round(num(kvm.resistancePx, P.RESISTANCE_PX, 0, 400)),
      crossingModifier: Crossing.modifier(kvm.crossingModifier), // held to leave this computer at an edge ('' none, #230)
      stayFullscreen: bool(kvm.stayFullscreen, false), // #373: no leaving at an edge while an app is fullscreen
      portalsOn: bool(kvm.portalsOn, false), // Cursor portals (Mouse › Cursor portals): off by default; on, Hold key to switch steps aside
      portalsByPeer: portalsByPeer(kvm.portalsByPeer), // each paired computer's portals (shared/cursor-portals.js)
      pcSide: P.SIDES.includes(kvm.pcSide) ? kvm.pcSide : null, // where this PC is, seen from the other computer (kvm.layout)
      along: typeof kvm.along === 'number' && Number.isFinite(kvm.along) ? Math.round(kvm.along) : null, // the other computer along our side, points (shared/kvm-geom.js); null: centred
      speed: Math.round(num(kvm.speed, 1.0, 0.25, 3) * 100) / 100,
      reverseScroll: bool(kvm.reverseScroll, false),
      linked: bool(kvm.linked, true), // cursor sharing on (the hotkey's double-tap switches it, kvm.link)
      // The last `linked` per paired device id, restored on connect
      linkedBy: kvm.linkedBy && typeof kvm.linkedBy === 'object'
        ? Object.fromEntries(Object.entries(kvm.linkedBy).filter(([, v]) => typeof v === 'boolean').slice(0, 50)) : {},
      gestures: bool(kvm.gestures, true), // Trackpad gestures work on the other computer (pair.sync 'gestures')
      shakeHome: bool(kvm.shakeHome, false), // shake this computer's mouse while driving: the pointer comes home (the helper's shake)
      syncPads: bool(kvm.syncPads, false), // every mouse and trackpad moves the one pointer; off: this PC's own takes it back (pair.sync 'syncPads')
      hotkeySwitch: bool(kvm.hotkeySwitch, false), // keyboard only (Cursor off): double-tap moves the keyboard over and back
      ble: bool(kvm.ble, true), // cursor sharing while the session runs through Bluetooth (pair.sync 'ble')
    },
    // hotkey: double-tap = mouse and keyboard home. lockKeys: cursor lock on/off (shared/cursorlock.js)
    keys: { swapCtrlCmd: bool(keys.swapCtrlCmd, true), hotkey: P.HOTKEYS.includes(keys.hotkey) ? keys.hotkey : P.HOTKEY_WIN, lockKeys: CL.validKeys(keys.lockKeys, CL.DEFAULT_KEYS.linux), emergencyKeys: Crossing.emergency(keys.emergencyKeys), modMap: require('../shared/modmap.js').clean(keys.modMap) }, // emergencyKeys: everything home, sharing off (#178)
    // hud: popup when switching computers. inputProtocol: udp = tdv2 input lane (default), tcp = tdv1
    app: { hud: bool(appS.hud, true), keepAwake: bool(appS.keepAwake, true), keepAwakeAlways: appS.keepAwakeAlways === true, inputProtocol: appS.inputProtocol === 'tcp' ? 'tcp' : 'udp', keepPinging: appS.keepPinging === true, proximityLock: appS.proximityLock === true, localApi: appS.localApi === true, lockTogether: appS.lockTogether === true }, // keepAwakeAlways: General › Keep the display awake › Always, connected or not (shared/keepawake.js) // lockTogether: General › Lock together (shared/locksync.js) // localApi: General › Local API (shared/localapi.js) // keepPinging: General › Advanced (shared/quiet.js)
    // New releases on GitHub (shared/updates.js); notified = the last version announced, skipped = version ignored
    updates: { auto: bool(up.auto, true), notified: typeof up.notified === 'string' ? up.notified.slice(0, 40) : '', skipped: typeof up.skipped === 'string' ? up.skipped.slice(0, 40) : '', install: up.install === true }, // install: install new versions by themselves (shared/selfupdate.js)
    clipboard: {
      enabled: bool(c.enabled, false),
      send: bool(c.send, true),
      receive: bool(c.receive, true),
      // Pictures too, up to 10 MB (shared/clipimage.js), screenshots put on the clipboard among them
      images: bool(c.images, false),
      // Instant by default; files from before it (no rev) are upgraded once
      mode: c.mode === 'switch' && (s.rev || 0) >= 7 ? 'switch' : 'instant',
      skipConcealed: bool(c.skipConcealed, true),
      maxKB: Math.round(num(c.maxKB, 256, 1, P.CLIP_MAX_BYTES / 1024)),
      historySize: Math.round(num(c.historySize, 20, 0, 100)),
      queue: bool(c.queue, true), // copies made while the other device is away go to its Recent when it's back (shared/clipqueue.js)
      queueLatest: bool(c.queueLatest, false), // … and the latest of those it sends lands on this clipboard
    },
    monitor: {
      volume: Math.round(num(mon.volume, 1, 0, 1) * 100) / 100,
      mute: bool(mon.mute, false),
      // Playback of shared screens, both directions, the same on both computers (pair.sync
      // 'pace'): 'fast' (default, shown the moment it is decoded) | 'smooth' (about a frame of buffer) |
      // 'steady' (no zero playout delay on the stream: WebRTC paces it itself, as a web browser plays it)
      pacing: ['smooth', 'steady'].includes(mon.pacing) && (s.rev || 0) >= 8 ? mon.pacing : 'fast', // rev 8: back to Fastest once
      framegen: bool(mon.framegen, false), // in-between frames on the GPU (shared/framegen.js), off by default
    },
    // Remote tab (shared/phone-remote.js): the phone's Remote page moves the pointer and types here
    // Real gamepad (pad): its sticks and buttons as a controller here, off until turned on
    remote: { allow: bool((s.remote || {}).allow, false), pad: bool((s.remote || {}).pad, false), padKind: (s.remote || {}).padKind === 'ds4' ? 'ds4' : 'xbox' },
    // TwinDesk Web (shared/web/webwire.js): off until turned on; what new web devices may do.
    web: (() => {
      const w = s.web || {};
      const port = Number(w.port);
      return { on: bool(w.on, false), port: Number.isInteger(port) && port >= 1024 && port < 65000 ? port : 47870,
        screen: bool(w.screen, true), control: bool(w.control, true), camera: bool(w.camera, true), mic: bool(w.mic, true), pad: bool(w.pad, false),
        airplay: bool(w.airplay, false), // Receive AirPlay (shared/airplay), off until turned on
        airplayMusic: bool(w.airplayMusic, true), airplaySound: bool(w.airplaySound, true), airplayFull: bool(w.airplayFull, false) }; // its switches
    })(),
    // ReZume tab (shared/rezume.js): off until turned on; what goes, which ways, where it shows
    rezume: require('../shared/rezume.js').normalize(s.rezume),
    // Camera tab (shared/camshare.js): this computer's camera to the other one, off until turned
    // on; device: which camera (a deviceId), '' = the default one; virtual: the running camera's
    // picture also goes to the virtual camera (shared/vcam.js), off until turned on; rotate: its
    // picture turned clockwise (0, 90, 180, 270)
    // on: the Camera tab's switch (camshare.js and vcam.js loaded only while it's on)
    camera: {
      // Off until turned on, even for settings from before it had a switch; rev 9: off once unless shared
      on: (s.rev || 0) < 9 && !bool((s.camera || {}).share, false) ? false : bool((s.camera || {}).on, false),
      share: bool((s.camera || {}).share, false),
      virtual: bool((s.camera || {}).virtual, false),
      rotate: [0, 90, 180, 270].includes((s.camera || {}).rotate) ? s.camera.rotate : 0,
      device: typeof (s.camera || {}).device === 'string' ? s.camera.device.slice(0, 200) : '',
    },
    audio: {
      receive: bool(audio.receive, false), // play the Mac's sound here (audio.policy W→M)
      volume: Math.round(num(audio.volume, 1, 0, 1) * 100) / 100,
      send: bool(audio.send, false), // send this PC's sound to the Mac (dir w2m)
      muteLocal: bool(audio.muteLocal, false), // silence this PC while sending
      routes: normRoutes(audio.routes), // the mixer: each sender's sound on which of our speakers, how loud (shared/sound-route.js)
      sync: bool(audio.sync, false), // Keep speakers in sync: our sound held to one delay on every receiver
      // This computer's own sound (Audio › the mixer, This device): 'system' plays on the default output only, as
      // always; 'custom' also on the speakers picked (ownOuts [{id, vol, delay}], shared/own-sound.js)
      ownMode: audio.ownMode === 'custom' ? 'custom' : 'system',
      ownOuts: (Array.isArray(audio.ownOuts) ? audio.ownOuts : []).filter((o) => o && typeof o.id === 'string' && o.id && o.id !== 'default').slice(0, 8)
        .map((o) => ({ id: o.id.slice(0, 200), vol: Math.round(num(o.vol, 1, 0, 1) * 100) / 100, delay: Math.round(num(o.delay, 0, 0, 1000)) })),
      // A phone: its media controls on Overview (shared/nowplaying.js), and its sound here over
      // Bluetooth, this computer as its speaker (shared/btaudio.js), off until turned on
      phoneMedia: bool(audio.phoneMedia, false),
      phoneBt: bool(audio.phoneBt, false),
      // Microphone (shared/mic.js): this computer's to the other (micSend), the other's here (micReceive),
      // off until turned on; micDevice: the microphone sent, micOut: where the other's plays ('' = found)
      micSend: bool(audio.micSend, false),
      micReceive: bool(audio.micReceive, false),
      micDevice: typeof audio.micDevice === 'string' ? audio.micDevice.slice(0, 200) : '',
      micOut: typeof audio.micOut === 'string' ? audio.micOut.slice(0, 200) : '',
      phoneBtDevice: typeof audio.phoneBtDevice === 'string' ? audio.phoneBtDevice.slice(0, 400) : '',
    },
    terminal: {
      enabled: bool(term.enabled, false), // shell on the Mac from this PC
      allowMac: bool(term.allowMac, false), // let the Mac open a shell here (needs OpenSSH Server)
      installedKey: typeof term.installedKey === 'string' ? term.installedKey : '', // digest of the last key line we installed ('': none of ours)
      // Each device's installed line, by its id (Multi-device: switching between two devices with keys
      // rewrote authorized_keys every time, behind an administrator prompt on Windows).
      installedKeys: Object.fromEntries(Object.entries(term.installedKeys && typeof term.installedKeys === 'object' ? term.installedKeys : {})
        .filter(([k, v]) => /^[A-Za-z0-9._-]{1,64}$/.test(k) && /^[0-9a-f]{64}$/.test(v)).slice(0, 32)),
    },
    files: {
      dropToMac: bool(files.dropToMac, false),
      shelf: bool(files.shelf, false), // File Shelf: shake a dragged file to open it (shared/shelf-watch.js)
      clipReceived: bool(files.clipReceived, false), // Put received files on the clipboard (filerecv.js)
      outboxHours: [0, 1, 24, 168].includes(files.outboxHours) ? files.outboxHours : 24, // Keep files to send (shared/outbox.js), 0 = off
      shareOn: bool(files.shareOn, false), // set only by a successful share setup (smb.js)
      shareFolder: typeof files.shareFolder === 'string' ? files.shareFolder : '',
      mountMac: bool(files.mountMac, false),
      mountFrom: Array.isArray(files.mountFrom) ? files.mountFrom.filter((x) => typeof x === 'string').slice(0, 32) : 'all', // Multi-device: whose shared folders connect here (shared/smb-mesh.js)
      acceptFromMac: bool(files.acceptFromMac, false), // files dragged from the Mac across the edge
      edgeDrag: bool(files.edgeDrag, false), // drag files/folders across the screen edge, both ways (drag.policy)
      // Copy and paste files with two global shortcuts (fclip.js)
      shortcuts: bool(files.shortcuts, false),
      copyKeys: accel(files.copyKeys, 'Control+Alt+C'),
      pasteKeys: accel(files.pasteKeys, 'Control+Alt+V'),
      plain: bool(files.plain, false), // Encrypt file transfers off: plain HTTP for file bytes where both allow it (shared/fastfile.js fxPlain)
      receivedFolder: normalizeFolder(files.receivedFolder), // General › Received files ('' = Downloads; shared/received.js)
    },
    notifs: { // (notifs.js): muted = apps never sent
      send: bool(nf.send, false),
      receive: bool(nf.receive, false),
      hideText: bool(nf.hideText, false),
      batteryAlerts: bool(nf.batteryAlerts, false),
      muted: Array.isArray(nf.muted) ? nf.muted.filter((x) => typeof x === 'string').map((x) => x.slice(0, 300)).slice(0, 500) : [],
      ...require('../shared/notifrules.js').saved(nf), // style, otpCopy, quiet, phoneApps: how a phone's show here
    },
    pcScreen: { // Display › PC → Mac; Off/Mirror/Extend itself is never saved
      monitor: typeof pcs.monitor === 'string' ? pcs.monitor : '', // Electron display id for Mirror ('' = main)
      mbps: [10, 20, 30, 50, 80].includes(pcs.mbps) ? pcs.mbps : 30, // same presets as the Mac
      maxHeight: [0, 1080, 1440, 2160].includes(pcs.maxHeight) ? pcs.maxHeight : 1080, // stream size (0 = full pixels)
      fps: [0, 30, 60].includes(pcs.fps) ? pcs.fps : 0, // frame rate cap (0 = the display's refresh rate)
      extendSize: ['mac', '1920x1080', '2560x1440', '3840x2160'].includes(pcs.extendSize) ? pcs.extendSize : 'mac', // the virtual monitor
      sound: bool(pcs.sound, false), // the screen's sound in the same session
      input: bool(pcs.input, true), // the Mac's mouse and keyboard drive this PC
      codec: pcs.codec === 'h265' ? 'h265' : 'h264', // Encoder (shared/screencodec.js)
      remote: bool(pcs.remote, true), // The viewer may start/stop and switch it (screen.ctl)
    },
    pairSync: pairSync(s.pairSync), // {deviceId: {feature: {out, in}}} (pairsync.js)
    drop: require('../shared/drop.js').normalize(s.drop), // Drop: on, and the devices blocked there (shared/drop.js)
    fullkvm: { unlock: bool((s.fullkvm || {}).unlock, false), unlockAsk: (s.rev || 0) >= 12 ? bool((s.fullkvm || {}).unlockAsk, false) : false /* rev 12: the phone is asked only when Unlock is pressed, once off for everyone */, unlockPhones: bool((s.fullkvm || {}).unlockPhones, true), unlockComputers: bool((s.fullkvm || {}).unlockComputers, false) }, // Full KVM › Biometric unlock (shared/fullkvm/unlock-host.js), off until switched on; unlockAsk: the lock screen asks by itself (on); who may unlock: phones (on), computers (off)
    wake: { peers: wakePeers(wk.peers) }, // {deviceId: {name, os, macs, address, at}} from wol.info
    // moveWindows: the move key held, a window clicked and dragged past the shared edge goes to the
    // other computer (shared/movewin.js), off until switched on; moveKey: which key.
    pcApps: { allow: bool(pca.allow, false), moveWindows: bool(pca.moveWindows, false), moveKey: MOVE_KEYS.includes(pca.moveKey) ? pca.moveKey : 'ControlRight' },
    // A phone as the peer: its screen window, apps and setup
    phone: {
      sound: bool(ph.sound, false),
      bitrateMbps: Math.round(num(ph.bitrateMbps, 8, 2, 40)),
      maxSize: [0, 1920, 1600, 1280, 1024].includes(ph.maxSize) ? ph.maxSize : 0,
      wallpaper: bool(ph.wallpaper, true),
      input: ph.input === 'phone' ? 'phone' : 'adb', // the mouse and keyboard through adb, or the phone's Accessibility service
      inputPicked: bool(ph.inputPicked, false), // not picked: automatic (phone-bridge.js inputMode)
      // The screen and the sound: through wireless debugging or the phone itself (shared/phonemodes.js)
      mirror: ['adb', 'native'].includes(ph.mirror) ? ph.mirror : 'auto',
      soundVia: ['adb', 'native'].includes(ph.soundVia) ? ph.soundVia : 'auto',
      panel: bool(ph.panel, true), // the phone windows' controls in the title bar (its panel button hides them)
      // Keys in a phone window and on the phone (shared/phonechat.js): Enter sends in WhatsApp,
      // Instagram and Telegram (Shift+Enter a new line); the arrow keys swipe the screen.
      enterSends: bool(ph.enterSends, true),
      enterAll: bool(ph.enterAll, false), // Enter sends in every app, through the phone's Accessibility (#359)
      uhid: bool(ph.uhid, false), // Type as a hardware keyboard (shared/uhidkbd.js)
      arrowSwipe: bool(ph.arrowSwipe, false),
      hover: bool(ph.hover, true), // the mouse hovers over the phone (#330); off: only presses and drags reach it
      // Mirroring over wireless debugging: past adbd straight over the Wi-Fi (scrcpy.js), and the
      // encoder's low-latency profile.
      direct: bool(ph.direct, false),
      lowLatency: bool(ph.lowLatency, false),
    },
    // Bluetooth for devices not on this network (blepipe.js, netlink.js): with phones (ble), with computers (blePc);
    // bleWifiOff: none at all while the session is on the same Wi-Fi (blepolicy.js wifiQuiet)
    net: { ble: bool(nt.ble, true), blePc: bool(nt.blePc, false), bleWifiOff: bool(nt.bleWifiOff, true), hotspots: hotspots(nt.hotspots), keepWifi: bool(nt.keepWifi, true), tailscale: bool(nt.tailscale, true), bleInput: bool(nt.bleInput, false), fallback: bool(nt.fallback, false), iface: typeof nt.iface === 'string' ? nt.iface.replace(/[^\w.:@-]/g, '').slice(0, 32) : '', relay: require('../shared/relay.js').clean(nt.relay) }, // relay: your own (shared/relay.js), none by default // tailscale: shared/tailnet.js; bleInput: shared/bleinput.js
    mount: { on: bool(mt.on, false) }, // the phone as a drive (phonedrive.js), only when Mount is clicked
    drive: { on: bool(dr.on, false), folder: typeof dr.folder === 'string' ? dr.folder.slice(0, 1024) : '', ...require('../shared/drive-folders.js').clean(dr) }, // File Sharing › TwinDesk Shared folders (shared/drive-host.js); '' = ~/TwinDesk Drive; devices and the shared folders (shared/drive-folders.js)
    // Calls, Messages, Photos and Files from a phone (shared/phonehub.js), each off until switched on.
    // callAudio: the calls' sound here over Bluetooth; btDevices: which paired Bluetooth device each
    // phone is (its device id -> the Bluetooth device's id), found by its name or picked.
    hub: {
      calls: bool(hub.calls, false), messages: bool(hub.messages, false), media: bool(hub.media, false), files: bool(hub.files, false),
      callAudio: bool(hub.callAudio, true), btDevices: btDevices(hub.btDevices),
      callPause: bool(hub.callPause, false), // pause what plays here during a call (shared/callpause.js)
      // Shared folders (shared/foldershare.js), both ways, off until switched on.
      shareMount: bool(hub.shareMount, false), shareServe: bool(hub.shareServe, false), shareFolder: typeof hub.shareFolder === 'string' ? hub.shareFolder.slice(0, 1000) : '',
      tether: bool(hub.tether, false), // Internet over USB (shared/tether.js)
      phoneNet: bool(hub.phoneNet, false), // the phone's internet here (shared/phonenet.js, #361)
    },
    macApps: { on: bool(mca.on, false) }, // The other computer's apps open here (pair.sync 'apps' in) // The Mac may open this PC's apps (it shows them only if it accepts)
    // Setup screen: shown once. done: everything was ready, or 'Skip for now' was pressed; after that
    // General and Display show what's missing (a firewall that changes with the network, a helper
    // that restarts, a phone connecting don't bring the screen back).
    setup: { skipped: Array.isArray(setup.skipped) ? setup.skipped.filter((x) => typeof x === 'string').slice(0, 10) : [], done: bool(setup.done, Array.isArray(setup.skipped) && setup.skipped.length > 0) },
    // overview: what Overview shows (General › Overview); chats: Messages' chat apps; language: the UI's ('' = the system's).
    ui: { tab: OLD_TABS[ui.tab] || (TABS.includes(ui.tab) ? ui.tab : 'overview'), overview: overviewParts(ui.overview), chats: bool(ui.chats, false), language: savedLanguage(ui.language),
      style: Look.style(ui.style), theme: Look.theme(ui.theme), accent: Look.accent(ui.accent) }, // General › Appearance (shared/look.js)
    windows: s.windows && typeof s.windows === 'object' ? s.windows : {},
    modules: require('../shared/modules.js').normalize(s.modules), // General › Modules
    deck: s.deck && typeof s.deck === 'object' && JSON.stringify(s.deck).length < 400000 ? s.deck : null, // the Deck's layout (shared/deck-model.js normalizes it when read)
    // OBS Studio for the Deck's OBS tiles (shared/obs.js): its port and the password, sealed.
    deckObs: s.deckObs && typeof s.deckObs === 'object' ? { port: Number.isInteger(s.deckObs.port) && s.deckObs.port > 0 && s.deckObs.port < 65536 ? s.deckObs.port : 4455, pass: typeof s.deckObs.pass === 'string' && s.deckObs.pass.length < 2000 ? s.deckObs.pass : '' } : null,
  };
}

function overviewParts(o) {
  const v = o && typeof o === 'object' ? o : {};
  return { media: bool(v.media, true), qs: bool(v.qs, true), notifs: bool(v.notifs, true), apps: bool(v.apps, true), clipboard: bool(v.clipboard, true), files: bool(v.files, true) };
}

// pair.sync values per paired device: booleans only, at most 20 devices.
function pairSync(v) {
  const out = {};
  if (!v || typeof v !== 'object') return out;
  for (const [id, feats] of Object.entries(v).slice(0, 20)) {
    if (!feats || typeof feats !== 'object') continue;
    out[id] = {};
    for (const [f, d] of Object.entries(feats).slice(0, 10)) {
      if (f === 'values') {
        out[id].values = {};
        if (d && ['fast', 'smooth', 'steady'].includes(d.pace)) out[id].values.pace = d.pace;
        if (d && typeof d.gestures === 'boolean') out[id].values.gestures = d.gestures;
        if (d && typeof d.keyboard === 'boolean') out[id].values.keyboard = d.keyboard; // with a phone
        if (d && typeof d.reverseScroll === 'boolean') out[id].values.reverseScroll = d.reverseScroll;
        if (d && Number.isFinite(d.speed)) out[id].values.speed = Math.min(3, Math.max(0.25, d.speed));
      }
      else if (d && typeof d === 'object') out[id][f] = { out: d.out === true, in: d.in === true };
    }
  }
  return out;
}

// wol.info per paired device, as wake.js stored it (at most 20, MAC addresses checked).
function wakePeers(v) {
  const out = {};
  if (!v || typeof v !== 'object') return out;
  for (const [id, p] of Object.entries(v).slice(0, 20)) {
    const macs = p && Array.isArray(p.macs) ? p.macs.filter((m) => typeof m === 'string' && /^[0-9a-f]{2}(:[0-9a-f]{2}){5}$/.test(m)).slice(0, 8) : [];
    if (!macs.length) continue;
    out[id] = { name: String(p.name || '').slice(0, 200), os: String(p.os || ''), macs, address: typeof p.address === 'string' ? p.address.slice(0, 64) : '', at: Number(p.at) || 0 };
  }
  return out;
}

// Merge a partial change from the UI into one section and re-validate.
function apply(settings, section, partial) {
  if (!partial || typeof partial !== 'object' || !(section in settings)) return false;
  const next = normalize({ ...settings, [section]: { ...settings[section], ...partial } });
  const changed = JSON.stringify(next[section]) !== JSON.stringify(settings[section]);
  settings[section] = next[section];
  return changed;
}

module.exports = { MOVE_KEYS, normalize, apply };