Files
mac_without_borders/README.md
T
lucioandClaude Fable 5.1 671b3dfa61 bootstrap: SwiftPM skeleton, gates, bundler, and the lane procedure
Four targets (MWBCore, MWBNet, MWBMac, mwb) with a layering test that
keeps MWBCore free of AppKit/CoreGraphics/Network; tools/gates.sh as the
definition of done; tools/bundle.sh producing a signed dist/mwb.app;
tools/lane.sh for lane worktrees; smoke binary with --version and
--check-permissions. docs/loop.md records the Dev -> QA -> lead loop with
the literal dispatch prompts, the wave schedule and escalations.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
2026-09-15 23:46:24 -07:00

172 lines
12 KiB
Markdown

# mwb-mac — Mouse Without Borders for macOS
A macOS port of PowerToys [Mouse Without Borders](https://learn.microsoft.com/en-us/windows/powertoys/mouse-without-borders):
share one keyboard, mouse and clipboard across up to four machines on a
LAN. The point of the port is **wire compatibility**: a Mac running
mwb-mac joins a matrix with unmodified Windows PowerToys machines, using
the same security key, ports and packets.
Start with [`CLAUDE.md`](CLAUDE.md) (rules), [`docs/loop.md`](docs/loop.md)
(how a lane runs), [`docs/protocol.md`](docs/protocol.md)
(the wire format, with citations into the Windows source),
[`docs/topo.md`](docs/topo.md) (dependency map used to plan parallel work)
and [`TODO.md`](TODO.md) (the milestone backlog and lane briefs).
Reference implementation: `/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/`
at commit `3104d5c` (v0.101.2572.0), C#/.NET, ~30 k lines including
WinForms UI. Read-only.
## Status
2026-09-15: bootstrap merged — the SwiftPM skeleton builds, the gates
are green, `mwb --version` / `--check-permissions` run. Wave 1
(`packet-codec` ‖ `cipher-stream`) is next; procedure in
[`docs/loop.md`](docs/loop.md).
## Decisions
| # | Decision | Why |
|---|---|---|
| D1 | **Swift 6 + SwiftPM, no Xcode project.** The `.app` bundle is assembled by `tools/bundle.sh`. | Every platform surface the port needs (event taps, event posting, pasteboard, displays, Network.framework, menu bar) is an Apple framework; a second language would add an FFI boundary for nothing. Rust was considered for the protocol core and rejected as a second build system with no consumer that needs it. |
| D2 | **Three targets, layered by import rules.** `MWBCore` (Foundation + CommonCrypto only; sans-I/O protocol state machines), `MWBNet` (Network.framework), `MWBMac` (AppKit/CoreGraphics), executable `mwb`. | Protocol, crypto, matrix and coordinate logic must be testable with no display, no network and no permissions. SwiftPM target boundaries make the layering a compile error rather than a convention. |
| D3 | **Settings file mirrors the PowerToys schema** (`{"name":"MouseWithoutBorders","version":"1.1","properties":{...}}`, same property names and defaults) at `~/Library/Application Support/mwb-mac/settings.json`, mode 0600. Key stored in plaintext like Windows. | Boring and copy-pasteable between machines. Keychain storage for the key is a backlog item, not a v1 blocker; the threat model equals the Windows one. |
| D4 | **Key mapping: Win↔Command, Alt↔Option, Ctrl↔Control**, with a static Windows-VK ↔ macOS-keycode table in `MWBCore/KeyMap.swift`. | Windows sends virtual-key codes only (protocol §5.1). A layout-independent table is the only thing both sides can agree on; a "swap Cmd/Ctrl when controlling Windows" option comes later. |
| D5 | **Permissions are the user's.** The app needs Accessibility (to post and swallow events) and Input Monitoring (to listen). It detects and explains; it never scripts System Settings. The binary must carry a **stable code-signing identity** (self-signed certificate at minimum) or TCC forgets the grant on every rebuild. | macOS TCC keys grants by code signature. Ad-hoc signatures change per build. |
| D6 | **Out of scope for v1**: Windows service / logon-screen control, Explorer drag-and-drop, screen capture to Paint, GPO, telemetry, key propagation via `Heartbeat_ex`, the animated fake cursor (`DrawMouse`). | No macOS equivalent, or Windows-shell specific, or not needed to join a matrix. Listed in TODO §9 with reasons. |
| D7 | **Hostname** = `gethostname()` with any `.local`/domain suffix stripped, ASCII only, ≤ 32 chars; refuse to start otherwise with a clear message. | Protocol §1.1: 32-byte ASCII, space padded. The Windows side resolves the Mac by this exact name (protocol §7), so it must also be resolvable — the `Name2IP` setting on the Windows side is the documented fallback. |
## Architecture
```
Sources/
MWBCore/ pure logic, no I/O — everything in docs/protocol.md
Packet.swift DATA layout, PackageType, big/small rule (§1.1-1.2)
Framing.swift magic + checksum encode/validate (§1.3)
MagicHash.swift Get24BitHash (§2.1)
CipherStream.swift PBKDF2 + AES-256-CBC zero-padding stream codec (§2.2-2.3)
Session.swift handshake / dedup / heartbeat state machine,
sans-I/O: bytes in, (packets, actions) out (§1.4, §3.2-3.3)
Matrix.swift 4-slot matrix, pool, LiveMachineMatrix (§4.1-4.2)
Edge.swift edge detection + coordinate normalization (§4.3-4.4)
KeyMap.swift VK ↔ macOS keycode, LLKHF/WM_* ↔ event kinds (§5)
ClipboardCodec.swift text tag/SEP format, deflate, 48-byte chunking (§6.1-6.2)
Settings.swift schema, defaults, load/save (§8)
MWBNet/ Network.framework only
ControlChannel.swift listener on port+1, one client per matrix name
BulkChannel.swift port 15100 clipboard/file transfers
Resolver.swift name → address, Name2IP
MWBMac/ AppKit / CoreGraphics only
EventTap.swift CGEventTap capture, swallow, re-enable on timeout
Injector.swift CGEvent posting, tagged so the tap ignores them
Screens.swift display list, primary/desktop bounds
Cursor.swift park/hide/warp
Pasteboard.swift NSPasteboard read/write, changeCount polling
StatusItem.swift menu-bar UI, status colours
Permissions.swift preflight/request Accessibility + Input Monitoring
mwb/ executable: wires the three together, CLI flags
Tests/
MWBCoreTests/ golden-byte vectors, property tests, state-machine tests
MWBNetTests/ loopback two-endpoint tests (no real devices)
Fixtures/ interop vectors captured from Windows (interop-vectors lane)
tools/
guard.sh runaway guard — every test run goes through it
bundle.sh SPM binary → mwb.app with Info.plist + codesign
gates.sh fmt + build-with-warnings-as-errors + test, the "done" check
```
### Windows concept → macOS mapping
| Windows (source) | macOS |
|---|---|
| `SetWindowsHookEx(WH_KEYBOARD_LL / WH_MOUSE_LL)` | `CGEvent.tapCreate(.cgSessionEventTap, .headInsertEventTap, .defaultTap, …)`; return `nil` from the callback to swallow. Re-enable on `.tapDisabledByTimeout` / `ByUserInput`. |
| `RealData` re-entrancy flag (skip own injected input) | Tag injected events via `CGEventField.eventSourceUserData`; the tap passes tagged events through untouched. |
| `SendInput` / `InjectMouseInput` | `CGEvent(keyboardEventSource:virtualKey:keyDown:)`, `CGEvent(mouseEventSource:mouseType:mouseCursorPosition:mouseButton:)`, `.post(tap: .cghidEventTap)`. |
| `SetCursorPos`, hide cursor | `CGWarpMouseCursorPosition`, `CGAssociateMouseAndMouseCursorPosition(false)` while controlling a remote, deltas from `mouseEventDeltaX/Y`. |
| `GetScreenConfig` (primary + desktop bounds) | `CGGetActiveDisplayList` + `CGDisplayBounds` (top-left origin, points). `CGMainDisplayID()` is the (0,0) display. |
| `Clipboard` + `FormHelper` (low-integrity helper process) | `NSPasteboard.general`, polled by `changeCount` every 500 ms (macOS has no change notification). |
| `Dns.GetHostEntry` | `getaddrinfo` (handles `.local` via mDNS) wrapped in `Resolver`. |
| `Socket` dual-mode IPv6 | `NWListener`/`NWConnection` over TCP, all interfaces, both families. |
| `DeflateStream` | `NSData.compressed(using: .zlib)` — Apple's `.zlib` is raw DEFLATE, same as .NET `DeflateStream`. **Verify in `clipboard-inband`.** |
| `Rfc2898DeriveBytes.Pbkdf2(SHA512)`, `AesCryptoServiceProvider` CBC/Zeros | `CCKeyDerivationPBKDF(kCCPBKDF2, kCCPRFHmacAlgSHA512)`, `CCCryptorCreate(kCCAlgorithmAES, options: 0)` streaming `CCCryptorUpdate` — CryptoKit has no CBC. |
| `SHA512` | CryptoKit `SHA512`. |
| `LockWorkStation` | `CGSession -suspend` (Fast User Switching lock) or `pmset displaysleepnow`; decide in `menubar-app`. |
| Windows service on secure desktops | none — out of scope (D6). |
| Named mutex single instance | `flock` on a pid file in Application Support. |
| Settings `FileSystemWatcher` | `DispatchSource.makeFileSystemObjectSource` on the settings file. |
| 100 ms UI timer (heartbeats, reconnect countdown) | `DispatchSourceTimer` on a dedicated queue. |
## Settings
Same names, types and defaults as PowerToys
(`src/settings-ui/Settings.UI.Library/MouseWithoutBordersProperties.cs:165-206`):
| property | default | | property | default |
|---|---|---|---|---|
| `SecurityKey` | `""` → random 16 chars | | `EasyMouse` | `1` |
| `WrapMouse` | true | | `MachineMatrixString` | `[]` |
| `ShareClipboard` | true | | `MachinePool` | `":,:,:,:"` |
| `TransferFile` | true | | `MatrixOneRow` | true |
| `HideMouseAtScreenEdge` | true | | `MachineID` | `0` → random |
| `DrawMouseCursor` | true (ignored, D6) | | `LastX`/`LastY`/`PackageID` | `0` |
| `ValidateRemoteMachineIP` | false | | `TCPPort` | `15100` |
| `SameSubnetOnly` | false | | `Name2IP` | `""` |
| `BlockScreenSaverOnOtherMachines` | true | | `DeviceID` | `""` → UUID |
| `MoveMouseRelatively` | false | | `HotKeySwitchMachine` | `0x70` (F1) |
| `BlockMouseAtScreenCorners` | false | | `ToggleEasyMouseShortcut` | Win+Ctrl+Alt+E |
| `ShowClipboardAndNetworkStatusMessages` | false | | `LockMachineShortcut` | Win+Ctrl+Alt+L |
| `DisableEasyMouseWhenForegroundWindowIsFullscreen` | true | | `ReconnectShortcut` | Win+Ctrl+Alt+R |
| `EasyMouseFullscreenSwitchBlockExcludedApps` | `[]` | | `Switch2AllPCShortcut` | disabled |
| `UseService`, `ShowOriginalUI`, `FirstRun`, `FirstCtrlShiftS`, `DrawMouseEx` | accepted, ignored | | | |
On the Mac, Win means Command and Alt means Option (D4), so the lock
hotkey is ⌘⌃⌥L and machine switching is ⌃⌥F1..F4 (Fn may be needed on
laptops).
## Build
Requirements: macOS 14+, Xcode 27 (Swift 6.4); `xcode-select -p` must point at Xcode.app.
```bash
tools/gates.sh # xcrun swift-format lint, build -warnings-as-errors, guarded swift test
```
```bash
MWB_SIGN_IDENTITY="mwb-mac dev" tools/bundle.sh # release build → dist/mwb.app, signed
```
```bash
tools/lane.sh new packet-codec # worktree ../mwb-lanes/packet-codec on branch lane/packet-codec
```
`swift-format` ships inside the Xcode toolchain, not on `PATH`; the
scripts call it via `xcrun`. The lint config is `.swift-format`
(110 columns, force-unwrap and force-try are lint errors).
**Toolchain note (2026-09-15):** with only Command Line Tools installed
(Swift 6.4, macOS 27.0) `swift build` failed while linking the package
manifest — the CLT's `libPackageDescription.dylib` and the compiler
disagreed on the `Package.init` signature, and the CLT ships no
`XCTest.framework`. Installing Xcode 27.0 and selecting it with
`xcode-select` fixed both: a smoke package linking AppKit and CryptoKit
builds, and an XCTest case runs. Details in the bootstrap README.
## Permissions
The app needs, and asks for on first run:
- **Accessibility** — required for a `.defaultTap` event tap that can
swallow events, and for posting events.
- **Input Monitoring** — required to listen to keyboard events.
Both are granted in System Settings by the user. The app checks with
`CGPreflightListenEventAccess()` / `CGPreflightPostEventAccess()` and
shows what is missing in the menu bar. Grants are tied to the code
signature (D5).
## Running two instances for development
The loopback harness (`Tests/MWBNetTests`) runs two `Session`s over
in-process `NWConnection`s to `localhost` on ports the test picks; no
permissions, no devices. Anything that posts real input is behind
`MWB_ALLOW_INPUT_TESTS=1` (CLAUDE.md invariant 5).