18 KiB
polish
Goal
Lane 10: fixes driven by the user's testing (CP1–CP3). Each item below is one finding, with the evidence, the decision and the file that owns the fix. Items are worked in order by one Dev → QA → lead round per batch; the lead re-bundles after each batch.
Findings and decisions
P1 — PowerToys stable uses the pre-June-2026 cipher scheme (CP1, 2026-09-16)
Evidence. The user's PC Lu-Corsair (10.233.33.52) accepts TCP on
15101 but every packet decrypts to garbage under our scheme. An
independent Python probe in the lead's scratchpad reproduced the whole
handshake against that PC with the legacy scheme and got: ten
Handshake packets named Lu-Corsair, a HandshakeAck whose nonce
was the complement of ours, then Heartbeat_ex (51) — the PC trusted
the probe. So Framing, MagicHash and Session's handshake are
proven against real Windows; only the stream cipher differs.
Why. PowerToys commit a9e1f0f20e (2026-06-22, PR #48742) replaced
a fixed salt/IV with the per-connection cleartext header
(docs/protocol.md §2.3). It is only in the v0.101.* build tags;
stable releases up to v0.100.2 (2026-06-26) still use the old code.
Users on stable PowerToys are the common case.
Legacy scheme (git show a9e1f0f20e^:src/modules/MouseWithoutBorders/App/Core/Encryption.cs):
InitialIV = ulong.MaxValue.ToString()="18446744073709551615".- Key =
PBKDF2-HMAC-SHA512(password: MyKey (UTF-8), salt: UTF-16LE("18446744073709551615") (40 bytes), iterations: 50 000, length: 32)(legacyGenLegalKey). - IV = ASCII of
InitialIVtruncated to 16 bytes ="1844674407370955"(legacyGenLegalIV). - No cleartext header. The stream is AES-256-CBC(key, IV) of
[16 random sacrificial bytes][packets…]— the sacrificial block (SendOrReceiveARandomDataBlockPerInitialIV) exists precisely because the IV was fixed. Same for the clipboard bulk connection.
Decision. A new Mac-only setting MacCipherScheme with values
"legacy" (default — matches current stable PowerToys) and "modern"
(PowerToys 0.101+ / the header scheme), stored in the same
settings.json (unknown to Windows, preserved). Applied to every
control and bulk connection. Shown in the Security pane as
"Encryption compatibility: PowerToys 0.100 and earlier / 0.101 and
later". Auto-negotiation is not attempted: both versions of Windows
write first and never adapt, and two auto-detecting Macs would
deadlock waiting for each other. Diagnostic: when the first packet
from a peer fails framing under the configured scheme, the reader
tries the other scheme on the same bytes; if that passes, the
connection reports status .invalidKey with a distinct reason
.cipherSchemeMismatch that the menu shows as "wrong encryption
setting (peer uses PowerToys 0.100 / 0.101 scheme)". This costs one
extra AES setup per failed connection and nothing on success.
Files. Sources/MWBCore/CipherStream.swift (a CipherScheme enum;
CipherWriter/CipherReader take it; legacy constants cited),
Sources/MWBCore/Settings.swift (accessor + default),
Sources/MWBNet/ChannelConfig.swift + PeerConnection.swift +
BulkConnection.swift (pass the scheme; the mismatch diagnostic),
Sources/MWBCore/Session.swift (InvalidKeyReason.cipherSchemeMismatch),
Sources/mwb/Engine.swift (config mapping), Sources/MWBMac/SettingsWindow/SecurityPane.swift
(the picker), Sources/MWBMac/StatusItem.swift (the wording),
docs/protocol.md (§2.5 "Legacy stream, PowerToys ≤ 0.100" and §10.9
"verified against a real Windows peer"), README.md (D3 note, §Status).
P2 — event tap not installed at first launch (CP1)
mwb.log: event tap not installed (creationFailed). Expected: the
user had not granted Accessibility yet; the menu says so. No code
change unless the user reports the menu text was unclear. Kept here so
the CP1 record is complete.
Handshakes
Requests to other lanes, raised by P1 and deliberately not made here.
- app-ui / app-engine — the notification for a scheme mismatch.
UIBridge.updateNotificationsfiresnotifier.invalidKey(for:)onstatus == .invalidKeyonly (Sources/mwb/UIBridge.swift:198-200), so a.cipherSchemeMismatchrow shows in the menu but posts no notification. Oneelse ifin that method would fix it;UIBridge.swiftis not in this item's file list, so it is a request rather than an edit.
Status / TODO
- P1: legacy scheme + setting + diagnostic, files as listed;
docs/protocol.md§2.5 and §10.9. - P2: none.
Work log
2026-09-16 — Dev (P1). Implemented as decided above.
Offline first. Before any app code, the legacy constants were checked
against an independent implementation, in the scratchpad: our
CipherWriter(scheme: .legacy) stream decrypts under Python
cryptography's AES-CBC with
hashlib.pbkdf2_hmac('sha512', key, '18446744073709551615'.encode('utf-16-le'), 50000, 32)
and IV b"1844674407370955", and our CipherReader(scheme: .legacy)
recovers a stream Python encrypted the same way. Both directions matched
byte for byte, and the derived key and IV matched Python's before either
stream was built. No socket was opened and the app was not launched.
What changed.
Sources/MWBCore/CipherStream.swift: aCipherSchemeenum (.legacydefault,.modern) withpreambleSizeandother;LegacyCipherConstantscarrying the fixed salt (UTF-16LE of"18446744073709551615", 40 bytes,Encryption.cs:126+Common.cs:407-410), 50 000 iterations (:127) and the ASCII IV (GenLegalIV,:140-154), all cited to the pre-a9e1f0f20efile;deriveStreamKeytakes the iteration count; aStreamMaterialvalue computes key/IV/cleartext-header per scheme for each side.CipherWriter.headeris now 16 bytes under.legacy(the encrypted sacrificial block alone) and 48 under.modern;CipherReaderconsumes a cleartext header only when the scheme has one.Sources/MWBCore/Settings.swift:MacCipherSchemein the defaults and amacCipherScheme: CipherSchemeaccessor, default.legacy.Sources/MWBCore/Session.swift:InvalidKeyReason.cipherSchemeMismatchand aSocketStatus.cipherSchemeMismatchcase. The status case has raw value 100, outside the Windows 0–9 range, so the Windows numbering the menu colours depend on is untouched; nothing serialises this enum.Sources/MWBNet/ChannelConfig.swift,BulkChannel.swift: both configs carry the scheme; a change to it triggersneedsFullReopen, like a key or port change.Sources/MWBNet/PeerConnection.swift: writer, reader and the preamble read all take the scheme (cipherScheme.preambleSize, replacing the hard-coded 48). The diagnostic keeps the peer's raw opening bytes and the plaintext they yielded until one packet frames; if the first packet fails framing under our scheme and the same raw bytes frame under the other, the connection closes.invalidKey(.cipherSchemeMismatch)and reports the matching status. Nothing is fed to theSessionon that path (invariant 2).Sources/MWBNet/BulkConnection.swift: takes the scheme. No diagnostic there — a bulk transfer only begins with a peer whose control connection already framed under the configured scheme (BulkSink.authorise), so a mismatch has already been reported.Sources/MWBMac/StatusItem.swift: the new status is painted the invalid-key brown (same kind of failure) with its own words, "wrong encryption compatibility setting".Sources/MWBMac/SettingsWindow/SecurityPane.swift: an "Encryption compatibility" radio group, "PowerToys 0.100 and earlier" / "PowerToys 0.101 and later", bound straight throughSettingsViewModel.binding. Not a draft like the key and port: one click is a whole change.Sources/mwb/EngineActions.swiftandSources/mwb/ClipboardBridge.swiftmapsettings.macCipherSchemeintoChannelConfig/BulkConfig. The brief saidEngine.swift; those two files are wherechannelConfig()andbulkConfig()actually live (both areEngineextensions).docs/protocol.md§2.5 and §10.9,README.mdD3 + §Status + the architecture line forCipherStream.swift,TODO.md§10.
Deviations and decisions worth flagging to the lead.
- Two files outside the stated list were touched, each additively and by
necessity:
Sources/MWBNet/BulkChannel.swift(thecipherSchemefield onBulkConfig—BulkConnectioncannot be handed a scheme without it) andSources/mwb/ClipboardBridge.swift(wherebulkConfig()is built). - The diagnostic needs up to 48 + 32 raw bytes, not one packet's worth.
Configured
.legacyagainst a.modernpeer, our reader treats the peer's first 16 bytes as the sacrificial block, so the first 32 bytes of plaintext appear after only 48 raw bytes — too few to re-run the modern reader, which wants 32 header bytes before it decrypts anything. The probe therefore waits fordiagnosticBytesbefore replaying. While it waits, the garbage keeps spending the session's untrusted budget exactly as it would without the diagnostic, and Windows sends ten handshakes at once, so the bytes are always there. - The notification gap in Handshakes 1 above.
QA log
2026-09-16 — QA (P1)
Verified git diff 32a0c72..HEAD against CLAUDE.md, docs/protocol.md
§2 (incl. §2.5) and §10.9, and the Work log above. Build only —
tools/guard.sh -m 8 -t 600 -- tools/gates.sh (all three gates: swift-format lint --strict, MWBCore layering, swift build -Xswiftc -warnings-as-errors) — green, no app launch, no sockets opened, no tests
(none exist in this repo; README.md says so by design). No
force-unwrap/try!/fatalError/precondition introduced, no log/print
statements anywhere in the diff.
- Legacy constants, against
git -C /Users/guoliangchen/repo/PowerToys show a9e1f0f20e^:src/modules/MouseWithoutBorders/App/Core/Encryption.csand the pairedCommon.cs:InitialIV = "18446744073709551615"(Encryption.cs:41);GenLegalKeysalts withCommon.GetBytesU(InitialIV)=ASCIIEncoding.Unicode.GetBytes= UTF-16LE (Common.cs:407-410), 50 000 iterations,HashAlgorithmName.SHA512, 32 bytes (Encryption.cs:117-138);GenLegalIVtakesInitialIVas ASCII, truncated tosymAl.IV.Length(16) (Encryption.cs:140-154,Common.cs:397-400).LegacyCipherConstantsinSources/MWBCore/CipherStream.swift:70-84matches all four facts exactly:saltbuilds UTF-16LE by hand (low byte, high byte per UTF-16 code unit, correct for this all-ASCII string),iterations = 50_000,iv = Array(initialIV.utf8.prefix(16))="1844674407370955". No header, sacrificial block first:CipherWriter.headeriscleartextHeader (empty under .legacy) + sacrificial, confirmed atCipherStream.swift:243-259. Modern path unchanged:CipherConstants(saltSize/blockSize16,iterations100_000,derivedKeyLength32,CipherStream.swift:58-67) are untouched by the diff, and both production call sites (PeerConnection.swift:107-108,BulkConnection.swift:91-92) passscheme:explicitly fromconfig.cipherScheme, so no caller falls through to the new= .legacydefault parameter. MacCipherSchemesetting (Settings.swift:163, 174-184): defaults to.legacyviaSettings.defaultProperties["MacCipherScheme"]and the?? .legacyfallback in the getter; round-trips through the same boxed-JSONValue mechanism every other string setting uses. ReachesChannelConfig.cipherScheme(EngineActions.swift:262) andBulkConfig.cipherScheme(ClipboardBridge.swift:408), both sourced fromsettings.macCipherScheme. "Preserved for Windows" checks out as: the genericproperties: [String: JSONValue]store round-trips every key it doesn't interpret, soMacCipherSchemefree-rides the same mechanism as every Windows-owned property this port doesn't implement — confirmed by reading, not by a round-trip test (none exist).PeerConnectionpreamble sizes:cipherScheme.preambleSizeused atreadPreamble()(PeerConnection.swift:189), computed ascleartextHeaderSize + blockSize(CipherStream.swift:29-56) — 16 for.legacy(0 + 16), 48 for.modern(32 + 16). Confirmed by reading, not by opening a socket.- Mismatch diagnostic (
PeerConnection.swift:234-294): traced both directions by hand — configured.legacyvs. an actual.modernpeer, and the reverse.SchemeProbe.rawaccumulates from the very firstconsume()call (the preamble chunk included, sincereadPreamble()itself callsconsume(bytes)), so by the timediagnosticBytes(48 + 32 = 80) raw bytes have arrived, replaying them from byte 0 under the other scheme'sCipherReaderlines up correctly with that scheme's own preamble-then-packet framing — matches Work log deviation #2's explanation. The diagnostic only evaluates the first post-preamble packet (self.probe = nilon every exit path fromnoteForDiagnostic, so it never re-arms). Wrong-key case traced: a bad key produces framing-failing garbage under both the configured and the other scheme (AES output is uncorrelated with the plaintext for a wrong key, so framing fails independently under each), soframesUnderOtherSchemereturnsfalseandconsume()falls through to the ordinarysession.feed, which is what eventually produces a plain.invalidKeyonce the session's own 10-non-handshake-packet budget (docs/protocol.md§3.2 guard 5) is spent — well after the diagnostic's ~2-3 packets, so there is no race between the two.BulkConnectiontakes no diagnostic, correctly:BulkSink.authorisegates a transfer on the control connection already being trusted. SocketStatus.cipherSchemeMismatch = 100: not a wire type anywhere — grepped everySocketStatususe inSources/; nothing serialises it toData/UInt8/a socket write.report(_:)(PeerConnection.swift:315) only updates the localSessionand drains local queues. EveryswitchoverSocketStatus(StatusItem.swiftcolour and wording) is exhaustive with nodefault, compiles clean under-warnings-as-errors, and both new cases have sensible values (brown, "wrong encryption compatibility setting") with a comment explaining why it shares the invalid-key colour.UIBridge.bestStatuses/rankusesdefault: return 0, so the new case doesn't break that switch either. The one gap —updateNotificationsdoesn't fire a notification for.cipherSchemeMismatch(UIBridge.swift:190-200) — is exactly the gap the Work log's Handshakes §1 already discloses; not a silent omission.- Security-pane picker:
model.binding(\.macCipherScheme)(SecurityPane.swift:63) goes throughSettingsViewModel.binding→commit→store.update→publishToEngine()(SettingsViewModel.swift:67-83), i.e.SettingsStore.update, matching the "not a draft, commits as it changes" pattern documented inSettingsViewModel.swift:8-12. The control channel path reopens fully:ChannelConfig.needsFullReopennow comparescipherScheme(ChannelConfig.swift:85-87), andControlChannel.reconfigurecallsreopen()wheneverneedsFullReopenis true (ControlChannel.swift:126-134). Minor finding, not blocking:BulkChannel.reconfigure'sdisruptiveflag (BulkChannel.swift:159-166) does not includecipherScheme, unlikeChannelConfig.needsFullReopen. Traced through: this is not a wire bug —config = newruns unconditionally before thedisruptivecheck, and every newBulkConnectionis built fromself.configat accept/dial time (BulkChannel.swift:271-276), so a scheme toggle takes effect on the next transfer regardless. Unlike the control channel'sPeerConnections,BulkConnections are one-shot per transfer, not long-lived sessions, so there is no persistent connection left running on the stale scheme in steady state — only a transfer already in flight at the moment of the toggle, which finishes under the scheme it started with rather than being cancelled. That's arguably the better behaviour (a background settings click doesn't kill an active file transfer), but the asymmetry with the control channel's explicitcipherSchemecomparison has no comment explaining it was a deliberate choice rather than an oversight. Worth a one-line comment atBulkChannel.swift:161-163for the next reader; not worth a rework. - Readability / CLAUDE.md: all touched files stay within the 300-600
line guidance except
Settings.swift(666),BulkConnection.swift(550→unchanged range) andClipboardBridge.swift(560) — all three were already over 600 before this diff (652/546/559 at32a0c72) and this diff adds only a handful of lines to each; not a new violation to raise here. New functions (StreamMaterial.forWriter/forReader,noteForDiagnostic,framingFails,framesUnderOtherScheme,startStream(consuming:)) are all well under the 50-line target, doc comments are present and say why, and every citation checked against PowerToys resolves to real, matching lines. - No key material logged: no
Log.*/printcall touchessecurityKey, derived key bytes, salt, IV, or plaintext anywhere in the diff;CipherErrorcases carry only status codes, never key or plaintext bytes (unchanged from before this diff).
Not verified (out of scope per the task): no test suite exists in this repo to run; no socket was opened and the app was not launched, so the legacy scheme's correctness rests on the Dev's offline Python cross-check (Work log) and this diff read, not on a fresh independent run.
Verdict: PASS
Review
- 2026-09-16 (lead), P1: inspected per
docs/loop.md§5. Gates green. Decisive check: a probe compiled from the app's ownCipherStream,Framing,PacketandMagicHashsources completed the handshake withLu-Corsairunder the legacy scheme — ten handshakes acked, our ack nonce matched,Heartbeat_exfollowed. The two files touched beyond the list (BulkChannel.swift,ClipboardBridge.swift) are the config plumbing and accepted. QA PASS; itsreconfigureasymmetry note and the Dev'sUIBridgenotification request go to the next batch. Verdict: merge. Bundle rebuilt for the user.