Plan the macOS port of Mouse Without Borders

Planning documents only: CLAUDE.md rules, README with decisions and
architecture, docs/protocol.md transcribed from the Windows source with
citations, docs/topo.md, TODO.md milestones and the first-wave feature
briefs (bootstrap, packet-codec, cipher-stream), plus tools/guard.sh.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-15 23:33:27 -07:00
commit 69c0f7ab53
11 files changed
+1536

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
.build/
dist/
*.xcodeproj
*.xcworkspace
.DS_Store
/Tests/Fixtures/*.pcap
+197
View File
@@ -0,0 +1,197 @@
# CLAUDE.md — rules for all agents working on mwb-mac
mwb-mac is a macOS port of PowerToys "Mouse Without Borders" (MWB): one
keyboard and mouse shared across up to four machines on a LAN, with
clipboard sharing, that **interoperates on the wire with the unmodified
Windows MWB**. Read `README.md` for architecture, `docs/topo.md` for the
dependency map and `TODO.md` for the backlog before doing anything. The
reference implementation is checked out at
`/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/`
(commit `3104d5c`, tag v0.101.2572.0) — read it, cite it, never edit it.
## Hard invariants (never break these)
1. **Wire compatibility is a contract, not a goal.** Packet layout, the
package-type numbering, the key derivation, the cipher mode and the
handshake are dictated by the Windows source (`docs/protocol.md`
is our transcription, with `file:line` citations). Any difference is
a bug on our side unless the Windows source changed. Every codec
change ships with golden-byte tests whose expected bytes were
produced by the Windows algorithm, not by our own encoder.
2. **Never act on an unauthenticated packet.** No input is injected, no
clipboard is written, no file is created from any packet that did
not decrypt and validate under the configured security key. There
is no "no key" mode. The key and decrypted keystrokes are never
logged, at any log level.
3. **The local machine is always recoverable.** Whatever happens on the
network, the user can regain their own keyboard and mouse: the
escape hotkey works while control is remote, control returns local
on any disconnect or on key-tap loss, and a
`kCGEventTapDisabledByTimeout` / `ByUserInput` tap is re-enabled
immediately. A build that can leave a Mac with a dead keyboard does
not ship.
4. **The event-tap callback never blocks.** No network, disk, locking on
contended locks, or allocation-heavy work inside the
`CGEventTap` callback; it classifies, enqueues and returns. Budget is
measured (`docs/perf/README.md`), not asserted.
5. **Synthetic input is opt-in.** Any test or tool that posts a
`CGEvent`, writes the real pasteboard or moves the real cursor runs
only with `MWB_ALLOW_INPUT_TESTS=1` set explicitly and only inside
the loopback harness. Never set that variable in CI config, a
script default or a `Makefile` target. This machine is the user's
daily driver: an agent test that hijacks the mouse is a P0 finding.
## Simplicity first
- Prefer the boring, obvious implementation. If you're building an
abstraction for a second user that doesn't exist yet, stop.
- Apple frameworks first (Foundation, Network, AppKit, CoreGraphics,
CryptoKit/CommonCrypto). Adding a Swift package dependency requires
a written justification in the feature README.
- Small functions, descriptive names, shallow nesting. Code should be
readable top-to-bottom without jumping around.
- Match the style of the surrounding code (comment density, naming,
module layout).
## File and function size
Files and functions are sized for a human reader, not a compiler.
- **Target 300–600 production lines per file.** At 800, consider
splitting. Above 1,200, an explicit reason not to split goes in the
feature README. Test lines do not count.
- **Functions: 10–50 lines.** Investigate anything over 80; anything
over 150 needs a reason in a comment (a `switch` over `PackageType`
is the usual one).
- **The real test is one sentence.** A human should be able to say what
a file is responsible for in one sentence and predict which parts a
change touches. Several "and" clauses mean the file wants to be
several modules. The Windows source fails this test in
`Common.cs`, `SocketStuff.cs` and `MachineStuff.cs`; do not port
their shape, port their behaviour.
- A split is a **pure move**: public names stay the same, behaviour
stays byte-identical on the wire, the test count does not drop.
## Swift standards
- Swift 6 language mode, strict concurrency on. `swift-format lint
--strict` clean, `swift build -Xswiftc -warnings-as-errors` clean,
`swift test` green — all three before declaring any work finished.
- No force-unwrap (`!`), `try!`, `fatalError` or `precondition` in
production code paths; return `Result`/throw. Tests and `main.swift`
argument handling may use them.
- Public items get a one-line doc comment. Doc comments say what/why,
not how.
- Layering is enforced by SwiftPM targets, not by discipline: the
`MWBCore` target imports Foundation only (no AppKit, no CoreGraphics,
no Network) so the protocol, crypto, matrix and settings logic is
testable without a display or a network. Platform code lives in
`MWBMac`; the executable `mwb` wires them together.
- C APIs (`CGEventTap`, `CommonCrypto`) are wrapped once, in one file
each, behind a Swift type; nothing else touches the raw API.
## Document-based development
Every feature lives in `docs/features/<feature-name>/README.md`. That
README is the single source of truth for the feature and must contain
these sections:
```markdown
# <feature name>
## Goal — one paragraph, what and why
## Assumptions — everything you assumed that isn't enforced by code
## Handshakes — interfaces/contracts with other modules: what you
consume from them, what you promise to them
## Status / TODO — checklist; keep current as you work
## Work log — dated entries by the dev agent: what was done, key
decisions, deviations from plan
## QA log — dated entries by the QA agent: what was verified,
how, and findings
## Review — reserved for the lead; do not write here
```
Rules:
- **Dev agents**: create/update the feature README *as you work*, not at
the end. Finished TODOs get checked off in the same README. If you
change a handshake another module depends on, say so explicitly in
Handshakes and in the work log. Every fact taken from the Windows
source is cited as `App/<path>.cs:<line>`.
- **QA agents**: you verify, you don't redesign. Run the checks, try to
break the feature, record everything in the QA log. File concrete
findings (file:line, reproduction) — not opinions. Small unambiguous
fixes (typos, missing test assertion) you may fix directly and note it.
- **Review section** is written only by the lead agent after examining
the work. Respond to review comments by fixing and logging in the work
log, not by editing the Review section.
- `docs/protocol.md` is the one place the wire format is written down.
A feature that learns something new about the protocol updates
`docs/protocol.md` in the same change, with the citation.
## Workflow
- Do **not** run `git commit` or `git push` — the lead reviews and
commits all work.
- Do not touch files outside your feature's stated scope. If you need a
change in another module, write it as a request in your README's
Handshakes section and stop.
- New behavior needs tests in the same change. Every codec or crypto
change must keep the golden-byte suite green
(`swift test --filter MWBCoreTests`).
- Update `TODO.md`: check items your feature completes (leave the item
text intact).
- Never grant, request or script macOS permissions (Accessibility,
Input Monitoring, Screen Recording) on the agent's own initiative.
Report what is missing; the user grants it in System Settings.
## Runaway guard (never run a suite or sweep bare)
macOS enforces no memory cap, so the cap is ours:
`tools/guard.sh [-m GB] [-t SECONDS] -- <command>` kills a command's
process tree when its resident set or wall clock exceeds the limits
(defaults 8 GB / 30 min).
- **Every `swift test`, every fuzzer, every soak test and every
two-process loopback run goes through `tools/guard.sh`** — dev, QA
and lead alike, foreground or background.
- A guard kill is a finding: report the command and the limit it hit;
do not raise the limit to make it pass.
## Parallel lanes (the 2-agent loop)
Up to **two dev/QA lanes may run concurrently** when — and only when —
their features do not collide in `docs/topo.md`: no shared edge between
them (no `──▶`, no `◀──▶`, and neither touching the same open handshake
in §2.9), and disjoint file sets. `docs/topo.md` is the authority; if the
collision question is not answerable from it, the features are not
proven independent and run serially. Rules for a parallel wave:
- **The lead plans the lanes** before anything is dispatched: one brief
per lane with an explicit file-ownership list. That list is the merge
contract — a lane touches nothing outside it. A needed change to a
file the other lane owns (or to any unlisted file) is a Handshake
request in the lane's README plus a flag in its report, never a
silent edit; the lead rules on it at merge.
- **Each lane works in its own git worktree** branched from the same
trunk commit. Never two agents in one tree. Trunk stays untouched
while lanes are in flight; the lead merges each lane back only after
that lane's QA verdict and lead review, and re-runs the full gates on
the merged tree before pushing.
- **Roles per lane are unchanged**: one dev (Opus), then one QA
(Sonnet) in the same worktree, then the lead's review — so at most
2 devs + 2 QA agents exist at once, and a lane's QA starts only when
its own dev is done. A QA rework loops inside its lane without
blocking the other lane.
- **Tracking lives in `TODO.md`**: the lead writes the wave's section
(one subsection per lane, each item naming its files) on trunk before
branching; each lane ticks only its own lines. Shared-by-nature files
(`TODO.md`, `docs/protocol.md`, `docs/perf/README.md`) may be appended
to by both lanes in their own sections — the lead resolves the
trivially-parallel merge; anything worse than trivially-parallel means
the lanes were not actually independent, which is a planning failure
to record.
- After merging, the lead updates `docs/topo.md` for any edge a lane
added or amended, so the next wave plans against reality.
- **Only one lane may hold the real input devices.** A lane whose QA
needs the loopback harness with `MWB_ALLOW_INPUT_TESTS=1` runs that
step serially, with the user warned in the report.
+160
View File
@@ -0,0 +1,160 @@
# 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/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
Planning, 2026-09-15. No code yet. Toolchain verified (Xcode 27.0);
the `bootstrap` lane is next.
## 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+, Swift 6.x, a working SwiftPM.
```bash
tools/gates.sh # swift-format lint, build -warnings-as-errors, guarded swift test
```
```bash
tools/bundle.sh # .build/release/mwb → dist/mwb.app, signed with $MWB_SIGN_IDENTITY
```
**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).
+253
View File
@@ -0,0 +1,253 @@
# TODO — mwb-mac backlog, by milestone
Legend: **(core)** pure logic in `MWBCore`, **(net)** `MWBNet`, **(mac)**
`MWBMac`, **(app)** executable/tooling. Section numbers are referenced
from `docs/topo.md` and feature READMEs as "TODO §n". Each lane's brief
names its files; a lane ticks only its own lines. Milestones are ordered;
lanes inside a milestone may run in parallel when `docs/topo.md` §3
says they are independent.
---
## 0. Toolchain and skeleton (M0, serial — `docs/features/bootstrap`)
- [x] **Unblock SwiftPM.** `swift build` failed with Command Line Tools
only (README §Build). Fixed 2026-09-15 by installing Xcode 27.0;
smoke build + XCTest verified. Recorded in the bootstrap README.
- [ ] `Package.swift` with targets `MWBCore`, `MWBNet`, `MWBMac`, `mwb`,
tests `MWBCoreTests`, `MWBNetTests`; Swift 6 language mode; macOS 14
minimum. Layering is enforced by a test in `MWBCoreTests` that
greps `Sources/MWBCore` for `import AppKit|CoreGraphics|Network`
and fails on any hit.
- [ ] `tools/gates.sh`: `swift-format lint --strict --recursive Sources Tests`,
`swift build -Xswiftc -warnings-as-errors`, `tools/guard.sh -- swift test`.
- [ ] `tools/bundle.sh`: release build → `dist/mwb.app` (Info.plist with
`LSUIElement = true`, bundle id `com.luciochen.mwb-mac`),
`codesign --force --sign "$MWB_SIGN_IDENTITY"`; document how to
create a self-signed identity once (D5).
- [ ] `.swift-format` config; `.gitignore` (`.build/`, `dist/`).
- [ ] Smoke executable: `mwb --version`, `mwb --check-permissions`
(prints preflight results, exit 0).
## 1. Wire core (M1 — two lanes: `packet-codec` ‖ `cipher-stream`)
### 1.1 packet-codec (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift`, `Tests/MWBCoreTests/PacketTests.swift`, `FramingTests.swift`
- [ ] `PackageType` enum, raw `UInt8`, every value from protocol §1.2;
`isBig` rule (§1.1) as a table-driven test over all 256 byte values.
- [ ] `Packet` value type with the union views (`mouse`, `keyboard`,
`nonce`, `postAction`, `machineName`) reading/writing a fixed
32/64-byte little-endian buffer at the documented offsets.
- [ ] `MachineName` ASCII, space-padded, trimmed; non-ASCII rejected.
- [ ] `Framing.seal(magic:bytes:)` and `Framing.open(magic:bytes:)`
exactly as §1.3, including the "only bytes 2..31" checksum and the
zeroing of bytes 1–3 on the receive side.
- [ ] Golden vectors: hand-assembled bytes for `Handshake`, `Mouse`,
`Keyboard`, `Matrix` (slot 4, both flags), `ClipboardText` chunk.
Property test: `open(seal(p)) == p` for random packets; flipping any
of bytes 2..31 is detected; flipping bytes 32..63 is **not** (pinned
as documented behaviour).
### 1.2 cipher-stream (core) — `Sources/MWBCore/MagicHash.swift`, `CipherStream.swift`, `Tests/MWBCoreTests/MagicHashTests.swift`, `CipherStreamTests.swift`
- [ ] `magicNumber(for key: String) -> UInt32` per §2.1 (50 001 SHA-512
rounds, the `<< 23` overlap, UTF-16 code unit truncation to a byte).
Pin one vector computed independently (Python transcription in
`Tests/Fixtures/magic_reference.py`, run once, result committed).
- [ ] `deriveKey(password:salt:)` = PBKDF2-HMAC-SHA512, 100 000 rounds,
32 bytes, via CommonCrypto. Vector pinned against Python `hashlib.pbkdf2_hmac`.
- [ ] `CipherWriter` / `CipherReader`: emit/consume the 16+16 header, the
sacrificial block, then a raw AES-256-CBC no-padding stream (§2.3).
Streaming API: `write(Data) -> Data` / `read(Data) -> Data`
accumulating partial blocks; a `CipherReader` fed one byte at a time
must produce the same plaintext as one fed all at once.
- [ ] Round-trip test writer→reader; a wrong key yields garbage, not a
throw, and the caller's framing check rejects it (that is the
Windows behaviour: `InvalidKey` after >10 bad packets).
- [ ] Never log key material: a test asserts `String(describing:)` and
`debugDescription` of every crypto type omit key/salt/IV bytes.
## 2. Session logic (M2 — two lanes: `session` ‖ `matrix-edge`)
### 2.1 session (core) — `Sources/MWBCore/Session.swift`, `Tests/MWBCoreTests/SessionTests.swift`
- [ ] Sans-I/O `Session` state machine: `feed(bytes)` → `[Event]`,
`outgoing()` → bytes; states NA…Connected per §3.2 `SocketStatus`.
- [ ] Handshake exactly as §3.2 (10× `Handshake`, nonce complement,
`HandshakeAck`, adopt peer name/id, >10 untrusted packets ⇒
InvalidKey, self-connection detection).
- [ ] Dedup ring of 50 ids with the four exemptions (§1.4).
- [ ] Heartbeat scheduling (60 s / 300 s, `Awake` vs `Heartbeat`), `Hi`
probe counting, `ByeBye`, 25 min liveness (§3.3) — all driven by an
injected clock.
- [ ] Two `Session`s wired back-to-back in a test reach `Connected` both
ways and exchange a `Mouse` packet.
### 2.2 matrix-edge (core) — `Sources/MWBCore/Matrix.swift`, `Edge.swift`, `Tests/MWBCoreTests/MatrixTests.swift`, `EdgeTests.swift`
- [ ] `Matrix` (4 slots, one/two rows, wrap) and `MachinePool`
(serialize/parse `Name:Id,…`, 25 min alive) per §4.1.
- [ ] `Matrix` packet encode/decode (slot in `Src`, flags in `Type`) §4.2.
- [ ] `LiveMachineMatrix`, moveLeft/Right/Up/Down, `desMachineID` / ALL.
- [ ] Edge detection §4.3 with the primary-vs-desktop rectangle rule,
100 ms debounce, corner blocking; coordinate normalization §4.4 with
all four rectangle cases, `MOVE_MOUSE_RELATIVE` / `XY_BY_PIXEL`
biases, `NextMachine` encoding (id in `WheelDelta`).
- [ ] Table tests on 1-, 2- and 3-monitor layouts including a negative-
origin monitor left of primary.
## 3. Platform capture (M3 — two lanes: `control-channel` ‖ `event-tap`)
### 3.1 control-channel (net) — `Sources/MWBNet/ControlChannel.swift`, `Resolver.swift`, `Tests/MWBNetTests/LoopbackTests.swift`
- [ ] `NWListener` on port+1, all interfaces, IPv4+IPv6; one
`NWConnection` client per non-local matrix name; 1 s retry for 30 s;
dedup to one client socket per peer (§3.1).
- [ ] `Resolver`: `getaddrinfo` + `Name2IP` lines (§7); optional
same-/16 check and reverse validation as settings, off by default.
- [ ] Each connection owns one `Session` and a `CipherWriter`/`Reader`
pair per direction; send serialised through one queue with 500 ms
send timeout; receive loop reads 32 then 32.
- [ ] Reconnect on path change (`NWPathMonitor`), wake
(`NSWorkspace.didWakeNotification` is `mac`; expose a
`reopenAll()` the app calls), connection reset, hotkey.
- [ ] Loopback test: two channels on 127.0.0.1 with random ports reach
`Connected` and pass 1 000 `Mouse` packets in order with no dedup
drops; wrong key on one side ends in `InvalidKey`.
### 3.2 event-tap (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Sources/MWBCore/KeyMap.swift`, `Tests/MWBCoreTests/KeyMapTests.swift`
- [ ] `Permissions`: preflight/request Accessibility + Input Monitoring;
never loops on request; reports per-permission state.
- [ ] `EventTap`: session tap, head-insert, default (swallowing) tap for
key down/up/flagsChanged, mouse move/drag/buttons/scroll; callback
converts to a `CapturedInput` value and enqueues; returns `nil` to
swallow when the destination is remote; passes tagged injected
events through; re-enables on timeout/user-input disable
(invariant 3 and 4).
- [ ] Modifier tracking (Cmd/Ctrl/Opt/Shift) and hotkey matching per
§4.5 with D4 mapping; the tap reports `.hotkey(...)` events.
- [ ] `KeyMap`: macOS keycode → Windows VK and back, `flagsChanged` →
modifier VK down/up pairs, `LLKHF` flags, `NSEvent.ModifierFlags`
→ nothing (VKs carry modifiers themselves). Table pinned by tests:
letters, digits, F1–F19, arrows, editing keys, numpad, punctuation
on US layout; unknown keys are dropped and counted.
- [ ] Mouse: `WM_*` mapping, wheel line deltas × 120, X-buttons, moves
as absolute 0..65535 against the primary display (§5.2, §4.4).
## 4. Platform injection and screens (M4 — two lanes: `input-inject` ‖ `screens-cursor`)
### 4.1 input-inject (mac) — `Sources/MWBMac/Injector.swift`
- [ ] `Keyboard` packet → `CGEvent` key down/up with VK→keycode; modifier
VKs → `flagsChanged` with maintained flag state; `EXTENDED` ignored;
autorepeat handled by repeated downs like Windows.
- [ ] `Mouse` packet → move (absolute, §4.4 de-normalization onto the
desktop bounds), buttons with click-count tracking (double-click =
two downs within `NSEvent.doubleClickInterval`, since Windows drops
`*DBLCLK`), wheel (`WheelDelta`/120 lines), X-buttons → other
mouse buttons 3/4.
- [ ] Every posted event tagged with the injected marker (README mapping).
- [ ] `ReleaseAllKeys` equivalent on switch/lock.
- [ ] Remote Win+L → lock; remote Ctrl+Alt+Del → nothing (documented).
### 4.2 screens-cursor (mac) — `Sources/MWBMac/Screens.swift`, `Cursor.swift`
- [ ] `Screens`: active displays, primary (`CGMainDisplayID`), desktop
union, corner points for `BlockMouseAtScreenCorners`; refresh on
`NSApplication.didChangeScreenParametersNotification`.
- [ ] `Cursor`: park at primary centre-x / y=4 (`HideMouse` on) or
centre; `CGAssociateMouseAndMouseCursorPosition(false)` while
controlling a remote, deltas read from the tap; restore on return
to the last local position.
- [ ] `HideMouse (50)` packet handling.
## 5. Clipboard and app shell (M5 — two lanes: `clipboard-inband` ‖ `menubar-app`)
### 5.1 clipboard-inband (core + mac) — `Sources/MWBCore/ClipboardCodec.swift`, `Sources/MWBMac/Pasteboard.swift`
- [ ] Text codec: `TXT`/`RTF`/`HTM` + SEP, UTF-16LE, raw DEFLATE
(§6.1). **First task: prove Foundation `.zlib` == .NET
`DeflateStream` on a fixture** (README mapping note); fall back to
`compression_stream` with `COMPRESSION_ZLIB` if not.
- [ ] 48-byte chunking at offset 16, `ClipboardDataEnd`, zero-padding
semantics on decode (§6.2); 1 MB in-band limit.
- [ ] Image: PNG from `NSPasteboard` (`.png`, else TIFF → PNG).
- [ ] `Pasteboard`: `changeCount` poll at 500 ms, 1 s suppression,
write on receive; never write when we were the source.
- [ ] Feature flag from `ShareClipboard`.
### 5.2 menubar-app (app + mac) — `Sources/mwb/*`, `Sources/MWBMac/StatusItem.swift`, `Sources/MWBCore/Settings.swift`
- [ ] `Settings`: schema per README §Settings, load/save/watch, 0600,
random key/`MachineID`/`DeviceID` on first run.
- [ ] `NSStatusItem` with per-machine status dots in the documented
colours, matrix editor (4 names, one/two rows), key entry, port,
toggles; "Reconnect", "Quit".
- [ ] Permissions onboarding panel; LaunchAgent install/uninstall.
- [ ] Single instance via pid-file lock; log to
`~/Library/Logs/mwb-mac/` with rotation, never key material.
- [ ] Lock-machine hotkey → `CGSession -suspend` (decide vs
`pmset displaysleepnow`; record).
## 6. Bulk transfer and interop (M6 — two lanes: `clipboard-bulk` ‖ `interop-vectors`)
### 6.1 clipboard-bulk (net) — `Sources/MWBNet/BulkChannel.swift`
- [ ] Listener on port; `Clipboard (69)` broadcast on big data;
pull on `MachineSwitched`, push on `ClipboardAsk` (§6.3).
- [ ] Bulk handshake: cipher layout, one 64-byte `DATA` each way,
`ResolveID(name) == Src` gate, 1024-byte UTF-16LE header
`"<len>*<name>"`, 1 MB chunks, 32-byte file padding, exact-length
read, atomic temp-file commit to `~/Desktop/MouseWithoutBorders/`.
- [ ] 100 MB file limit, single file only, folders refused with the
Windows message; `TransferFile` flag.
### 6.2 interop-vectors (tests) — `Tests/Fixtures/`, `tools/winvectors/`
- [ ] A small .NET console program (`tools/winvectors/`, runs **on a
Windows machine with the PowerToys tree**) that links the MWB
assembly and dumps: `Get24BitHash` for 5 keys, PBKDF2 key for
fixed salt, one full encrypted control-stream capture for a
scripted handshake with fixed RNG, framed bytes for each packet
type, a deflated clipboard text fixture.
- [ ] Until a Windows machine is available: a `pcap` of a real
Windows↔Windows session (user-provided) plus the typed key lets us
decrypt and replay; document how to capture it.
- [ ] Every `[transcribed]` mark in `docs/protocol.md` flips to
`[verified]` only when a fixture from this lane pins it.
## 7. End to end (M7, serial — needs the real devices)
- [ ] `docs/features/end-to-end`: Mac ↔ Windows over the LAN, both
directions, checklist: switch by edge, by hotkey, wrap, one/two
rows, keyboard incl. modifiers and function keys, wheel, clipboard
text/image/file, reconnect on sleep/wake, wrong key, kill the peer
mid-control (invariant 3).
- [ ] Soak: 8 h with heartbeats and periodic switches under
`tools/guard.sh`; memory flat; tap never stays disabled.
- [ ] `docs/perf/README.md` filled with measured tap-callback and
end-to-end latencies.
## 8. Later (post-v1, ordered by value)
- [ ] Keychain storage for `SecurityKey` (D3).
- [ ] Easy Mouse fullscreen suppression + excluded apps (`NSWorkspace`
frontmost app, `NSWindow` fullscreen detection via Accessibility).
- [ ] `Heartbeat_ex` key propagation (§3.3) so a key typed on one
machine spreads.
- [ ] "Swap ⌘/⌃ when controlling Windows" option.
- [ ] Non-US layouts: send VKs by physical position vs by character —
needs a decision and a test matrix.
- [ ] Sparkle-style updates, notarization, Homebrew cask.
## 9. Out of scope, with reasons (D6)
- Windows service / logon-screen / UAC secure desktop control: macOS
login window cannot be driven by a user-session event tap.
- Explorer drag-and-drop (§6.4): depends on a Windows-shell helper; a
Finder equivalent is a separate design.
- Screen capture to Paint (`CaptureScreenCommand`, `ClipboardCapture`):
niche; packets are ignored and logged.
- GPO, telemetry, `ShowOriginalUI`: Windows-only.
- Animated fake cursor (`DrawMouse`): cosmetic.
+76
View File
@@ -0,0 +1,76 @@
# bootstrap
## Goal
Turn the empty repository into a building, testing SwiftPM package with
the three-target layering from README D2, the `done` gate script and the
`.app` bundler — and, first of all, establish whether `swift build`
works on this machine at all. Nothing in later lanes can start until
`tools/gates.sh` passes on an empty skeleton.
## Assumptions
- **The SwiftPM breakage is the toolchain, not the manifest.** Measured
2026-09-15: Command Line Tools only (`/Library/Developer/CommandLineTools`,
Swift 6.4, macOS 27.0, no Xcode.app). A trivial manifest fails to link
with `swift-tools-version` 5.9 and 6.0 alike; `libPackageDescription.dylib`
exports `Package.init(… swiftLanguageVersions: [SwiftLanguageMode]? …)`
while the compiled manifest references `[SwiftVersion]?`. Purging
`~/Library/Caches/org.swift.swiftpm` did not help. `swiftc` compiles and
links an AppKit + CryptoKit program fine. The CLT ships Swift Testing
but no `XCTest.framework`.
- **Installing Xcode.app fixes both.** It carries its own SwiftPM and
XCTest. If the user prefers not to, the fallback is a `Makefile`
driving `swiftc` per target plus Swift Testing (`import Testing`) run
via `swift-testing`'s console runner — recorded here only if needed.
- **Minimum macOS 14.** `CGPreflightListenEventAccess` and friends exist
since 10.15; 14 is chosen for Swift 6 concurrency and `NWListener`
maturity, not for a specific API.
- **Bundle id** `com.luciochen.mwb-mac`; `LSUIElement = true` (menu-bar
app, no Dock icon). A self-signed "mwb-mac dev" code-signing
certificate is created once by the user via Keychain Access;
`tools/bundle.sh` reads its name from `MWB_SIGN_IDENTITY` and refuses
to sign ad-hoc unless `MWB_ADHOC=1` is set explicitly (D5).
## Handshakes
### Promised
- `Package.swift` target names `MWBCore`, `MWBNet`, `MWBMac`, `mwb`,
`MWBCoreTests`, `MWBNetTests` are frozen; later lanes add files, not
targets, without a handshake here.
- `tools/gates.sh` exit status is the definition of "done" for every
lane: 0 means format-clean, warning-free, tests green under the guard.
- `MWBCoreTests/LayeringTests.swift` greps `Sources/MWBCore` for
`import (AppKit|CoreGraphics|Network|Cocoa)` and fails on any hit
(topo.md §1 standing promise).
### Consumed
- `tools/guard.sh` (already present; copied from lucisv, header adapted).
## Status / TODO
- [x] Report the toolchain state to the user and wait for Xcode.
Xcode 27.0 (27A266a) installed 2026-09-15; `xcode-select -p` is
`/Applications/Xcode.app/Contents/Developer`.
- [ ] `Package.swift`, empty targets with one placeholder type each,
`Tests/MWBCoreTests/LayeringTests.swift`.
- [ ] `tools/gates.sh`, `.swift-format`.
- [ ] `tools/bundle.sh` + `Resources/Info.plist`.
- [ ] `mwb --version`, `mwb --check-permissions`.
- [ ] `tools/gates.sh` green; record Swift/Xcode versions in the work log.
## Work log
- 2026-09-15 (lead, planning): toolchain probed; findings in Assumptions.
No code written.
- 2026-09-15 (lead): after the user installed Xcode 27.0, the same smoke
package (executable importing AppKit + CryptoKit + CommonCrypto, one
XCTest case, `swift-tools-version:6.0`) built in 8 s and the test
passed under `swift test`. The Assumptions above stay as the record of
why Xcode is a requirement; the fallback Makefile is not needed.
## QA log
## Review
+78
View File
@@ -0,0 +1,78 @@
# cipher-stream
## Goal
The two cryptographic primitives the wire needs, in `MWBCore` with
CommonCrypto and CryptoKit only: the magic-number hash of the security
key (`docs/protocol.md` §2.1) and the per-direction AES-256-CBC stream
with its cleartext salt+IV header and sacrificial first block (§2.2–2.3).
Streaming, allocation-light, and never able to leak key material into a
log. Wire compatibility with the Windows `Encryption.cs` is the whole
point; there is no "better" cipher choice to make here.
## Assumptions
- **CryptoKit cannot do CBC**, so AES goes through `CCCryptorCreate`
with `options = 0` (no padding, CBC) and `CCCryptorUpdate` per chunk.
Zero padding on the Windows side never emits bytes because every write
is a multiple of 16; we therefore do *no* padding at all and treat a
non-multiple-of-16 total as a stream error at close.
- **PBKDF2 goes through `CCKeyDerivationPBKDF`** with
`kCCPRFHmacAlgSHA512`, 100 000 rounds, 32 bytes. Password bytes are
UTF-8 of the key string — `Rfc2898DeriveBytes.Pbkdf2(string, …)` uses
UTF-8 (documented .NET behaviour). Pinned by a Python
`hashlib.pbkdf2_hmac('sha512', …)` vector.
- **The magic hash truncates each UTF-16 code unit to a byte**
(`(byte)st[i]`, `Encryption.cs:184`) and hashes a fixed 32-byte
buffer; keys longer than 32 characters contribute only their first 32.
The `<< 23` overlap is reproduced with `UInt32` wrapping arithmetic in
the same order as the C# expression.
- **Salt and IV are fresh per direction and never reused**; Windows
tests pin uniqueness (`EncryptionTests.cs:59-68`) and so do ours.
- **The sacrificial block is part of the cipher type's contract**: the
writer emits it right after the header, the reader discards the first
16 plaintext bytes. Callers never see it (topo.md handshake 2).
- A wrong key is not detectable here — CBC has no authentication. The
reader returns garbage plaintext and the framing layer's magic/checksum
rejects it, matching Windows (`InvalidKey` after >10 bad packets).
## Handshakes
### Promised (topo.md handshake 2, to control-channel and clipboard-bulk)
```swift
public enum MagicHash { public static func magicNumber(for key: String) -> UInt32 }
public struct CipherWriter {
public init(key: String, rng: RandomBytes = .system) throws // derives, builds header + sacrificial block
public mutating func header() -> Data // 32 bytes cleartext + 16 bytes ciphertext, once
public mutating func write(_ plaintext: Data) throws -> Data // ciphertext for the full blocks now available
}
public struct CipherReader {
public init(key: String)
public mutating func read(_ ciphertext: Data) throws -> Data // consumes header on first bytes; returns plaintext after the sacrificial block
}
```
`RandomBytes` is injectable so tests can pin whole streams.
### Consumed
- Nothing from other lanes.
## Status / TODO
- [ ] `Sources/MWBCore/MagicHash.swift` + `Tests/MWBCoreTests/MagicHashTests.swift`
with `Tests/Fixtures/magic_reference.py` (run once; vector committed).
- [ ] `Sources/MWBCore/CipherStream.swift`: key derivation, writer, reader.
- [ ] `Tests/MWBCoreTests/CipherStreamTests.swift`: PBKDF2 vector;
round-trip; byte-at-a-time reader equals all-at-once; unique
header per instance; wrong key ⇒ garbage without throwing;
descriptions omit secrets.
- [ ] Note in `docs/perf/README.md`: PBKDF2 at 100 000 rounds SHA-512
costs ~N ms per connection open (measure; it is per direction).
## Work log
## QA log
## Review
+84
View File
@@ -0,0 +1,84 @@
# packet-codec
## Goal
The `DATA` packet and its framing as Swift value types in `MWBCore`,
byte-exact with `docs/protocol.md` §1: the 32/64-byte layout, the
`PackageType` numbering and big/small rule, the ASCII machine name, and
the magic + checksum framing that overwrites bytes 1–3. This is the
foundation every other lane reads bytes through; it has no I/O and no
crypto.
## Assumptions
- **Little-endian, natural alignment, no padding**, because the Windows
side marshals an explicit-layout struct (`DATA.cs:135-149`). All
offsets are taken from `docs/protocol.md` §1.1, not recomputed.
- **`Type` is one byte on the wire.** The Swift type stores `PackageType`
as `UInt8` at offset 0; `Framing.open` zeroes bytes 1–3 exactly as
`ProcessReceivedDataEx` does, so a decoded packet's bytes 1–3 are
always 0 and re-sealing is deterministic.
- **The checksum covers bytes 2..31 only, even on 64-byte packets.** We
reproduce this, and pin it with a test that corrupts byte 40 of a
64-byte packet and asserts it is *not* detected — the encryption
layer, not the checksum, is what protects the name half.
- **Unknown type values decode as `.unknown(UInt8)`** rather than
throwing, so a newer Windows build cannot desynchronise our framing.
Size for an unknown value follows the big/small rule (`0x80` bit ⇒ 64,
else 32), which is what Windows would do.
- **Machine names are ASCII, ≤ 32, space-padded.** Non-ASCII input is an
error at construction time; on decode, bytes are trimmed of trailing
spaces and NULs (Windows trims spaces; NUL tolerance costs nothing).
- The magic number is a parameter of `Framing`, not computed here
(that is cipher-stream's `magicNumber(for:)`).
## Handshakes
### Promised (topo.md handshake 1, to session and every later consumer)
```swift
public enum PackageType: RawRepresentable { case hi, hello, … , unknown(UInt8); var rawValue: UInt8; var isBig: Bool }
public struct Packet {
public var type: PackageType; public var id: Int32; public var src: UInt32; public var des: UInt32
public var mouse: MouseData // X, Y, wheelDelta, flags at 16..31
public var keyboard: KeyboardData// dateTime at 16, vk at 24, flags at 28
public var nonce: (UInt32, UInt32, UInt32, UInt32)
public var postAction: UInt32
public var machineName: String? // nil on small packets
public var payload48: Data // bytes 16..63 for clipboard chunks
public init(type:) // zeroed buffer of the right size
public init?(bytes: Data) // 32 or 64 bytes, no framing check
public var bytes: Data // 32 or 64
}
public enum Framing {
public static func seal(_ p: Packet, magic: UInt32) -> Data
public static func open(_ bytes: Data, magic: UInt32) -> Packet // type == .invalid on bad framing
}
```
Exact spelling may change during the lane; the README is updated in the
same change and session codes against the README.
### Consumed
- Nothing. Foundation only.
## Status / TODO
- [ ] `Sources/MWBCore/Packet.swift`: `PackageType` (every value in
protocol §1.2), `isBig`, `Packet` with union views.
- [ ] `Sources/MWBCore/Framing.swift`: `seal` / `open` per §1.3.
- [ ] `Tests/MWBCoreTests/PacketTests.swift`: offsets pinned per field,
big/small over all 256 values, name padding/trim, non-ASCII refused.
- [ ] `Tests/MWBCoreTests/FramingTests.swift`: hand-assembled golden
bytes for Handshake / Mouse / Keyboard / Matrix(slot 4, both
flags) / ClipboardText chunk; round-trip property test; bytes
2..31 corruption detected; byte 40 corruption *not* detected.
- [ ] `docs/protocol.md`: add any offset or rule learned; keep
`[transcribed]` marks until interop-vectors.
## Work log
## QA log
## Review
+15
View File
@@ -0,0 +1,15 @@
# perf — budgets and measurements
Budgets (targets until measured; CLAUDE.md invariant 4 makes the first
one a hard rule):
| what | budget | how measured |
|---|---|---|
| `CGEventTap` callback, p99 | < 1 ms | `os_signpost` interval around the callback, `xctrace` or an in-app counter dumped on quit |
| capture → wire (tap callback to `NWConnection.send` enqueue), p99 | < 2 ms | signposts |
| Mouse packet end-to-end on a wired LAN (Mac tap → Windows cursor) | < 10 ms | camera-free: Windows side logs receive tick; compare clocks via NTP; or ping-pong a `Hi` and halve |
| Heartbeat/idle CPU | < 0.5 % | Activity Monitor over 10 min |
| Memory after 8 h soak | flat within 10 MB | `tools/guard.sh` + `ps` sampling |
Measurements: none yet. Each lane that touches the hot path appends a
dated block here.
+452
View File
@@ -0,0 +1,452 @@
# protocol.md — the Mouse Without Borders wire protocol, transcribed
**Purpose.** The single place the wire format is written down. Every fact
here is transcribed from the Windows source at
`/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/App/`
(commit `3104d5c`, v0.101.2572.0) and cited as `file:line`. The Windows
source is the authority; this file is our reading of it. Where a fact has
been confirmed against real Windows bytes it is marked **[verified]**;
everything else is **[transcribed]** until the `interop-vectors` feature
lands golden vectors captured from a Windows machine.
Transcribed 2026-09-15 (lead + Explore agent). Spot-checked by the lead the
same day: §1.3 framing, §2.1 magic hash, §2.2 cipher config, §2.3
sacrificial block (all read directly from source).
---
## 1. Packets
### 1.1 Layout — `Core/DATA.cs`
`DATA` is `[StructLayout(LayoutKind.Explicit)]` and marshalled with
`Marshal.StructureToPtr` (`DATA.cs:135-149`): **little-endian, natural
alignment, no padding.** Two sizes (`Core/Package.cs:17-19`):
`PACKAGE_SIZE = 32` (small), `PACKAGE_SIZE_EX = 64` (big).
| Offset | Size | Field | Notes |
|---|---|---|---|
| 0 | 4 | `Type` (`PackageType`, int) | **only byte 0 survives the wire** — bytes 1–3 are overwritten by framing (§1.3). `DATA.cs:27-28` |
| 4 | 4 | `Id` (int) | packet sequence number. `DATA.cs:30-31` |
| 8 | 4 | `Src` (`ID` = uint) | source machine id. `DATA.cs:33-34` |
| 12 | 4 | `Des` (`ID` = uint) | destination machine id. `DATA.cs:36-37` |
| 16 | 8 | `DateTime` (long) | only set for `Keyboard` (`Event.cs:266`), unused on receive |
| 24 | 8 | `Kd` (`KEYBDDATA`) | `{ int wVk; int dwFlags }` `Core/KEYBDDATA.cs:18-25` |
| 16 | 16 | `Md` (`MOUSEDATA`) | union with DateTime+Kd: `{ int X; int Y; int WheelDelta; int dwFlags }` `Core/MOUSEDATA.cs:18-26` |
| 16..28 | 4×4 | `Machine1..4` (`ID`) | union; handshake nonce words. `DATA.cs:48-58` |
| 16 | 4 | `PostAction` (uint) | union; clipboard post action. `DATA.cs:60-61` |
| 32 | 32 | `MachineName` | big packets only; 4×8 bytes `machineNameP1..P4`. `DATA.cs:63-94` |
`MachineName` is **ASCII** (`Common.GetBytes`, `Common.cs:397-405`),
right-padded with spaces to exactly 32 bytes, trimmed on read. The local
name is `Dns.GetHostName()` truncated to 32 chars (`Common.cs:1381-1384`).
Non-ASCII hostnames do not round-trip.
**Big vs small** (`DATA.cs:124-133`): a packet is 64 bytes iff `Type` ∈
{Hello, Awake, Heartbeat, Heartbeat_ex, Handshake, HandshakeAck,
ClipboardPush, Clipboard, ClipboardAsk, ClipboardImage, ClipboardText,
ClipboardDataEnd} **or** `(Type & 0x80) != 0` (Matrix). Everything else —
including `Heartbeat_ex_l2/l3`, `HideMouse`, `MachineSwitched`,
`NextMachine`, `Mouse`, `Keyboard`, `ByeBye`, `Hi` — is 32 bytes and
carries no machine name.
Receive is two-phase (`Class/SocketStuff.cs:558-610`): read exactly 32
bytes, validate framing, construct `DATA`; if big, read 32 more into
bytes 32..63.
### 1.2 `PackageType` — `Core/PackageType.cs:15-57`
| Name | Value | Size | Name | Value | Size |
|---|---|---|---|---|---|
| `Hi` | 2 | 32 | `ClipboardDataEnd` | 76 | 64 |
| `Hello` | 3 | 64 | `MachineSwitched` | 77 | 32 |
| `ByeBye` | 4 | 32 | `ClipboardAsk` | 78 | 64 |
| `Heartbeat` | 20 | 64 | `ClipboardPush` | 79 | 64 |
| `Awake` | 21 | 64 | `NextMachine` | 121 | 32 |
| `HideMouse` | 50 | 32 | `Keyboard` | 122 | 32 |
| `Heartbeat_ex` | 51 | 64 | `Mouse` | 123 | 32 |
| `Heartbeat_ex_l2` | 52 | 32 | `ClipboardText` | 124 | 64 |
| `Heartbeat_ex_l3` | 53 | 32 | `ClipboardImage` | 125 | 64 |
| `Clipboard` | 69 | 64 | `Handshake` | 126 | 64 |
| `ClipboardDragDrop` | 70 | 32 | `HandshakeAck` | 127 | 64 |
| `ClipboardDragDropEnd` | 71 | 32 | `Matrix` | 128 (0x80, flag) | 64 |
| `ExplorerDragDrop` | 72 | 32 | `MatrixSwapFlag` | 2 (OR'd into Matrix) | — |
| `ClipboardCapture` | 73 | 32 | `MatrixTwoRowFlag` | 4 (OR'd into Matrix) | — |
| `CaptureScreenCommand` | 74 | 32 | `Error` | 0xFE — local only (0-byte read) | — |
| `ClipboardDragDropOperation` | 75 | 32 | `Invalid` | 0xFF — local only (bad framing) | — |
All values fit in one byte by design (`PackageType.cs:17`).
### 1.3 Framing: magic + checksum in bytes 1–3 **[verified against source]**
Send — `SocketStuff.cs:497-529` (`TcpSendData`):
```
bytes[3] = (MagicNumber >> 24) & 0xFF
bytes[2] = (MagicNumber >> 16) & 0xFF
bytes[1] = 0
for i in 2..<32: bytes[1] = (bytes[1] + bytes[i]) & 0xFF // bytes 2..31 ONLY
write(bytes) // 32 or 64 bytes, through the cipher stream
```
Receive — `SocketStuff.cs:531-556` (`ProcessReceivedDataEx`), on the first
32 bytes only:
```
magic = (buf[3] << 24) | (buf[2] << 16)
if magic != (MagicNumber & 0xFFFF0000): buf[0] = 0xFF (Invalid)
if buf[1] != sum(buf[2..31]) & 0xFF: buf[0] = 0xFF (Invalid)
buf[1] = buf[2] = buf[3] = 0
```
Consequences: `Type` is effectively one byte; the checksum never covers
bytes 32..63; only the top 16 bits of the magic are transmitted.
### 1.4 Sequence numbers and replay window
`Id` is a process-global increment (`Common.cs:906`) persisted as the
`PackageID` setting. `Receiver.PreProcess` (`Core/Receiver.cs:40-82`)
keeps the last **50** ids in a ring and drops repeats, except for
`ClipboardText`, `ClipboardImage`, `Handshake`, `HandshakeAck`.
### 1.5 Machine IDs — `Core/ID.cs:15-19`
`ID` is `uint`; `NONE = 0`, `ALL = 255` (broadcast). A machine's own id is
a random non-negative `int` persisted as `MachineID`
(`Class/Setting.cs:1048-1083`), generated when 0, regenerated on collision
(`SocketStuff.cs:1984-1992`). Peers' ids are learned from `Src` during
handshake and heartbeats. **Exception:** in `Matrix` packets `Src` is a
1-based slot index (§4.2).
---
## 2. Cryptography — `Core/Encryption.cs`
### 2.1 Magic number **[verified against source]**
`Get24BitHash(MyKey)` (`Encryption.cs:173-200`), computed once per socket
open (`SocketStuff.cs:227`):
```
b = 32 zero bytes; for i in 0..<min(32, key.count): b[i] = UInt8(truncating: key.utf16[i])
h = SHA512(b)
50 000 times: h = SHA512(h) // 50 001 hashes in total
magic = UInt32((h[0] << 23) + (h[1] << 16) + (h[63] << 8) + h[2])
```
`h[0] << 23`, not `<< 24`: the shifted terms overlap at bit 23 and the
sum carries. Reproduce exactly. Only bits 16..31 of `magic` go on the wire.
### 2.2 Cipher **[verified against source]**
AES-256-CBC, **`PaddingMode.Zeros`**, 16-byte blocks
(`Encryption.cs:92-98`). Key = `PBKDF2-HMAC-SHA512(password: MyKey (UTF-8),
salt: 16 random bytes, iterations: 100 000, length: 32)`
(`Encryption.cs:107-115`, constants at `:38-45`).
### 2.3 Stream layout, per direction
Each direction of each connection is one continuous CBC stream
(`SocketStuff.cs:104, 118`; the two directions wrap separate
`NetworkStream`s over the same socket):
```
[16 bytes salt][16 bytes IV] cleartext header, written by the writer, read by the reader
(Encryption.cs:117-171)
[16 bytes random] FIRST ciphertext block: the "sacrificial" block,
written through the cipher and discarded by the reader
(Common.cs:1528-1558, wired at SocketStuff.cs:105,119)
[32 or 64 byte packets ...] framed as §1.3; no per-packet IV, no per-packet MAC
```
Zero padding never adds bytes because every write is a multiple of 16.
Framing is therefore entirely length-driven by `Type` (§1.1). The
clipboard channel (§5.3) uses the same layout.
### 2.4 The security key
- Minimum 16 characters; validation is length-only (`Encryption.cs:235-242`).
- Auto-generated keys are 16 chars drawn round-robin from
`abcdefghjkmnpqrstuvxyz`, `ABCDEFGHJKMNPQRSTUVXYZ`, `123456789`,
`` ~!@#$%^*()_-+=:;<,>.?/\|[] `` (`Encryption.cs:207-212`).
- Stored in **plaintext** in `settings.json` as `SecurityKey`
(`Class/Setting.cs:479-511`); a key change reopens all sockets.
---
## 3. Connections and handshake — `Class/SocketStuff.cs`
### 3.1 Ports and sockets
- `TCPPort` default **15100** (`MouseWithoutBordersProperties.cs:202`).
- Listener on **port + 1 (15101)**: control channel. Listener on **port
(15100)**: clipboard/file bulk channel (`SocketStuff.cs:475-495`).
- Clients connect to port+1 for control (`:1169`) and port for clipboard
(`Clipboard.cs:1087-1091`).
- Sockets are IPv6 dual-mode (`:1141-1142`).
- Each machine pair ends up with two control connections (one client
each way); dedup keeps the first connected client socket per peer
name (`:1980-2004`).
- Options: send/recv buffers 320 000, `NoDelay`, `SendTimeout` 500 ms
(`:1283-1286`). Connect retried every 1 s for 30 s (`:158, 276, 1179-1198`).
- **No UDP, no multicast, no discovery** anywhere in the module.
### 3.2 Handshake — `SocketStuff.cs:1261-1565` (`MainTCPRoutine`, same path client and server)
1. Build a `DATA` from 64 cryptographically random bytes (`:1269-1270`)
— `Machine1..4` at offsets 16..31 are the nonce.
2. Set `MachineName = local`, `Type = Handshake (126)`. Send it **10 times**
(`:1291-1294`). Set expected = `~Machine1..4` (`:1296-1299`).
3. On receiving `Handshake`: reply `HandshakeAck (127)` with `Src = own
id` (filled by `TcpSend`, `:666-669`), `MachineName = local`,
`MachineN = ~MachineN` (`:1371-1384`).
4. On receiving `HandshakeAck`: all four words must equal expected
(`:1409-1410`). Then `tcp.MachineId = Src`, status `Connected`, peer
name := `MachineName` from the packet (`:1412-1419`), and send an
initial heartbeat (`:1451`).
5. Guards: >10 non-handshake packets before trust ⇒ send `Invalid` ×10,
status `InvalidKey`, close (`:1387-1406`). Mismatched ack ⇒
`InvalidKey`. >10 failures from one endpoint ⇒ app quits
(`:1482-1499`). Peer name == own name ⇒ close (`:1430-1437`).
`SocketStatus` (`:54-66`): NA 0, Resolving 1, Connecting 2, Handshaking 3,
Error 4, ForceClosed 5, InvalidKey 6, Timeout 7, SendError 8, Connected 9.
Status colours are in `doc/devdocs/modules/mousewithoutborders.md`.
### 3.3 Liveness
- Heartbeat from the 100 ms UI timer (`frmScreen.cs:285-288, 566-575`):
every 60 s when `BlockScreenSaver` is on, else every 300 s.
`Awake (21)` if the user was recently active, else `Heartbeat (20)`
(`Common.cs:499-513, 662-676`).
- Key propagation chain during pairing: `Heartbeat_ex (51)` → receiver
adopts key, replies `Heartbeat_ex_l2 (52)` → `Heartbeat_ex_l3 (53)`
(`Receiver.cs:210-243`). *Port decision: not implemented in M2; the
key is typed on both sides.*
- `HEARTBEAT_TIMEOUT = 1 500 000 ms` (25 min) (`MachineStuff.cs:32`,
`MachinePool.cs:304-307`).
- `Hi (2)` is a liveness probe written by `TestSend` (`Common.cs:822-847`);
the receiver only counts it. `ByeBye (4)` on shutdown.
- Reconnect triggers (`InitAndCleanup.cs:28-31`, `frmScreen.cs:427-461`):
network change, sleep/wake, display change, connection reset, hotkey.
---
## 4. Machines, matrix, switching — `Core/MachineStuff.cs`, `Class/MachinePool.cs`
### 4.1 Model
- `MAX_MACHINE = 4`, `MAX_SOCKET = 8` (`MachineStuff.cs:30-31`).
- Matrix = `string[4]` of names (`:883-933`), persisted as
`MachineMatrixString`. Layout: one row `[0][1][2][3]` (`MatrixOneRow`,
default true; up/down disabled `:538-541, 607-610`) or two rows
`[0][1]/[2][3]`. `MatrixCircle` (= `WrapMouse`, default true) wraps.
- `MachinePool`: name↔id↔last-seen, max 4, serialized
`Name:Id,Name:Id,Name:Id,Name:Id`, default `:,:,:,:`
(`MachinePool.cs:195-243, 287-301`; parser `MachinePoolHelpers.cs:16-43`).
- `desMachineID` = machine receiving input; `ALL (255)` = broadcast
mode (`:1030-1050`). `LiveMachineMatrix` blanks disconnected slots in
one-row mode (`:935-945`).
### 4.2 Matrix replication
Four `Matrix` packets, one per slot: `Src = slot+1`, `Des = ALL`,
`MachineName = slot name`, `Type = 0x80 | (circle ? 2 : 0) | (oneRow ? 0 : 4)`
(`:952-976`). Receiver stores slot `Src-1`; on `Src == 4` commits flags
and reopens clients (`:978-1006`). Peers are also learned from
`Heartbeat`/`Hello`/`Awake` via `AddToMachinePool` (`:712-777`).
### 4.3 Edge detection — `MoveToMyNeighbourIfNeeded` (`:203-283`)
- `SKIP_PIXELS = 1`, `JUMP_PIXELS = 2` (`:33-34`); 100 ms debounce
(`:217`); disabled in ALL mode.
- `BlockMouseAtCorners`: no switch within 100 px of a monitor corner
(`:222-234`).
- Rectangle tested: `desktopBounds` (union of all monitors) when the
controller owns the cursor, else `primaryScreenBounds` (`:239-280`).
- `x < left+1` → left; `x >= right-1` → right; `y < top+1` → up;
`y >= bottom-1` → down.
### 4.4 Coordinates
Universal value (`:181-190`): `X = (x - r.left) * 65535 / r.width`,
same for Y — absolute 0..65535 relative to a rectangle chosen by mode
(`:385-421`):
| case | source rectangle |
|---|---|
| `MoveMouseRelatively` on | desktopBounds → 65535 → remote desktopBounds |
| off, switching back to the controller | primaryScreenBounds |
| off, switching away from the controller | desktopBounds |
| off, between two non-controllers | primaryScreenBounds |
Mouse-move packets (`Event.cs:112-113`): `Md.X = (x - primary.left) *
65535 / screenWidth` where `screenWidth` is the **primary** monitor
(`WinAPI.cs:70-80`). Receiver de-normalizes onto its **desktopBounds**
(`InputSimulation.cs:160-173`):
```
w = (dB.right - dB.left) * 65535 / screenWidth ; l = dB.left * 65535 / screenWidth
dx = X * w / 65535 + l (same for Y)
```
Relative mode biases: `MOVE_MOUSE_RELATIVE = 100 000` added to dx/dy
(`Event.cs:32`, `InputHook.cs:311-312`, stripped at `Receiver.cs:147-153`);
`XY_BY_PIXEL = 300 000` marks pixel coordinates on the local switch path
(`Event.cs:33`, `InputHook.cs:272-281`).
`NextMachine (121)` (`Common.cs:559-585`): `Md.X/Y` = landing point
0..65535, **`Md.WheelDelta` = target machine id**, `Des` = controller;
max one per 100 ms; sent by a controlled machine that hit its own edge
in relative mode (`Receiver.cs:156-170`).
### 4.5 Hotkeys (defaults from `MouseWithoutBordersProperties.cs`)
| Setting | Default | Notes |
|---|---|---|
| `HotKeySwitchMachine` | `0x70` VK_F1: Ctrl+Alt+F1..F4 → slot 0..3 | `InputHook.cs:611-658` |
| `LockMachineShortcut` | Win+Ctrl+Alt+L | twice within 500 ms ⇒ ALL mode + lock everywhere (`:539-577`) |
| `ReconnectShortcut` | Win+Ctrl+Alt+R | `PleaseReopenSocket` (`:578-584`) |
| `ToggleEasyMouseShortcut` | Win+Ctrl+Alt+E | |
| `Switch2AllPCShortcut` | disabled | |
| `HotKeyExitMM` | 0 (disabled) | `Setting.cs:811-817` |
Hotkeys are ignored if Shift or Win is also held with Ctrl+Alt
(`InputHook.cs:604-610`). Easy Mouse (`EasyMouseOption.cs`, default 1 =
always): 0 disabled, 1 enabled, Ctrl/Shift variants require the modifier.
---
## 5. Input encoding
### 5.1 Keyboard — `KEYBDDATA { wVk, dwFlags }`
- `wVk` = Windows **virtual-key code** (`InputHook.cs:347-349`). Scan
codes are never sent; the receiver regenerates one with
`MapVirtualKey` (`InputSimulation.cs:125`).
- `dwFlags` = raw `LLKHF` bits (`WM.cs:47-54`): `EXTENDED 0x01`,
`INJECTED 0x10`, `ALTDOWN 0x20`, `UP 0x80`.
- Receiver: `UP` → key up, `EXTENDED` → extended key
(`InputSimulation.cs:108-157`); 10 ms sleep after key-up sends
(`Event.cs:268-271`).
- Sender swallows the key locally whenever the destination is remote
(`InputHook.cs:361-368`).
### 5.2 Mouse — `MOUSEDATA { X, Y, WheelDelta, dwFlags }`
- `dwFlags` = the **`WM_*` message id** (`InputHook.cs:251`; `WM.cs:27-40`):
`MOUSEMOVE 0x200`, `LBUTTONDOWN 0x201`, `LBUTTONUP 0x202`,
`LBUTTONDBLCLK 0x203`, `RBUTTONDOWN 0x204`, `RBUTTONUP 0x205`,
`RBUTTONDBLCLK 0x206`, `MBUTTONDOWN 0x207`, `MBUTTONUP 0x208`,
`MBUTTONDBLCLK 0x209`, `MOUSEWHEEL 0x20A`, `XBUTTONDOWN 0x20B`,
`XBUTTONUP 0x20C`, `MOUSEHWHEEL 0x20E`.
- `WheelDelta = (short)(mouseData >> 16)` (`InputHook.cs:254`): signed
wheel delta in multiples of 120 for wheel events, XBUTTON1/2 index for
X-button events.
- Receiver maps to `MOUSEEVENTF` (`InputSimulation.cs:181-219`); moves
are absolute; `*DBLCLK` falls through and is effectively dropped.
### 5.3 Modifier and cursor state
- Sender tracks Win/Ctrl/Alt/Shift for hotkeys (`InputHook.cs:80-92,
371-473`; only LSHIFT toggles shift). Receiver tracks the same for
remote Win+L / Ctrl+Alt+Del interception (`InputSimulation.cs:358-475`).
- `ReleaseAllKeys` (`InitAndCleanup.cs:214-243`) synthesizes key-up for
every modifier that is down, at most once per 2 s, on switch / mode
change / lock.
- `HideMouse (50)` and local switch-away park the real cursor at the
primary screen's horizontal centre, y = 4 (`Common.cs:1482-1496`,
`Receiver.cs:383-388`). While controlled remotely the hook clamps the
virtual cursor to `primaryScreenBounds ± 1` (`InputHook.cs:293-309`).
---
## 6. Clipboard and files — `Core/Clipboard.cs`, `SocketStuff.cs`
### 6.1 Payload formats (`Helper/FormHelper.cs:180-218, 269-330`)
- **Text**: `"TXT" + unicode + SEP + "RTF" + rtf + SEP + "HTM" + html + SEP`
where `SEP = "{4CFF57F7-BEDD-43d5-AE8F-27A61E886F2F}"` (`Clipboard.cs:47`);
UTF-16LE encoded, then **Deflate** compressed (`Clipboard.cs:190-201`).
Reassembled at `:1148-1194`.
- **Image**: PNG bytes, uncompressed (`FormHelper.cs:281`).
- **File**: exactly one file path; folders refused (`SocketStuff.cs:1693`).
### 6.2 Small payloads — in-band on the control channel (≤ 1 MB compressed)
`SendClipboardDataUsingTCP` (`Clipboard.cs:253-306`): 64-byte packets of
type `ClipboardText (124)` / `ClipboardImage (125)`, `Des = ALL`, with
**48 payload bytes at offsets 16..63**; final chunk zero-padded, no
length field; terminated by `ClipboardDataEnd (76)`. Receiver appends
every chunk (`:308-373`) and aborts after 100 interleaved foreign packets.
### 6.3 Large payloads and files — bulk channel on port 15100
Signal: `Clipboard (69)` broadcast "I have big data" (`Common.cs:665`);
30 s window (`Clipboard.cs:42`). The machine being switched to pulls
(`Receiver.cs:284-291`, `Event.cs:219-231`, `MachineSwitched (77)`) or
asks for a push with `ClipboardAsk (78)` (`Clipboard.cs:425-449`).
Bulk connection (`Clipboard.ShakeHand` `:961-1060`, `SendClipboardData`
`SocketStuff.cs:1673-1811`, receive `Clipboard.cs:498-923`):
1. TCP to peer:15100, 30 s receive timeout, 1 024 000 buffers.
2. Same cipher layout as §2.3 (salt+IV header, sacrificial block).
3. One 64-byte `DATA` each way: `ClipboardPush (79)` if the connector
pushes, else `Clipboard (69)`; carries `Src`, `MachineName`, `PostAction`.
4. Accepted only if `MachinePool.ResolveID(name) == Src` and connected (`:1009`).
5. Sender writes a **1024-byte UTF-16LE zero-padded header**
`"<byteLength>*<name>"`, `name` ∈ {`text`, `image`, full file path};
failures encode as `"0*<path> not found!"` (`SocketStuff.cs:1701, 1749, 1781`).
6. Then raw bytes in 1 MB chunks (`Common.cs:112`), files padded to a
32-byte boundary (`SocketStuff.cs:1832-1836`); receiver reads exactly
`byteLength` (`Clipboard.cs:943-959`).
7. `ClipboardPostAction` (`Core/ClipboardPostAction.cs:20-25`): `Other 0`,
`Desktop 1`, `Mspaint 2`.
Limits: files ≤ **100 MB** (`Clipboard.cs:44`); clipboard events within
1 s of the previous are ignored (`:100-107`). Destination:
`<Desktop>\MouseWithoutBorders\` (`Common.cs:1291-1330`), committed
atomically via temp file + move (`Core/ReceivedDestinationFile.cs`).
### 6.4 Drag and drop — `Core/DragDrop.cs:25-51`
Packets `ExplorerDragDrop (72)`, `ClipboardDragDrop (70)`,
`ClipboardDragDropOperation (75)`, `ClipboardDragDropEnd (71)`; bytes
travel over §6.3. Requires the Windows-shell helper process. *Port
decision: out of scope for v1 (see TODO §9).*
---
## 7. Name resolution (no discovery)
1. For every non-local matrix name without a connection, start a client
(`SocketStuff.cs:797-837`).
2. Name → address by `Dns.GetHostEntry(name)` (`:950`), IPv4 and IPv6.
3. `Name2IP`: CRLF-separated lines of `"<name> <ip>"` (`:1258-1259`), used
in addition to DNS.
4. Optional reverse-lookup validation (`ValidateRemoteMachineIP`, `:991-1032`)
and same-subnet check that compares only the first two IPv4 octets
(`:1065-1107`).
5. Inbound peers are named by reverse DNS, domain suffix stripped
(`:733-762`), then overridden by the `HandshakeAck` name.
---
## 8. Settings file
`%LOCALAPPDATA%\Microsoft\PowerToys\MouseWithoutBorders\settings.json`,
`{ "name": "MouseWithoutBorders", "version": "1.1", "properties": {...} }`.
Property names, types and defaults: see `README.md` §Settings (transcribed
from `src/settings-ui/Settings.UI.Library/MouseWithoutBordersProperties.cs:165-206`).
---
## 9. What the Windows tests cover (and do not)
`MouseWithoutBorders.UnitTests/` (MSTest): AES round-trip and unique
salt/IV per stream (`EncryptionTests.cs`), received-file staging
(`ReceivedDestinationFileTests.cs`), logger formatting, settings IPC.
**No tests exist for packet layout, framing, handshake, matrix logic,
coordinate normalization or clipboard chunking** — the port has no
upstream oracle for those and must build its own (`interop-vectors`).
+141
View File
@@ -0,0 +1,141 @@
# topo.md — the dependency topology of mwb-mac
**Purpose.** The map an agent reads before touching anything: which
targets depend on which, which features consume which, and where the two
graphs meet. It exists to make parallel multi-agent development safe —
every edge below is an interface somebody can break. An absent edge is
only a candidate for independent work: confirm imports, shared files and
open handshakes before assigning ownership.
Sources of truth this document is derived from (and defers to on
conflict): `Package.swift`, each `docs/features/<name>/README.md`
(**Handshakes** in particular), `README.md`, `CLAUDE.md`,
`docs/protocol.md`. Drafted 2026-09-15 at planning time, before any code;
the lead updates it after every merged lane.
**Edge notation:**
| notation | meaning |
|---|---|
| `A ──▶ B` | **A consumes B.** B's published interface; B does not know A exists. Breaking B breaks A. |
| `A ◀──▶ B` | **Handshake.** A negotiated two-sided contract written down in one or both READMEs. Either side moving unilaterally breaks the other. |
| `A ─▶ B` | Not a dependency: `sequencing`, `standing promise`, `open request`. |
| *(absent)* | Nothing recorded. Confirm before treating as independent. |
---
## 1. Target dependency graph
```mermaid
graph TD
Core[MWBCore — Foundation + CommonCrypto only]
Net[MWBNet — Network.framework] --> Core
Mac[MWBMac — AppKit / CoreGraphics] --> Core
App[mwb executable] --> Core
App --> Net
App --> Mac
CT[MWBCoreTests] --> Core
NT[MWBNetTests] --> Net
```
Standing promises:
- `MWBCore ─▶ everyone` (standing promise): imports only `Foundation`
and `CommonCrypto`. Enforced by a test in `MWBCoreTests` that greps
the target's sources.
- `MWBNet` and `MWBMac` never import each other. The executable is the
only place they meet.
- Nothing outside `MWBCore` interprets packet bytes; `MWBNet` hands
`Data` to `Session` and `CipherReader`, `MWBMac` hands
`CapturedInput` values in and takes `Packet`-derived commands out.
### 1.1 Intra-target structure that matters for lanes
`MWBCore` files and who owns them at planning time:
| file | lane | consumers |
|---|---|---|
| `Packet.swift`, `Framing.swift` | packet-codec | session, matrix-edge, clipboard-inband, control-channel, bulk |
| `MagicHash.swift`, `CipherStream.swift` | cipher-stream | session (magic), control-channel, clipboard-bulk |
| `Session.swift` | session | control-channel |
| `Matrix.swift`, `Edge.swift` | matrix-edge | mwb, event-tap (edge), input-inject (coords) |
| `KeyMap.swift` | event-tap | input-inject |
| `ClipboardCodec.swift` | clipboard-inband | clipboard-bulk (header format only) |
| `Settings.swift` | menubar-app | everyone via `mwb` |
## 2. Feature dependency graph
### 2.1 Milestone order (sequencing, `─▶`)
```
bootstrap ─▶ { packet-codec ‖ cipher-stream }
─▶ { session ‖ matrix-edge }
─▶ { control-channel ‖ event-tap }
─▶ { input-inject ‖ screens-cursor }
─▶ { clipboard-inband ‖ menubar-app }
─▶ { clipboard-bulk ‖ interop-vectors }
─▶ end-to-end ─▶ soak
```
### 2.2 Consumption edges (`──▶`)
| consumer | consumes | what |
|---|---|---|
| session | packet-codec | `Packet`, `PackageType`, `Framing` |
| session | cipher-stream | `magicNumber(for:)` only |
| matrix-edge | packet-codec | `Packet` (Matrix, NextMachine, Mouse encode) |
| control-channel | session, cipher-stream, packet-codec | everything above the socket |
| event-tap | matrix-edge | `Edge` decisions on captured moves |
| input-inject | event-tap (KeyMap), matrix-edge (de-normalization), screens-cursor (desktop bounds) | |
| screens-cursor | matrix-edge | rectangle definitions |
| clipboard-inband | packet-codec | 64-byte chunk packets |
| clipboard-bulk | cipher-stream, packet-codec, clipboard-inband | stream layout, `DATA`, header/text format |
| menubar-app | every `MWBCore` type, control-channel, event-tap, screens-cursor | wiring |
| interop-vectors | packet-codec, cipher-stream, clipboard-inband | fixtures are tests for these |
| end-to-end | all | |
### 2.3 Handshakes (`◀──▶`) — all open at planning time
Numbered so lanes can cite them. A lane that needs one not listed here
files it in its README and flags it in its report; the lead adds it.
1. **packet-codec ◀──▶ session**: the `Packet` API shape (value type
with typed union views, `Data` in/out). packet-codec proposes in its
README; session consumes as published. Closed when session lands.
2. **cipher-stream ◀──▶ control-channel**: streaming `write/read`
returning `Data` with internal partial-block buffering; header and
sacrificial block handled inside the cipher types, not by the
channel. Closed when control-channel lands.
3. **session ◀──▶ control-channel**: `Session.feed(_:) -> [Event]`,
`Session.outgoing() -> Data`, injected `Clock`. The channel never
inspects packet bytes.
4. **matrix-edge ◀──▶ event-tap**: `Edge.evaluate(point:rect:now:)`
returns a `Switch?` decision. Debounce lives in `Edge` with the
injected clock; the tap only supplies points and timestamps.
5. **event-tap ◀──▶ input-inject**: the injected-event tag value
(`eventSourceUserData`) is one constant defined in `MWBMac/Injector.swift`
and read by `EventTap.swift`.
6. **screens-cursor ◀──▶ input-inject**: `Screens.desktopBounds` and
`primaryBounds` in CG coordinates (top-left origin, points).
7. **clipboard-inband ◀──▶ clipboard-bulk**: the `"<len>*<name>"`
header codec and the text tag/SEP codec live in `ClipboardCodec.swift`
and are reused by bulk unchanged.
8. **menubar-app ◀──▶ everyone**: `Settings` is the one struct passed
down; lanes read fields, never the file.
## 3. Which pairs may run in parallel
Proven independent by disjoint files **and** no edge above:
| wave | lane A | lane B | shared files |
|---|---|---|---|
| 1 | packet-codec | cipher-stream | none (both create their own files; `Package.swift` untouched) |
| 2 | session | matrix-edge | none; both consume packet-codec read-only |
| 3 | control-channel | event-tap | none; different targets |
| 4 | input-inject | screens-cursor | **edge 6** — screens-cursor publishes its API in its README first; input-inject codes against the README. Acceptable only because the API is two rectangles. |
| 5 | clipboard-inband | menubar-app | `Settings.swift` is menubar-app's; clipboard reads `ShareClipboard` via a constructor parameter, not the struct |
| 6 | clipboard-bulk | interop-vectors | `Tests/Fixtures/` is interop-vectors'; bulk adds tests under `Tests/MWBNetTests/` only |
Anything not in this table runs serially. `TODO.md`, `docs/protocol.md`
and `docs/perf/README.md` are shared-by-nature: append in your own
section only.
Executable
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Run a command under a memory and wall-clock guard.
#
# Usage: tools/guard.sh [-m MAX_GB] [-t MAX_SECONDS] -- <command...>
# tools/guard.sh -m 8 -t 900 -- swift test
#
# Every second the resident set of the command's whole process tree is
# summed; if it exceeds MAX_GB (default 8) or the clock exceeds MAX_SECONDS
# (default 1800) the tree is killed (TERM, then KILL) and the script exits
# 137 with a line saying why. Inherited from the lucisv repo, where a runaway
# test once consumed 100 GB and took the machine down (2026-09-03): agents
# run every `swift test`, fuzzer, soak test and two-process loopback run
# through this.
#
# macOS has no enforced `ulimit -v`, so the guard is a poller, not a cap:
# a process that allocates faster than one second's worth of headroom can
# still overshoot briefly. Standard tooling only (ps, awk, kill).
set -u
max_gb=8
max_s=1800
while [ $# -gt 0 ]; do
case $1 in
-m) max_gb=$2; shift 2 ;;
-t) max_s=$2; shift 2 ;;
--) shift; break ;;
*) echo "usage: $0 [-m MAX_GB] [-t MAX_SECONDS] -- <command...>" >&2; exit 2 ;;
esac
done
[ $# -gt 0 ] || { echo "guard.sh: no command" >&2; exit 2; }
# Keep the command's stdin: a plain `cmd &` in a non-interactive shell
# gives the job /dev/null, which silently empties any stdin-fed command.
exec 3<&0
"$@" <&3 &
root=$!
start=$(date +%s)
# The command's process tree: descendants by parent pid, transitively.
tree() {
local all="$1" next
while :; do
next=$(ps -axo pid=,ppid= | awk -v set=" $all " '
{ if (index(set, " " $2 " ") > 0 && index(set, " " $1 " ") == 0) printf "%s ", $1 }')
[ -z "$next" ] && break
all="$all $next"
done
echo "$all"
}
kill_tree() {
local pids; pids=$(tree "$root")
kill -TERM $pids 2>/dev/null
sleep 2
kill -KILL $pids 2>/dev/null
}
max_kb=$((max_gb * 1024 * 1024))
while kill -0 "$root" 2>/dev/null; do
pids=$(tree "$root")
rss=$(ps -o rss= -p $(echo "$pids" | tr ' ' ',') 2>/dev/null | awk '{s+=$1} END {print s+0}')
now=$(date +%s)
if [ "$rss" -gt "$max_kb" ]; then
echo "guard.sh: memory ${rss} kB exceeded ${max_gb} GB — killing: $*" >&2
kill_tree; exit 137
fi
if [ $((now - start)) -gt "$max_s" ]; then
echo "guard.sh: ${max_s} s exceeded — killing: $*" >&2
kill_tree; exit 137
fi
sleep 1
done
wait "$root"