Files
lucioandClaude Opus 5 81e35b6691 polish P1: protocol §2.5 and §10.9, README D3 and Status, TODO §10
§2.5 is the legacy stream: the fixed salt, IV and iteration count with
citations into the pre-a9e1f0f20e Encryption.cs, the missing cleartext
header, why the sacrificial block exists, the MacCipherScheme setting and
the mismatch diagnostic. §2.3 now says plainly that it describes v0.101
and later only.

§10.9 records the one fact in this document confirmed against a live
Windows machine rather than the source: the lead's independent Python
probe completed the whole handshake against the user's PC under the
legacy scheme, which proves framing, the magic hash, the packet layout
and the handshake as transcribed, and localises the earlier failure to
the stream cipher alone.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 21:11:09 -07:00

177 lines
13 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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. Lanes run one at
a time in the order of [`docs/loop.md`](docs/loop.md) §6; `packet-codec`
is next. There are no test suites by design: the user tests the app.
2026-09-16: all lanes through `extras` merged; checkpoints CP1–CP3 with
the user. The `polish` lane is now working the findings from that
testing ([`docs/features/polish/README.md`](docs/features/polish/README.md)).
P1 of it matters to anyone pairing with a PC: **the encryption changed
in PowerToys 0.101**, and a machine on stable PowerToys still speaks the
older scheme, so `MacCipherScheme` defaults to `legacy` and the Security
pane's "Encryption compatibility" picker is the switch to change if the
menu says a machine has the wrong one (protocol
[§2.5](docs/protocol.md)). The legacy handshake is the one part of this
protocol confirmed against a real Windows peer rather than against the
source (§10.9).
## 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 stay readable and reviewable without any platform code around them. SwiftPM target boundaries make the layering a build failure 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. Properties Windows writes and this port does not implement are round-tripped untouched. **One property is ours alone**: `MacCipherScheme` (`"legacy"` \| `"modern"`), because the wire has no way to ask a peer which encryption scheme it speaks (protocol §2.5) and Windows has no such switch — its build decides. A PowerToys that rewrites the file drops the key and the default, `legacy`, applies again. | 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. A second settings file for one Mac-only property would be worse than one unknown key in a file that already tolerates unknown keys. |
| 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,
legacy and modern schemes (§2.2-2.5)
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
tools/
guard.sh runaway guard for long-running commands
bundle.sh SPM binary → mwb.app with Info.plist + codesign
gates.sh lint + MWBCore layering grep + build-with-warnings-as-errors, 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, MWBCore layering check, build -warnings-as-errors
```
```bash
MWB_SIGN_IDENTITY="mwb-mac dev" tools/bundle.sh # release build → dist/mwb.app, signed
```
`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).
## Testing
The user tests the app. Agents build `dist/mwb.app` and hand it over
with a checklist of what changed (`docs/loop.md` §7); findings come
back as `TODO.md` lines. No agent posts input events, writes the real
pasteboard or moves the cursor (CLAUDE.md invariant 5).