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 fromdocs/protocol.md§1.1, not recomputed. Typeis one byte on the wire. Stored asUInt8at offset 0;Framing.openzeroes bytes 1–3 exactly asProcessReceivedDataExdoes (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 the0x80rule. Type0is included: Windows throws there (DATA.cs:126-127), we decode a small.unknown(0)rather than fail a receive loop over a byte that is not a legal type anyway. Error(0xFE) andInvalid(0xFF) are big packets, because they carry the0x80bit. This is not a quirk we chose: the Windows receive loop reads 32 more bytes after rejecting a packet (SocketStuff.cs:578-600), and a receiver that does not will desynchronise. See protocol §10.1 note 1.- 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
CCCryptorCreatewithoptions = 0(CBC, no padding) andCCCryptorUpdateper chunk. Zero padding on Windows never emits bytes because every write is a multiple of 16; we do no padding. - PBKDF2 is
CCKeyDerivationPBKDFwithkCCPRFHmacAlgSHA512, 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<< 23overlap is reproduced withUInt32wrapping arithmetic in the C# order. - Salt and IV are fresh per direction; the sacrificial block is
inside the cipher types' contract:
CipherWriter.headeris the whole 48-byte preamble (salt, IV, then the encrypted random block), andCipherReadereats the peer's preamble out of the byte stream and discards the first 16 plaintext bytes (Common.cs:1528-1558,SocketStuff.cs:105, 119). - Randomness comes from
SystemRandomNumberGenerator, documented as cryptographically secure on Apple platforms — the salt, the IV and the sacrificial block all come from it, matchingRandomNumberGenerator.Fill(Encryption.cs:125). Generated keys use it too, via unbiasedrandomElement()rather than the Windows modulo reduction (Encryption.cs:222); nothing on the wire depends on how a key was chosen. - A wrong key is not detectable here (no MAC). The reader returns
garbage and framing rejects it, matching Windows (
InvalidKeyafter more than 10 bad packets).
Handshakes
Promised (topo.md handshakes 1 and 2, to session-matrix, control-channel, clipboard)
As shipped 2026-09-16. Later lanes code against this.
public let packageSize = 32 // Package.cs:17
public let packageSizeEx = 64 // Package.cs:18
public enum PackageType: RawRepresentable, Sendable, Hashable {
case hi, hello, byeBye, heartbeat, awake, hideMouse, heartbeatEx, heartbeatExL2,
heartbeatExL3, clipboard, clipboardDragDrop, clipboardDragDropEnd, explorerDragDrop,
clipboardCapture, captureScreenCommand, clipboardDragDropOperation, clipboardDataEnd,
machineSwitched, clipboardAsk, clipboardPush, nextMachine, keyboard, mouse,
clipboardText, clipboardImage, handshake, handshakeAck, matrix, error, invalid
case unknown(UInt8)
public init(rawValue: UInt8) // never fails
public var rawValue: UInt8
public var isBig: Bool // true for .error and .invalid too — see below
public var isMatrix: Bool
public var packetSize: Int // 32 or 64
public static let matrixBit: UInt8 // 0x80
public static let matrixSwapFlag: UInt8 // 2
public static let matrixTwoRowFlag: UInt8 // 4
}
public enum MachineID { public static let none: UInt32; public static let all: UInt32 }
public struct MouseData: Sendable, Hashable { public var x, y, wheelDelta, flags: Int32 }
public struct KeyboardData: Sendable, Hashable {
public var dateTime: Int64; public var virtualKey, flags: Int32
}
public enum PacketError: Error { case machineNameNotASCII, machineNameTooLong }
public struct Packet: Sendable, Hashable {
public init(type: PackageType)
public init?(bytes: Data) // 32 or 64 bytes, no framing check
public var bytes: Data // 32 or 64
public var type: PackageType
public var id: Int32
public var src: UInt32
public var des: UInt32
public var mouse: MouseData // bytes 16..31
public var keyboard: KeyboardData // dateTime 16, vk 24, flags 28
public var nonce: (UInt32, UInt32, UInt32, UInt32) // bytes 16..31
public var postAction: UInt32 // bytes 16..19
public var payload48: Data // bytes 16..63, zero-filled when short
public var machineName: String? { get } // nil on small packets
public mutating func setMachineName(_ name: String) throws
public static let clipboardChunkSize = 48
}
public enum Framing {
public static func seal(_ packet: 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 let minimumLength = 16
public static func isValid(_ key: String) -> Bool
public static func normalize(_ typed: String) -> String // discards whitespace
public static func random() -> String
public static func displayText(_ key: String) -> String
}
public enum CipherError: Error {
case keyDerivationFailed, cryptorCreationFailed(Int32), cryptorUpdateFailed(Int32)
}
public final class CipherWriter {
public init(securityKey: String) throws
public let header: Data // 48 bytes: salt | IV | encrypted sacrificial block
public func write(_ plaintext: Data) throws -> Data
}
public final class CipherReader {
public init(securityKey: String)
public func read(_ ciphertext: Data) throws -> Data // eats the peer preamble itself
}
Three deviations from the shape proposed at planning time, all deliberate:
machineNameis a read-only property plussetMachineName(_:) throws. A setter cannot reject a non-ASCII name, and silently encoding one as?the way Windows does would produce a machine nobody can resolve.CipherWriter/CipherReaderarefinal class, notstruct. They own CBC chaining state in aCCCryptorRef; a struct copy would fork one stream into two that each think they own the chain. They are notSendable: one connection owns one of each, on one queue.CipherWriter.headeris a storedlet, not amutating func, and it includes the encrypted sacrificial block, so it is 48 bytes. Write it verbatim before the first packet; there is nothing else to remember.
Two rules the consuming lanes must honour:
Framing.openreturning.invalidstill means 64 bytes on the wire (protocol §10.1 note 1). Receive loop: read 32,Framing.open, and ifpacket.type.isBig, read 32 more andFraming.openthe concatenated 64 — the checksum covers bytes 2..31 either way, so opening twice is identical to what Windows does.- Nothing may be acted on before
Framing.openreturns a non-.invalidpacket (CLAUDE.md invariant 2). There is no MAC: framing under the key-derived magic number is the only authentication in this protocol.
Consumed
- Nothing. Foundation, CommonCrypto, CryptoKit only.
Status / TODO
Sources/MWBCore/Packet.swift:PackageType(every value §1.2, cited),isBig,Packetwith union views, machine name rules.Sources/MWBCore/Framing.swift:seal/openper §1.3, each constant cited toSocketStuff.cs.Sources/MWBCore/MagicHash.swift:magicNumber(for:)§2.1 cited toEncryption.cs:173-200;SecurityKeyrules §2.4 (Encryption.cs:207-242,:65-79).Sources/MWBCore/CipherStream.swift: PBKDF2,CipherWriter,CipherReader(header, sacrificial block, streaming CBC), cited toEncryption.csandCommon.cs:1528-1558; the CommonCrypto wrapper lives in this one file.docs/protocol.md: add anything learned while porting, cited.
Work log
2026-09-16 — dev (Opus)
Ported all four files; tools/gates.sh green. What each file is
responsible for, in one sentence apiece:
Packet.swift(404 lines) — theDATAbuffer and its overlapping field views. Storage is always 64 bytes, asDATAalways is, andbytestruncates to 32 for a small packet exactly asDATA.Bytesdoes (DATA.cs:105-113); that removed all resize logic from the type setter and made the union views trivial offset reads.PackageTypeis aRawRepresentableenum with a non-failableinit(rawValue:)(Swift accepts one where a failable initialiser is required), so an unrecognised byte round-trips as.unknown(raw)and still sizes correctly.Framing.swift(72 lines) — bytes 1..3 only: the 8-bit sum of bytes 2..31 and the magic's top 16 bits.MagicHash.swift(113 lines) — everything derived from the key string: its magic number, and its validity/generation/display rules. Two responsibilities by the letter of the one-sentence test, one by its spirit: both are "what the key string means", neither is 30 lines, and splitting would give the next reader two files to find.CipherStream.swift(212 lines) — the per-direction CBC stream and the only CommonCrypto in the project.CCCryptorUpdatealready buffers a partial block internally, so the only buffering written by hand is the reader's 32 cleartext preamble bytes.
Key decisions and deviations:
CipherWriter/CipherReaderare classes,machineNameis set through a throwing method, andheaderis a stored property. Reasons and the exact signatures are in Handshakes above; later lanes code against that block, not against the planning sketch.- The magic hash needs wrapping arithmetic. The C# expression
overflows
intfor large digest bytes and is reinterpreted by a(uint)cast;&+reproduces it, plain+would trap in Swift. Written up as protocol §10.1 note 3. Error/Invalidare big packets. Found while portingIsBigPackage; it changes how control-channel must frame its reads, so it is called out in Handshakes and protocol §10.1 note 1.- NULs are trimmed from a decoded machine name, which
String.Trimdoes not do. Windows pads with spaces, so this cannot change what a real packet decodes to; it only stops a zero-filled field reading as 32 NULs. - Generated keys use unbiased random selection instead of the
Windows
% set.Length. Local-only choice, noted in Assumptions.
Verified by hand (no test suite, per CLAUDE.md — the user tests the
app). Each check was run from a throwaway swiftc build of MWBCore
in the scratchpad, against an independent implementation, never
against our own encoder:
- Magic number for
abcdefghijklmnop=334517251, matching a Python SHA-512 chain of the same 50 001 rounds. - PBKDF2-HMAC-SHA512 (100 000 rounds, salt 16×0x01) matching Python's
hashlib.pbkdf2_hmac. CipherReaderfed a 112-byte stream built byopenssl enc -aes-256-cbc -nopadfrom that derived key — delivered in 13-byte slices to exercise the preamble and partial-block buffering — returns exactly the 64 plaintext packet bytes, andFraming.openthen reads it back ashandshake/MACBOOK.- Packet offsets, the 32/64 size rule, seal→open round trip, and rejection of a flipped payload byte, a wrong magic and a short buffer.
No macOS permission was requested, no event was posted, no pasteboard was touched.
QA log
2026-09-16 — QA (Sonnet)
Ran tools/guard.sh -t 600 -- tools/gates.sh: all three gates green
(swift-format lint --strict, MWBCore layering, swift build -Xswiftc -warnings-as-errors).
Checked every Status/TODO tick against the code and, line by line,
against the Windows source at
/Users/guoliangchen/repo/PowerToys/src/modules/MouseWithoutBorders/App/:
PackageTyperaw values — every one of the 26 named types plusMatrix/Error/Invalidcompared 1:1 againstPackageType.cs:15-57. Exact match, includingMatrixSwapFlag/MatrixTwoRowFlagas static constants rather than enum cases (they are OR'd flags, not standalone wire types).isBig's explicit 12-type list (Packet.swift:148-150) matchesDATA.cs:130(IsBigPackage) name-for-name and order-for-order; the bitwise fallback correctly makes.error(0xFE) and.invalid(0xFF) big too, reproducing the Windows receive-loop quirk already recorded in protocol.md §10.1 note 1 — verified by hand againstSocketStuff.cs:578-600.Packetbyte offsets —Type(0),Id(4),Src(8),Des(12),DateTime/Md(16),Kd(24),Machine1..4(16,20,24,28),PostAction(16),machineNameP1..4(32,40,48,56) — checked againstDATA.cs:27-73field offsets computed fromsizeof(PackageType) + n*sizeof(uint)/sizeof(long).MOUSEDATA/KEYBDDATAfield order checked againstMOUSEDATA.cs:18-26,KEYBDDATA.cs:18-25. All correct.- Checksum range:
Framing.checksumsums bytes 2..<32 only, matchingSocketStuff.cs:509-513(TcpSendData) and:537-543(ProcessReceivedDataEx), both bounded byPackage.PACKAGE_SIZE(32) even though a big packet is 64 bytes on the wire. - Magic hash: shift amounts and term order (
h[0]<<23, h[1]<<16, h[last]<<8, h[2]) matchEncryption.cs:199exactly, including the<<23/<<24overlap. Independently recomputed the documented example (keyabcdefghijklmnop) with a fresh Python SHA-512 chain of 50 001 rounds: got decimal334517251, matching the doc and the Swift&+wrapping-arithmetic reproduction. Found the hex gloss next to that decimal wrong —docs/protocol.md:480said0x13EC_4F03;334517251is actually0x13F0_5403. Trivial doc typo, fixed directly (commit56448cc,qa:prefix); the decimal value and the Swift code were never wrong. - PBKDF2: the
CCKeyDerivationPBKDFcall useskCCPRFHmacAlgSHA512, 100 000 rounds, 32-byte output, UTF-8 password — matchesEncryption.cs:107-115andRfc2898DeriveBytes.Pbkdf2(string, ...)'s documented UTF-8 handling. Independently recomputed the documented vector (keyabcdefghijklmnop, salt 16×0x01) with Python'shashlib.pbkdf2_hmac('sha512', ...): got6c30ca8b15c27f6e…14ae2a4da14728e1, matching the doc exactly. - 48-byte preamble:
CipherWriter.headeris salt(16) + IV(16) + encrypted sacrificial block(16) = 48 bytes, matchingEncryption.cs:124-129(GetEncryptedStream) plusCommon.cs:1528-1558/SocketStuff.cs:105,119(SendOrReceiveARandomDataBlockPerInitialIV, called on the encrypted stream so the sacrificial block is written through the cipher, not appended in the clear).CipherReaderconsumes the same 32 clear bytes then discards the first 16 plaintext bytes the cryptor emits, matching the Windows reader path (SendOrReceiveARandomDataBlockPerInitialIV(decryptedStream, false)reads through the already-wrappedCryptoStream). - Big/small rule including
Error/Invalid: covered above underisBig.
Read every changed file top to bottom for readability against CLAUDE.md:
- File sizes:
Packet.swift404,CipherStream.swift212,MagicHash.swift113,Framing.swift72 lines — all well inside the 300–600 target. No function exceeds ~35 lines. - No
!force-unwrap,try!,fatalErrororpreconditionanywhere in the four files (grep -n '!' ... | grep -v '//' | grep -v '!='turns up only!input.isEmpty,!valid,!$0.isWhitespace— boolean negation, not force-unwrap). - No
print/Logger/NSLogcall anywhere in the diff — nothing to audit for key-material leakage because nothing logs at all. CipherError/PacketErrorcases carry only status ints or nothing; none carry key, salt, IV or plaintext, as the doc comment onCipherErrorpromises.- No dead code, no TODO/FIXME left in the shipped files.
- Every public symbol has a one-line doc comment; comments cite
Windows
file:linethroughout, none cite nothing. - Confirmed nothing in these four files acts on a packet before
Framing.openreturns it — they only encode/decode bytes; there is no packet dispatch here for a "before decrypt" check to apply to beyond that. TheCipherReaderdoc comment correctly states the invariant for its callers.
One note, not a finding: SecurityKey.isValid/random measure length
with Swift's String.count (grapheme clusters) where Windows measures
string.Length (UTF-16 code units) (Encryption.cs:237). For the
ASCII character sets the generator and the UI actually produce this
never differs; flagging only so a later lane doesn't assume the two
are interchangeable for arbitrary input.
No macOS permission was requested, no CGEvent posted, no pasteboard
was touched, matching CLAUDE.md invariant 5 — this lane has no such
surface to begin with.
Findings: none outstanding (one trivial doc typo found and fixed directly, see above).
Verdict: PASS
Review
- 2026-09-16 (lead): inspected per
docs/loop.md§5. Gates green run by me; diff touches only the lane's files plus TODO §1, protocol.md §10.1 and this README. Read all four Swift files: offsets and enum values match protocol §1, checksum loop is bytes 2..31, magic uses wrapping adds with the<< 23overlap, PBKDF2 parameters and the 48-byte preamble match §2, no logging, no force-unwraps, files 72–404 lines. QA independently recomputed the magic and PBKDF2 vectors. Verdict: merge. Carry into the next brief: (1)Framing.openon an.invalidfirst half still means 64 bytes on the wire — the control-channel receive loop must read the second half; (2)CipherWriter/Readerare non-Sendable classes, so one connection owns them on one queue; (3)Packet.setMachineNamethrows on non-ASCII — the app must validate the hostname at startup (D7).