Skip to content

Latest commit

 

History

History
256 lines (178 loc) · 22.7 KB

README.md

File metadata and controls

256 lines (178 loc) · 22.7 KB

Magic Switch app icon

Magic Switch

Mac App Store       GitHub Releases       Homebrew

Mac App Store  ·  GitHub Releases  ·  Homebrew

A macOS menu-bar utility that hands off Magic Keyboard, Magic Trackpad, and Magic Mouse between two Macs with one click — no KVM, no cables.

This is a security-hardened fork of HoshimuraYuto/blue-switch, whose LAN protocol is unauthenticated and unencrypted: anyone on the same Wi-Fi can take over your Bluetooth peripherals or spoof notifications. Magic Switch replaces it with an encrypted, mutually authenticated channel keyed by a pairing code you share between your two Macs.

If you'd like to say thanks for Magic Switch, you can do so through GitHub Sponsors.

The Magic Switch menu-bar dropdown
It lives in the menu bar: click your other Mac to move every peripheral between the two, or a peripheral to move just that one.

Installation

Get it from the Mac App Store, which keeps it up to date for you, or with Homebrew:

brew install --cask megamansec/tap/magic-switch

Or download app.zip from the releases page, unzip it, and move Magic Switch.app to /Applications. To check that the download was built by this repository's GitHub Actions, run gh attestation verify app.zip --repo MegaManSec/magic-switch with the GitHub CLI.

When macOS asks, allow Bluetooth and Local Network (only macOS 15 and later ask for Local Network); Magic Switch needs both. Also allow Notifications, or a switch started from a keyboard shortcut, the URL scheme or a display fails silently. You can change all three later in System Settings.

Setup

Install Magic Switch on both Macs. Steps 2 and 3 happen on both; steps 1, 4 and 5 on just one.

  1. Pair your peripherals with one Mac. In System Settings → Bluetooth, pair your Magic Keyboard, Trackpad or Mouse with one of the Macs as usual. Don't also pair them with the other Mac: that can break this Mac's pairing, and the other Mac pairs each one itself the first time it takes it.

  2. Link the two Macs. Click the Magic Switch menu-bar icon → Settings → Pairing. Click Generate Code on one Mac, then Enter Code on the other and type the same code. Both Macs then show the same eight-character fingerprint. If they don't, the code was mistyped.

    Generated pairing code dialog Enter pairing code dialog
    The code one Mac generates, and the box on the other Mac where you type it.

    Pairing tab after pairing, showing the fingerprint
    Once paired, both Macs show the same fingerprint.

  3. Pick the other Mac. On the Macs tab, choose your other Mac under Macs Found on the Network. If it never shows up, see If the Macs can't find each other.

    Macs tab showing the connected Mac and available Macs
    Macs tab: pick the other Mac, sync peripherals to it, and check it's reachable.

  4. Register your peripherals. On the Peripherals tab of the Mac from step 1, click + beside each peripheral you want Magic Switch to move. A keyboard that needs a code typed on it each time it switches says so in its row; see Older keyboards that need a code.

    Peripherals tab showing registered and available peripherals
    Peripherals tab: register the peripherals you want to hand off.

  5. Sync them to the other Mac. On the Macs tab, click Sync (the circular arrows) beside your other Mac.

That's it. Each switch unpairs a peripheral from one Mac and pairs it with the other, because a Magic device only reconnects to the last Mac it used. You never pair it by hand again.

If a peripheral won't connect

Switch it off and on.

A Magic keyboard, trackpad or mouse waits for the last Mac it used. If that Mac went to sleep, shut down or moved out of range while it still had the peripheral, the peripheral can get stuck waiting for it and ignore your other Mac. Switching it off and on makes it accept a new connection.

Usually that's all you need to do, because Magic Switch is already trying to connect it. When a peripheral should come to this Mac but doesn't connect, this Mac looks for it every few seconds for 10 minutes and connects it as soon as it's back on. That happens after:

  • a switch to this Mac: from either Mac's menu, a keyboard shortcut, the URL scheme, or a marked display;
  • a handoff: your other Mac gave this Mac its peripherals as it went to sleep or shut down;
  • a drop: a peripheral dropped off this Mac;
  • a wake: this Mac woke up, for what it had before sleeping and what an unreachable other Mac left behind;
  • your other Mac going offline: for what that Mac had.

