Files
mac_without_borders/docs/protocol.md
T
lucioandClaude Fable 5.1 69c0f7ab53 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]>
2026-09-15 23:33:27 -07:00

21 KiB
Raw Blame History

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 NetworkStreams 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).