brief: wire-core; consolidate the backlog into eight serial lanes

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-16 00:02:11 -07:00
1 parent 5bb415c7bc
commit 9810ba441b
6 files changed
+295 -337

No files matched your search

+136 -117
View File
@@ -1,156 +1,175 @@
# TODO — mwb-mac backlog, one lane at a time
Legend: **(core)** `MWBCore`, **(net)** `MWBNet`, **(mac)** `MWBMac`,
**(app)** executable/tooling. Lanes run strictly in this order
(`docs/topo.md` §3, `docs/loop.md` §6); each lane ticks only its own
lines. Items describe Windows behaviour to port, with the
`docs/protocol.md` section that specifies it. No test-writing items
exist by the user's instruction — the user tests the app.
Lanes run strictly in this order (`docs/loop.md`). Each lane ticks only
its own lines. Items name the Windows behaviour to port and the
`docs/protocol.md` section (§) or Windows file that specifies it. There
are no test-writing items: the user tests the app (CLAUDE.md).
Target: a native macOS app with a menu-bar status item and a settings
window that supports every function of the PowerToys module except the
ones in §Out of scope.
---
## 0. bootstrap (app) — done 2026-09-15
## 0. bootstrap — done 2026-09-15
- [x] SwiftPM skeleton, four targets, layering enforced by `tools/gates.sh`.
- [x] `tools/gates.sh` (lint + build), `tools/bundle.sh`, `tools/lane.sh`,
`.swift-format`, `Resources/Info.plist`.
- [x] `mwb --version`, `mwb --check-permissions`.
- [x] `docs/loop.md`, `docs/features/TEMPLATE.md`.
- [x] Xcode 27.0 installed; toolchain verified.
- [x] SwiftPM skeleton, `tools/gates.sh`, `tools/bundle.sh`, `tools/lane.sh`,
`mwb --version` / `--check-permissions`, `docs/loop.md`.
## 1. packet-codec (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift`
## 1. wire-core (core) — `Sources/MWBCore/Packet.swift`, `Framing.swift`, `MagicHash.swift`, `CipherStream.swift`
- [ ] `PackageType` (raw `UInt8`, every value in protocol §1.2), the
big/small rule §1.1, unknown values tolerated.
- [ ] `Packet` value type over a 32/64-byte little-endian buffer with the
union views: mouse, keyboard, nonce, postAction, machineName,
48-byte clipboard payload at offset 16.
- [ ] ASCII, space-padded, 32-byte machine name; non-ASCII refused.
- [ ] `Framing.seal` / `Framing.open` exactly as §1.3 (checksum over
bytes 2..31 only; magic top 16 bits; bytes 1–3 zeroed on open).
- [ ] `PackageType` (raw `UInt8`, every value §1.2), big/small rule §1.1,
unknown values tolerated.
- [ ] `Packet` over a 32/64-byte little-endian buffer with union views:
mouse, keyboard, nonce, postAction, machineName, 48-byte clipboard
payload at offset 16.
- [ ] ASCII space-padded 32-byte machine name; non-ASCII refused.
- [ ] `Framing.seal` / `open` exactly §1.3 (checksum bytes 2..31, magic
top 16 bits, bytes 1–3 zeroed on open).
- [ ] `magicNumber(for:)` §2.1 (50 001 SHA-512 rounds, `<< 23` overlap,
UTF-16 unit truncated to a byte, 32-byte buffer).
- [ ] PBKDF2-HMAC-SHA512 100 000 rounds / 32 bytes via CommonCrypto;
`CipherWriter` / `CipherReader` with 16+16 header, sacrificial
block, streaming AES-256-CBC no padding §2.3. No secrets in
descriptions or logs.
- [ ] Key rules §2.4: 16-char minimum, generator with the four charsets,
display grouping.
## 2. cipher-stream (core) — `Sources/MWBCore/MagicHash.swift`, `CipherStream.swift`
## 2. session-matrix (core) — `Sources/MWBCore/Session.swift`, `Matrix.swift`, `MachinePool.swift`, `Edge.swift`, `Coordinates.swift`
- [ ] `magicNumber(for:)` per §2.1 (50 001 SHA-512 rounds, `<< 23`
overlap, UTF-16 unit truncated to a byte, 32-byte buffer).
- [ ] PBKDF2-HMAC-SHA512, 100 000 rounds, 32 bytes, via CommonCrypto.
- [ ] `CipherWriter` / `CipherReader`: 16+16 cleartext header, 16-byte
sacrificial block, AES-256-CBC no padding, streaming with partial
block buffering (§2.3). Descriptions never include secrets.
- [ ] `Session`: sans-I/O state machine, `feed(bytes) -> [Event]`,
`outgoing() -> Data`, `SocketStatus` NA…Connected §3.2, injected clock.
- [ ] Handshake §3.2: 10× `Handshake`, nonce complement, `HandshakeAck`,
adopt peer name/id, >10 untrusted ⇒ InvalidKey, self-connect close,
>10 failures ⇒ give up.
- [ ] Dedup ring of 50 ids with the four exemptions §1.4; `Id` counter
persisted via settings hook.
- [ ] Heartbeat 60 s / 300 s, `Awake` vs `Heartbeat`, `Hi`, `ByeBye`,
25 min liveness §3.3.
- [ ] `Matrix` (4 slots, one/two rows, wrap) and `MachinePool`
(`Name:Id,…`, alive) §4.1; `Matrix` packet encode/decode §4.2;
learning peers from Heartbeat/Hello/Awake; `LiveMachineMatrix`.
- [ ] Switching: move left/right/up/down, `desMachineID`, ALL mode,
`MachineSwitched`, `NextMachine` (id in `WheelDelta`) §4.4.
- [ ] Edge detection §4.3 (primary-vs-desktop rule, 100 ms debounce,
corner blocking) and coordinate normalisation §4.4 (four rectangle
cases, `MOVE_MOUSE_RELATIVE` / `XY_BY_PIXEL` biases).
## 3. session (core) — `Sources/MWBCore/Session.swift`
## 3. control-channel (net) — `Sources/MWBNet/ControlChannel.swift`, `PeerConnection.swift`, `Resolver.swift`
- [ ] Sans-I/O state machine: `feed(bytes) -> [Event]`, `outgoing() -> Data`,
`SocketStatus` NA…Connected (§3.2).
- [ ] Handshake: 10× `Handshake`, nonce complement, `HandshakeAck`, adopt
peer name/id, >10 untrusted packets ⇒ InvalidKey, self-connection
close, >10 failures from one endpoint ⇒ give up (§3.2).
- [ ] Dedup ring of 50 ids with the four exemptions (§1.4).
- [ ] Heartbeat 60 s / 300 s, `Awake` vs `Heartbeat`, `Hi` counting,
`ByeBye`, 25 min liveness; injected clock (§3.3).
## 4. matrix-edge (core) — `Sources/MWBCore/Matrix.swift`, `Edge.swift`
- [ ] `Matrix` (4 slots, one/two rows, wrap), `MachinePool`
(`Name:Id,…` serialisation, 25 min alive) §4.1.
- [ ] `Matrix` packet encode/decode (slot in `Src`, flags in `Type`) §4.2;
learning peers from Heartbeat/Hello/Awake.
- [ ] `LiveMachineMatrix`, move left/right/up/down, `desMachineID`, ALL mode.
- [ ] Edge detection §4.3 (primary-vs-desktop rectangle rule, 100 ms
debounce, corner blocking) and coordinate normalisation §4.4 (all
four rectangle cases, relative-move biases, `NextMachine`).
## 5. control-channel (net) — `Sources/MWBNet/ControlChannel.swift`, `Resolver.swift`
- [ ] `NWListener` on port+1, both IP families; one `NWConnection` per
non-local matrix name; 1 s retry for 30 s; one client socket per
peer (§3.1).
- [ ] `NWListener` on port+1, both IP families; one client per non-local
matrix name; 1 s retry for 30 s; one connected client per peer §3.1.
- [ ] `PeerConnection`: one `Session` + cipher pair; serialised sends with
500 ms timeout; 32-then-32 receive; status reported for the UI colours.
- [ ] `Resolver`: `getaddrinfo` + `Name2IP` lines; optional /16 and
reverse-lookup checks (§7).
- [ ] One `Session` + one cipher pair per connection; serialised sends
with 500 ms timeout; 32-then-32 receive.
- [ ] Reconnect on path change, wake, reset, hotkey; delete `Placeholder.swift`.
reverse-lookup checks off by default §7.
- [ ] Reconnect triggers §3.3: `NWPathMonitor` change, wake, reset,
hotkey; `reopenAll()`; delete `Placeholder.swift`.
- [ ] Machine-ID collision ⇒ regenerate and reopen (§1.5).
## 6. event-tap (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Sources/MWBCore/KeyMap.swift`
## 4. input-capture (mac) — `Sources/MWBMac/EventTap.swift`, `Permissions.swift`, `Screens.swift`, `Cursor.swift`, `Hotkeys.swift`, `Sources/MWBCore/KeyMap.swift`
- [ ] `Permissions.request…` added to the existing preflight file.
- [ ] Session-level, head-insert, swallowing `CGEventTap` for keys,
flags, mouse, scroll; enqueue and return; pass tagged injected
- [ ] `Permissions.request…` added to the preflight file.
- [ ] Session-level head-insert swallowing `CGEventTap` for keys, flags,
mouse, scroll; classify → enqueue → return; pass tagged injected
events; re-enable on timeout/user-input disable (invariants 3, 4).
- [ ] Modifier tracking and hotkey matching per §4.5 with D4 mapping
(⌘=Win, ⌥=Alt); Easy Mouse modes.
- [ ] `KeyMap`: macOS keycode ↔ Windows VK, `flagsChanged` → modifier
VK pairs, `LLKHF` flags; `WM_*` mouse mapping, wheel ×120,
X-buttons, absolute 0..65535 moves (§5).
- [ ] `KeyMap`: macOS keycode ↔ Windows VK, `flagsChanged` → modifier VK
pairs, `LLKHF` flags §5.1; `WM_*` mouse mapping, wheel ×120,
X-buttons, absolute 0..65535 moves §5.2.
- [ ] Hotkeys §4.5 with D4 (⌘=Win, ⌥=Alt): switch machine ⌃⌥F1–F4,
lock (double-press ⇒ ALL + lock), reconnect, toggle Easy Mouse,
switch-to-all; ignore when Shift/⌘ also held; Easy Mouse modes.
- [ ] `Screens`: displays, primary, desktop union, corners; refresh on
change. `Cursor`: park (centre-x, y=4) / hide, decouple while
controlling remote, restore; `HideMouse (50)`; clamp while
controlled §5.3.
## 7. screens-cursor (mac) — `Sources/MWBMac/Screens.swift`, `Cursor.swift`
- [ ] Display list, primary, desktop union, corner points; refresh on
screen-parameter change.
- [ ] Park/hide cursor (primary centre-x, y=4), decouple cursor while
controlling a remote, restore on return; `HideMouse (50)` (§5.3).
## 8. input-inject (mac) — `Sources/MWBMac/Injector.swift`
## 5. input-inject (mac) — `Sources/MWBMac/Injector.swift`, `KeyState.swift`
- [ ] `Keyboard` packet → `CGEvent` down/up via KeyMap; modifiers as
`flagsChanged`; repeat as repeated downs.
`flagsChanged`; repeats as repeated downs; 10 ms after key-up like
Windows only if needed.
- [ ] `Mouse` packet → absolute move (de-normalise onto desktop bounds
§4.4), buttons with click-count, wheel (`WheelDelta`/120), X-buttons.
- [ ] Injected-event tag; `ReleaseAllKeys` on switch/lock; remote Win+L
→ lock; remote Ctrl+Alt+Del → ignored.
- [ ] Injected-event tag (shared constant with the tap);
`ReleaseAllKeys` on switch/lock/mode change; remote Win+L ⇒ lock
(`CGSession -suspend`); remote Ctrl+Alt+Del ⇒ ignored, logged.
## 9. menubar-app (app + core + mac) — `Sources/mwb/*`, `Sources/MWBMac/StatusItem.swift`, `Sources/MWBCore/Settings.swift`
## 6. app-shell (app + core + mac) — `Sources/mwb/*`, `Sources/MWBCore/Settings.swift`, `Sources/MWBMac/StatusItem.swift`, `Sources/MWBMac/SettingsWindow/*.swift`, `Sources/MWBMac/Notifications.swift`
- [ ] `Settings`: PowerToys schema (README §Settings), load/save/watch,
0600, random key / `MachineID` / `DeviceID` on first run.
- [ ] Menu-bar item with per-machine status dots in the documented
colours; matrix editor; key entry; port; toggles; Reconnect; Quit.
- [ ] Permissions onboarding; LaunchAgent install/uninstall; single
instance; logs without key material.
- [ ] Wire everything: tap → edge → session → channel → injector.
- [ ] **Hand `dist/mwb.app` to the user** with a checklist: switch by
edge and hotkey, wrap, one/two rows, keyboard with modifiers and
function keys, wheel, reconnect after sleep, wrong key, peer
killed mid-control.
- [ ] `Settings`: PowerToys schema (README §Settings), JSON load/save at
`~/Library/Application Support/mwb-mac/settings.json` (0600),
file watch, random key / `MachineID` / `DeviceID` on first run,
`LastX/LastY/PackageID` persistence.
- [ ] Menu-bar `NSStatusItem`: per-machine status dot in the documented
colours (`doc/devdocs/modules/mousewithoutborders.md`), current
controlled machine, Reconnect, Easy Mouse toggle, Lock all, Open
Settings, Quit.
- [ ] Settings window (SwiftUI): machine matrix editor (4 slots,
drag-reorder, one/two rows), security key (show/generate/copy),
port, every boolean in README §Settings, Easy Mouse picker, hotkey
recorders, Name2IP editor, permissions status with "Open System
Settings" buttons, LaunchAgent toggle.
- [ ] Status messages (`ShowClipboardAndNetworkStatusMessages`) via
`UserNotifications`.
- [ ] Wiring: tap → edge → session → channel → injector; single instance;
logs at `~/Library/Logs/mwb-mac/` without key material.
- [ ] **Hand `dist/mwb.app` to the user** (docs/loop.md §7) with a
checklist: switch by edge and hotkey, wrap, one/two rows, keyboard
with modifiers and function keys, wheel, reconnect after sleep,
wrong key, peer killed mid-control.
## 10. clipboard-inband (core + mac) — `Sources/MWBCore/ClipboardCodec.swift`, `Sources/MWBMac/Pasteboard.swift`
## 7. clipboard (core + net + mac) — `Sources/MWBCore/ClipboardCodec.swift`, `Sources/MWBMac/Pasteboard.swift`, `Sources/MWBNet/BulkChannel.swift`, `Sources/MWBMac/ReceivedFile.swift`
- [ ] Text codec `TXT`/`RTF`/`HTM` + SEP, UTF-16LE, raw DEFLATE (§6.1);
confirm Foundation `.zlib` matches .NET `DeflateStream` by
reasoning from the docs, note the decision.
- [ ] 48-byte chunks at offset 16, `ClipboardDataEnd`, zero-padding
semantics, 1 MB limit (§6.2); PNG images.
- [ ] `NSPasteboard` polling (500 ms), 1 s suppression, write on
receive, `ShareClipboard` flag.
- [ ] Text codec `TXT`/`RTF`/`HTM` + SEP, UTF-16LE, raw DEFLATE §6.1
(Foundation `.zlib` is raw DEFLATE like .NET `DeflateStream`; say so);
PNG images; single file path.
- [ ] In-band: 48-byte chunks at offset 16, `ClipboardDataEnd`,
zero-padding, 1 MB limit §6.2.
- [ ] Bulk channel §6.3: listener on port, `Clipboard (69)` broadcast,
pull on `MachineSwitched`, push on `ClipboardAsk`, cipher layout,
64-byte `DATA` each way, `"<len>*<name>"` 1024-byte UTF-16LE header,
1 MB chunks, 32-byte file padding, exact-length read.
- [ ] Files: atomic temp-file commit to `~/Desktop/MouseWithoutBorders/`,
100 MB limit, folders refused, `TransferFile` flag; reveal in Finder.
- [ ] `Pasteboard`: `changeCount` poll 500 ms, 1 s suppression, write on
receive (text/RTF/HTML/PNG/file URL), `ShareClipboard` flag.
## 11. clipboard-bulk (net) — `Sources/MWBNet/BulkChannel.swift`
## 8. extras (mac + core) — `Sources/MWBMac/Awake.swift`, `Sources/MWBMac/Fullscreen.swift`, `Sources/MWBMac/FakeCursor.swift`
- [ ] Listener on port; `Clipboard (69)` broadcast; pull on
`MachineSwitched`, push on `ClipboardAsk` (§6.3).
- [ ] Bulk handshake, 1024-byte UTF-16LE `"<len>*<name>"` header, 1 MB
chunks, 32-byte file padding, exact-length read, atomic commit to
`~/Desktop/MouseWithoutBorders/`; 100 MB limit; `TransferFile` flag.
- [ ] `BlockScreenSaverOnOtherMachines`: hold an `IOPMAssertion`
(`PreventUserIdleDisplaySleep`) while `Awake` packets arrive within
the heartbeat window; release on `Heartbeat`/timeout (§3.3).
- [ ] `DisableEasyMouseWhenForegroundWindowIsFullscreen` +
`EasyMouseFullscreenSwitchBlockExcludedApps`: frontmost app via
`NSWorkspace`, fullscreen via the Accessibility API; excluded-apps
editor in the settings window.
- [ ] `DrawMouseCursor` / `DrawMouseEx`: a borderless transparent overlay
window drawing a cursor image where the remote pointer is, so the
user sees where the pointer went (Windows `CustomCursor.cs`).
- [ ] `BlockMouseAtScreenCorners` end-to-end; `MoveMouseRelatively`
end-to-end with `NextMachine` §4.4.
## 12. end-to-end polish
## 9. polish — driven by the user's testing
- [ ] Driven entirely by the user's testing findings; each becomes a
line here with the lane that owns the fix.
- [ ] Each finding from the user becomes a line here with the file that
owns the fix.
## 13. Later (post-v1)
## Later (post-v1)
- [ ] Keychain storage for `SecurityKey` (D3).
- [ ] Easy Mouse fullscreen suppression + excluded apps.
- [ ] `Heartbeat_ex` key propagation (§3.3).
- [ ] "Swap ⌘/⌃ when controlling Windows" option.
- [ ] Non-US keyboard layouts: by position vs by character.
- [ ] CI on the Gitea runner running `tools/gates.sh` (lint + build only).
- [ ] Non-US layouts: VKs by position vs by character.
- [ ] Finder drag-and-drop file transfer (the Windows Explorer
choreography §6.4, re-designed for Finder).
- [ ] CI on the Gitea runner running `tools/gates.sh`.
- [ ] Updates, notarization, Homebrew cask.
## 14. Out of scope, with reasons (D6)
## Out of scope, with reasons (D6)
- Windows service / logon-screen / UAC secure-desktop control: the macOS
login window cannot be driven from a user-session event tap.
- Explorer drag-and-drop (§6.4): depends on a Windows-shell helper.
- Screen capture to Paint: niche; packets ignored and logged.
- GPO, telemetry, `ShowOriginalUI`: Windows-only.
- Animated fake cursor (`DrawMouse`): cosmetic.
- Screen capture to Paint (`CaptureScreenCommand`): niche; packets are
ignored and logged.
- GPO, telemetry, `ShowOriginalUI`, `UseService`: Windows-only.
-74
View File
@@ -1,74 +0,0 @@
# 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).
- **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**
(`EncryptionTests.cs:59-68` documents the Windows expectation).
- **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 the lead can reproduce a stream by hand when checking against a Windows capture.
### Consumed
- Nothing from other lanes.
## Status / TODO
- [ ] `Sources/MWBCore/MagicHash.swift`: `magicNumber(for:)` per §2.1,
every step cited to `Encryption.cs:173-200`.
- [ ] `Sources/MWBCore/CipherStream.swift`: PBKDF2 key derivation,
`CipherWriter`, `CipherReader` (header, sacrificial block,
streaming CBC), cited to `Encryption.cs` and `Common.cs:1528-1558`.
- [ ] `docs/perf/README.md`: note the PBKDF2 cost per connection open.
## Work log
## QA log
## Review
-77
View File
@@ -1,77 +0,0 @@
# 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; the encryption layer, not the checksum, is what
protects the name half. Say so in a comment at the checksum loop.
- **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, cited), `isBig`, `Packet` with the union views.
- [ ] `Sources/MWBCore/Framing.swift`: `seal` / `open` per §1.3, each
constant cited to `SocketStuff.cs`.
- [ ] `docs/protocol.md`: add any offset or rule learned while porting.
## Work log
## QA log
## Review
+104
View File
@@ -0,0 +1,104 @@
# wire-core
## Goal
The bytes of the protocol as Swift value types in `MWBCore`, byte-exact
with `docs/protocol.md` §1–§2: the 32/64-byte `DATA` packet and its
union views, the `PackageType` numbering and big/small rule, the ASCII
machine name, the magic + checksum framing that overwrites bytes 1–3,
the magic-number hash of the security key, PBKDF2 key derivation, and
the per-direction AES-256-CBC stream with its cleartext salt+IV header
and sacrificial first block. No I/O. Every later lane reads and writes
the wire through this code, and wire compatibility with the unmodified
Windows build is the whole point (CLAUDE.md invariant 1).
## Assumptions
- **Little-endian, natural alignment, no padding**, because the Windows
side marshals an explicit-layout struct (`DATA.cs:135-149`). Offsets
come from `docs/protocol.md` §1.1, not recomputed.
- **`Type` is one byte on the wire.** Stored as `UInt8` at offset 0;
`Framing.open` zeroes bytes 1–3 exactly as `ProcessReceivedDataEx`
does (`SocketStuff.cs:531-556`).
- **The checksum covers bytes 2..31 only, even on 64-byte packets**
(`SocketStuff.cs:510-513`). The cipher, not the checksum, protects
the name half. Say so in a comment at the loop.
- **Unknown type values decode as `.unknown(UInt8)`**, not an error, so
a newer Windows build cannot desynchronise framing; their size follows
the `0x80` rule.
- **Machine names are ASCII, ≤ 32, space-padded** (`Common.cs:397-405`,
`DATA.cs:75-94`); non-ASCII is a construction error; decode trims
trailing spaces and NULs.
- **CryptoKit cannot do CBC**, so AES is `CCCryptorCreate` with
`options = 0` (CBC, no padding) and `CCCryptorUpdate` per chunk. Zero
padding on Windows never emits bytes because every write is a multiple
of 16; we do no padding.
- **PBKDF2 is `CCKeyDerivationPBKDF`** with `kCCPRFHmacAlgSHA512`,
100 000 rounds, 32 bytes, password = UTF-8 of the key
(`Encryption.cs:107-115`).
- **The magic hash truncates each UTF-16 unit to a byte** and hashes a
fixed 32-byte buffer (`Encryption.cs:180-186`); the `<< 23` overlap
is reproduced with `UInt32` wrapping arithmetic in the C# order.
- **Salt and IV are fresh per direction**; the sacrificial block is
inside the cipher types' contract: the writer emits it after the
header, the reader discards the first 16 plaintext bytes
(`Common.cs:1528-1558`).
- **A wrong key is not detectable here** (no MAC). The reader returns
garbage and framing rejects it, matching Windows (`InvalidKey` after
more than 10 bad packets).
## Handshakes
### Promised (topo.md handshakes 1 and 2, to session-matrix, control-channel, clipboard)
```swift
public enum PackageType: RawRepresentable, Sendable { case hi, hello, …, unknown(UInt8); var rawValue: UInt8; var isBig: Bool }
public struct Packet: Sendable {
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 // .invalid on bad framing
}
public enum MagicHash { public static func magicNumber(for key: String) -> UInt32 }
public enum SecurityKey { public static func isValid(_:) -> Bool; public static func random() -> String; public static func displayText(_:) -> String }
public struct CipherWriter { public init(key: String) throws; public mutating func header() -> Data; public mutating func write(_ plaintext: Data) throws -> Data }
public struct CipherReader { public init(key: String); public mutating func read(_ ciphertext: Data) throws -> Data }
```
Exact spelling may change during the lane; this README is updated in
the same change and later lanes code against it.
### Consumed
- Nothing. Foundation, CommonCrypto, CryptoKit only.
## Status / TODO
- [ ] `Sources/MWBCore/Packet.swift`: `PackageType` (every value §1.2,
cited), `isBig`, `Packet` with union views, machine name rules.
- [ ] `Sources/MWBCore/Framing.swift`: `seal` / `open` per §1.3, each
constant cited to `SocketStuff.cs`.
- [ ] `Sources/MWBCore/MagicHash.swift`: `magicNumber(for:)` §2.1 cited
to `Encryption.cs:173-200`; `SecurityKey` rules §2.4
(`Encryption.cs:207-242`, `:65-79`).
- [ ] `Sources/MWBCore/CipherStream.swift`: PBKDF2, `CipherWriter`,
`CipherReader` (header, sacrificial block, streaming CBC), cited to
`Encryption.cs` and `Common.cs:1528-1558`; the CommonCrypto wrapper
lives in this one file.
- [ ] `docs/protocol.md`: add anything learned while porting, cited.
## Work log
## QA log
## Review
+10 -13
View File
@@ -147,23 +147,20 @@ carry into the next brief.
## 6. Lane order
Strictly one at a time, in this order (from `docs/topo.md` §3):
Strictly one at a time, in this order (mirrors `TODO.md`):
| # | lane | status |
|---|---|---|
| 0 | bootstrap | merged 2026-09-15 (lead, solo) |
| 1 | packet-codec | brief written |
| 2 | cipher-stream | brief written |
| 3 | session | |
| 4 | matrix-edge | |
| 5 | control-channel | |
| 6 | event-tap | |
| 7 | screens-cursor | |
| 8 | input-inject | |
| 9 | menubar-app | — first user-testable milestone: two Macs, or Mac ↔ Windows, mouse and keyboard |
| 10 | clipboard-inband | |
| 11 | clipboard-bulk | |
| 12 | end-to-end polish | driven by the user's testing findings |
| 1 | wire-core | brief written |
| 2 | session-matrix | |
| 3 | control-channel | |
| 4 | input-capture | |
| 5 | input-inject | |
| 6 | app-shell | first user-testable build: menu bar + settings window + mouse/keyboard sharing |
| 7 | clipboard | |
| 8 | extras | screensaver blocking, fullscreen Easy Mouse rule, drawn cursor |
| 9 | polish | driven by the user's testing |
## 7. Escalations — things only the user can do
+45 -56
View File
@@ -53,24 +53,24 @@ Standing promises:
| 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` |
| `Packet.swift`, `Framing.swift` | wire-core | session, session-matrix, clipboard, control-channel, bulk |
| `MagicHash.swift`, `CipherStream.swift` | wire-core | session-matrix (magic), control-channel, clipboard |
| `Session.swift` | session-matrix | control-channel |
| `Matrix.swift`, `Edge.swift` | session-matrix | mwb, input-capture (edge), input-inject (coords) |
| `KeyMap.swift` | input-capture | input-inject |
| `ClipboardCodec.swift` | clipboard | clipboard (header format only) |
| `Settings.swift` | app-shell | everyone via `mwb` |
`MWBMac` files owned at planning time:
| file | lane | note |
|---|---|---|
| `Permissions.swift` | bootstrap → **event-tap** | preflight shipped by bootstrap; event-tap adds `request…` and owns the file from wave 3 |
| `EventTap.swift` | event-tap | |
| `Permissions.swift` | bootstrap → **input-capture** | preflight shipped by bootstrap; input-capture adds `request…` and owns the file from wave 3 |
| `EventTap.swift` | input-capture | |
| `Injector.swift` | input-inject | defines the injected-event tag (handshake 5) |
| `Screens.swift`, `Cursor.swift` | screens-cursor | |
| `Pasteboard.swift` | clipboard-inband | |
| `StatusItem.swift` | menubar-app | |
| `Screens.swift`, `Cursor.swift` | input-capture | |
| `Pasteboard.swift` | clipboard | |
| `StatusItem.swift` | app-shell | |
`MWBNet/Placeholder.swift` is deleted by control-channel.
@@ -82,26 +82,25 @@ lead's; a lane needing a change there files a Handshake request.
### 2.1 Lane order (sequencing, `─▶`)
```
bootstrap ─▶ packet-codec ─▶ cipher-stream ─▶ session ─▶ matrix-edge
─▶ control-channel ─▶ event-tap ─▶ screens-cursor ─▶ input-inject
─▶ menubar-app (first user-testable build)
─▶ clipboard-inband ─▶ clipboard-bulk ─▶ end-to-end polish
bootstrap ─▶ wire-core ─▶ session-matrix ─▶ control-channel
─▶ input-capture ─▶ input-inject ─▶ app-shell (first user-testable build)
─▶ clipboard ─▶ extras ─▶ polish
```
### 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 |
| session-matrix | wire-core | `Packet`, `PackageType`, `Framing` |
| session-matrix | wire-core | `magicNumber(for:)` only |
| session-matrix | wire-core | `Packet` (Matrix, NextMachine, Mouse encode) |
| control-channel | session, wire-core, wire-core | everything above the socket |
| input-capture | session-matrix | `Edge` decisions on captured moves |
| input-inject | input-capture (KeyMap), session-matrix (de-normalization), input-capture (desktop bounds) | |
| input-capture | session-matrix | rectangle definitions |
| clipboard | wire-core | 64-byte chunk packets |
| clipboard | wire-core, wire-core, clipboard | stream layout, `DATA`, header/text format |
| app-shell | every `MWBCore` type, control-channel, input-capture, input-capture | wiring |
| end-to-end | all | |
### 2.3 Handshakes (`◀──▶`) — all open at planning time
@@ -111,56 +110,46 @@ Numbered so lanes can cite them. With serial lanes a handshake is simply
list still matters because it names the APIs the lead checks at
inspection.
1. **packet-codec ◀──▶ session**: the `Packet` API shape (value type
with typed union views, `Data` in/out). packet-codec proposes in its
1. **wire-core ◀──▶ session**: the `Packet` API shape (value type
with typed union views, `Data` in/out). wire-core proposes in its
README; session consumes as published. Closed when session lands.
2. **cipher-stream ◀──▶ control-channel**: streaming `write/read`
2. **wire-core ◀──▶ 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:)`
4. **session-matrix ◀──▶ input-capture**: `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
5. **input-capture ◀──▶ 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
6. **input-capture ◀──▶ input-inject**: `Screens.desktopBounds` and
`primaryBounds` in CG coordinates (top-left origin, points).
7. **clipboard-inband ◀──▶ clipboard-bulk**: the `"<len>*<name>"`
7. **clipboard ◀──▶ clipboard**: 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
8. **app-shell ◀──▶ everyone**: `Settings` is the one struct passed
down; lanes read fields, never the file.
## 3. Lane order
Lanes run **one at a time** (CLAUDE.md, the user's standing
instruction), so this section is an order, not a parallelism proof. The
order follows the consumption edges in §2.2: nothing is started before
everything it consumes is merged.
Lanes run **one at a time** (CLAUDE.md), so this is an order, not a
parallelism proof. Nothing starts before everything it consumes is merged.
| # | lane | consumes (must be merged first) |
| # | lane | consumes |
|---|---|---|
| 1 | packet-codec | bootstrap |
| 2 | cipher-stream | bootstrap |
| 3 | session | packet-codec, cipher-stream |
| 4 | matrix-edge | packet-codec |
| 5 | control-channel | session, cipher-stream, packet-codec |
| 6 | event-tap | matrix-edge |
| 7 | screens-cursor | matrix-edge |
| 8 | input-inject | event-tap (KeyMap), matrix-edge, screens-cursor |
| 9 | menubar-app | all of the above — the first build the user can test |
| 10 | clipboard-inband | packet-codec, menubar-app (Settings) |
| 11 | clipboard-bulk | cipher-stream, packet-codec, clipboard-inband |
| 12 | end-to-end polish | everything; driven by the user's testing |
`interop-vectors` is no longer a lane: there are no test suites. If a
Windows machine becomes available, the lead verifies protocol facts by
hand against a capture and flips `[transcribed]` marks in
`docs/protocol.md`.
| 1 | wire-core | bootstrap |
| 2 | session-matrix | wire-core |
| 3 | control-channel | session-matrix, wire-core |
| 4 | input-capture | session-matrix (Edge, coordinates) |
| 5 | input-inject | input-capture (KeyMap, Screens, injected tag), session-matrix |
| 6 | app-shell | all of the above |
| 7 | clipboard | wire-core, control-channel, app-shell (Settings) |
| 8 | extras | app-shell, session-matrix |
| 9 | polish | everything |
`TODO.md`, `docs/protocol.md` and `docs/perf/README.md` are
shared-by-nature: append in your own section only.