This needs Settings → Other → Reconnect peripherals if they drop on (the default) on this Mac. It never takes a peripheral your other Mac is using. After a failed attempt to bring a peripheral back, its row in the menu says Switch it off and on to connect while Magic Switch keeps trying.

If the peripheral isn't back a few seconds after you switch it on, click it in the menu. That's needed once the 10 minutes are up, or when Reconnect peripherals if they drop is off.

If your other Mac is awake but greyed out in the menu, Magic Switch can't ask it to let go, and switching the peripheral off and on just sends it back there. Fix the connection first: see If the Macs can't find each other.

If nothing else works, connect the peripheral to the Mac with its charging cable. That pairs it with that Mac.

To run into this less, leave Release peripherals when this Mac sleeps enabled on both Macs (see Settings).

Example

You work on a MacBook plugged into a desk display, next to an iMac. On the MacBook, the display is marked under Take Peripherals When a Display Connects. In the evening you shut the iMac down while it has the keyboard and trackpad. A desktop Mac keeps its peripherals when it shuts down, so they keep waiting for the iMac.

The next morning you plug the MacBook into the display, and it tries to take the keyboard and trackpad. Neither answers. You switch each one off and on, and a few seconds later both are on the MacBook. You never open the menu.

Usage

  • Menu → your other Mac: move every peripheral between the two Macs. If they're here, they go there; if they're there, they come here.
  • Menu → a peripheral: move just that one. A checkmark marks what's on this Mac, with its battery level.
  • Keyboard shortcuts: record them under Settings → Other → Keyboard Shortcuts to send, take or toggle every peripheral from anywhere in macOS.

The menu-bar icon shows a warning triangle when Magic Switch needs attention (hover for the reason), an arrow while peripherals move between Macs, a bell when the other Mac pings this one, and a filled background while peripherals are connected to this Mac.

URL scheme

Anything that can open a URL (Raycast, BetterTouchTool, the Shortcuts app, a shell script) can trigger the same switches as the menu:

open -g "magicswitch://switch"                                      # everything, like clicking the other Mac in the menu
open -g "magicswitch://switch?direction=take"                       # bring everything to this Mac
open -g "magicswitch://switch?peripheral=trackpad&direction=take"   # just the trackpad(s)
open -g "magicswitch://switch?peripheral=trackpad&peripheral=mouse" # repeat peripheral= for several
  • peripheral (repeatable): a MAC address (aa-bb-cc-dd-ee-ff), a type (keyboard, mouse, trackpad, headphones, airpods, microphone; a peripheral's icon on the Peripherals tab shows its type, and clicking the icon changes it), or a device name in any case. Leave it out for every registered peripheral.
  • direction: take (to this Mac), send (to the other Mac), or toggle (the default, like a menu click). Bind take and send to hotkeys: repeating one does nothing once the peripherals are there.

Run it on the Mac that should act; -g keeps your current app focused. take works even while the other Mac is asleep or offline. Errors show up as notifications.

Settings

Settings → Other holds the rest:

  • Open at Login (macOS 13 and later).
  • Connect over Bluetooth when the network can't: see If the Macs can't find each other.
  • Release peripherals when this Mac sleeps (on by default; "…sleeps or shuts down" on a Mac laptop): closing or sleeping this Mac hands its peripherals to your other Mac, or frees them for it, instead of leaving them waiting for a sleeping Mac. A Mac laptop also hands them over as it shuts down, if your other Mac is awake to take them. A desktop Mac keeps them when it shuts down, so it has them at the login window when it starts up. If both Macs end up asleep, freed peripherals belong to neither and may need a key press right after waking, or switching off and on. Turned off, peripherals stay paired with this Mac while it sleeps or is off, and the other Mac needs the off-and-on instead.
  • Reconnect peripherals if they drop (on by default): the 10-minute retries in If a peripheral won't connect.
  • Switch peripherals without unpairing them (off by default): reconnect peripherals instead of pairing them again, for ones that stay paired with both Macs at once. Leave it off with Apple's Magic keyboards, trackpads and mice, and older Apple keyboards: with it on, they go back to the last Mac they used.
  • Keyboard Shortcuts: send, take or toggle every peripheral. A take shortcut works even while the other Mac is asleep.
  • Take Peripherals When a Display Connects: mark your desk's display, and connecting this Mac to it takes your peripherals over, as in the example; so does starting Magic Switch while it's connected. Click the sunrise button on its row to have waking up while connected count too.
  • Updates: see Updates.

Other tab showing all app preferences
The Other tab.

If the Macs can't find each other

  • The network blocks Bonjour (some MDM-managed Macs, some Wi-Fi networks): once both Macs are paired, click + on the Macs tab of either one and enter the address and port shown in the other's + sheet. Allow TCP port 41952 (or the port the sheet shows) through any firewall between them.
  • The network keeps the Macs apart (a VPN that blocks local traffic, or Wi-Fi that isolates devices): turn on Connect over Bluetooth when the network can't in Settings → Other on both Macs. They then reach each other over Bluetooth while in range, still encrypted, and a Mac reached that way shows an antenna badge.
  • Both Macs changed IP address at once on a network that blocks Bonjour: add the other Mac by address again, from either side.

The Add a Mac by Address sheet
The + sheet shows this Mac's address and port, to enter on the other Mac.

Older keyboards that need a code

Older keyboards, such as Apple's Wireless Keyboard that runs on AA batteries, use an older kind of Bluetooth pairing that only finishes once a code is typed on the keyboard itself, and Magic Switch pairs a peripheral again on every switch. When the keyboard needs the code, the Mac pairing it shows a window: type 0 on the keyboard, then press Return. Nothing appears on screen while you type. Once the keyboard connects, the window says so and closes. The window can't appear over the lock screen, so if that Mac is locked, just type 0 and press Return. Once a keyboard has asked for the code, its row in the Peripherals tab says Needs a code to switch.

The window asking to type 0 on the keyboard, then press Return

  • If a switch doesn't finish, click the keyboard in the menu on the Mac you want it on. That Mac shows the window again when the keyboard asks for the code.
  • If your other Mac can't take the keyboard, for example because it isn't in that Mac's list, the Mac you sent it from takes it back and shows the window.
  • In a switch with other peripherals, the others connect first.
  • When a Mac sleeps, it keeps such a keyboard paired unless your other Mac can take it right then, so closing a lid doesn't leave you typing the code on wake.
  • If no window ever appears and the keyboard won't connect, set its type to Keyboard in the Peripherals tab.
  • None of this applies to Magic keyboards, trackpads or mice, or to headphones: they pair without a code.
  • This older pairing is weak. Someone nearby with specialised equipment who records a pairing can read what you type until the next one, and every switch is a new pairing. For sensitive work, use a newer keyboard.

Troubleshooting

  • A peripheral won't connect: see If a peripheral won't connect.
  • An older keyboard asks for a code each time it switches: see Older keyboards that need a code.
  • A Mac is greyed out: it's asleep, off the network or out of range, or Magic Switch isn't running on it. Ping on the Macs tab tests the connection.
  • A switch failed and nothing said so: notifications are probably off. Settings → Other warns when they are; turn them on under System Settings → Notifications → Magic Switch.
  • Otherwise, check that both Macs show Paired on the Pairing tab, that Bluetooth is on, and that Bluetooth and Local Network are allowed under System Settings → Privacy & Security.

Updates

The Mac App Store keeps its copy up to date. Other copies update themselves with Sparkle: about once a day Magic Switch checks this repo's latest release, with no account or telemetry, downloads any newer version, and installs it when Magic Switch quits. To install it sooner, click Update Available in the menu, or the new version number in Settings → Other → Updates; the circular arrow next to the version checks right away. Turn off Download and install updates automatically to see the release notes first, or Check for updates automatically to stop checking. After an update, a notification shows what's new.

An update installs only if its feed and disk image are signed with this project's update key; should that key ever change, a disk image signed with this project's Apple Developer ID is accepted instead.

Developer notes

Requirements: Xcode 26.5 or later; CI and release builds use 26.5 (Swift 5 language mode).

Build without code signing, as CI does (the project signs with the maintainer's team, so a plain build fails for anyone else):

xcodebuild -project "Magic Switch.xcodeproj" -scheme "Magic Switch" -configuration Debug build CODE_SIGNING_ALLOWED=NO

Format on commit (optional):

sh ./setup-hooks.sh

This sets core.hooksPath to the in-repo .hooks/ directory, so be aware you're trusting whatever lives there in your current checkout.

Architecture

Two Macs discover each other over Bonjour, then exchange short commands over a sealed TCP channel keyed by the shared pairing code. Where Bonjour can't carry advertisements, the channel doubles as discovery: every reachability probe is an INTRODUCE exchange that refreshes both sides' endpoints over the authenticated connection, and a Mac can be bootstrapped by IP address from the Macs tab. Where the network can't carry the channel at all, it can run over Bluetooth LE instead (opt-in): each Mac publishes a GATT service whose UUID is derived from the pairing key, sessions are multiplexed over the link between them, and the sealed channel runs on top unchanged.

                  Bonjour discovery (_magicswitch._tcp. in local.)
                 ┌──────────────────────────────────────────────────┐
                 │                                                  │
                 ▼                                                  ▼
   ┌────────────────────────────┐                    ┌────────────────────────────┐
   │  Mac A — Magic Switch      │                    │  Mac B — Magic Switch      │
   │                            │                    │                            │
   │   AppDelegate              │                    │   AppDelegate              │
   │   (status item, menu)      │                    │   (status item, menu)      │
   │       │         ▲          │                    │       │         ▲          │
   │       ▼         │          │     sealed TCP     │       ▼         │          │
   │   Outgoing  Incoming       │◀── ChaCha20-Poly ─▶│   Outgoing  Incoming       │
   │   Conn.     Conn.          │    (per session)   │   Conn.     Conn.          │
   │       │         │          │                    │       │         │          │
   │       ▼         ▼          │                    │       ▼         ▼          │
   │   NetworkDeviceStore       │                    │   NetworkDeviceStore       │
   │   BluetoothPeripheralStore │                    │   BluetoothPeripheralStore │
   │   PairingStore             │                    │   PairingStore             │
   │       │                    │                    │       │                    │
   │       ▼ IOBluetooth        │                    │       ▼ IOBluetooth        │
   │   Magic Keyboard           │ one host at a time │   Magic Keyboard           │
   │   Magic Trackpad           │ (peripherals owned │   Magic Trackpad           │
   │   Magic Mouse              │  by whichever Mac  │   Magic Mouse              │
   │                            │  took them last)   │                            │
   └────────────────────────────┘                    └────────────────────────────┘

Security model

The LAN channel uses a shared symmetric key derived from the twelve-character pairing code via PBKDF2-HMAC-SHA256 (600k iterations) and stored in the Keychain. Per connection, both sides exchange a 32-byte nonce and derive direction-specific session keys via HKDF; messages are framed as length-prefixed ChaCha20-Poly1305 sealed boxes with monotonic counter nonces. Failed authentications are rate-limited per source IP (5 failures / 60s → 15-minute block), and the client side backs off after 5 failed outgoing attempts in the same window.

Each Mac pins the other's key fingerprint the first time it sees it (trust on first use). If a later advertisement carries a different fingerprint, switching to that peer is paused and the Macs tab asks you to explicitly Trust the new identity — so a key change is surfaced rather than silently accepted. The fingerprint is a hash of the shared pairing key, not a per-machine identity, so a peer that completes the authenticated handshake has proved strictly more than the advertisement claims: if it proves it holds this Mac's current key while the pending fingerprint is exactly that key's, the warning resolves itself (the state a mutual re-pair leaves behind). A peer that cannot complete the handshake is rejected outright, whatever it advertises.

Known limits:

  • On some systems an ad-hoc-signed build (releases up to v2.25.7, and local builds made with CODE_SIGNING_ALLOWED=NO; later releases are Developer ID signed and notarized) can't register with Notification Center at all, so failure notifications never fire no matter what the permission says; the Peripherals, Macs and Pairing tabs surface their errors inline as a fallback.
  • Sixty bits of entropy in the pairing code is fine against an online attacker (rate limit makes brute force infeasible), but guesses can be tested offline without capturing any traffic: anyone on the local network can connect and receive a Mac's handshake MAC before proving anything (the 32-bit key fingerprint in the Bonjour TXT record also narrows guesses), and with Connect over Bluetooth when the network can't turned on, anyone in radio range sees a 128-bit service UUID derived from the key. The PBKDF2 salt is a fixed constant, so one exhaustive search covers every install. It is still impractical — about 2^59 guesses on average, each costing 600k PBKDF2 iterations — but a PAKE would close the gap and is the obvious next step.

Support

Magic Switch is made by me, Joshua Rogers. I write about it and my other projects on my blog, joshua.hu.

If Magic Switch is useful to you, you can support its development by sponsoring me on GitHub.

License

GNU GPL v3.0. See LICENSE.