Bridge (device-to-device sync)
Bridge moves selected data between two of the user's devices, directly, with no server and no account. Module:
SyncEngine. Three layers:
SyncCoordinator what changed, how two versions merge, how a change is applied
BridgeSyncSession one exchange between two devices
BridgeSecureChannel encryption, authentication, ordering
BridgeTransport bytes between two devices (in memory for tests, TCP + Bonjour, or anything else)The capsule (a file) is the other way to move data: CAPSULE_FORMAT.md.
Pairing
One device shows a 6-digit code (BridgePairingOffer), the user types it on the other
(BridgePairing.initiate). Then, over the unprotected transport:
typing device (I) showing device (R)
1. version, nonceI, mI = pkI ⊕ pad(code, nonceI, "I") ──▶
R: pkI = mI ⊕ pad(code, nonceI, "I")
◀── 2. version, nonceR, mR = pkR ⊕ pad(code, nonceI ‖ nonceR, "R"), confR
I: pkR = mR ⊕ pad(code, nonceI ‖ nonceR, "R"); checks confR
3. confI ──▶ R checks confI
pkX ephemeral X25519 public keys (new for every pairing)
pad(…) HKDF-SHA256(code, salt = label ‖ nonces, info = role), 32 bytes; bit 255 is left unmasked
shared X25519(own private key, unmasked peer public key)
transcript SHA-256(label ‖ nonceI ‖ nonceR ‖ mI ‖ mR ‖ pkI ‖ pkR)
keys HKDF-SHA256(shared, salt = transcript), then HKDF again with the code mixed in
confX HMAC-SHA256(confirmation key, role ‖ transcript)Both sides then hold two ChaCha20-Poly1305 keys (one per direction). Any mismatch aborts and closes the link. Confirmations are compared in constant time. Keys are ephemeral: nothing about a pairing is stored, and each transfer pairs anew.
What this is, and what it is not
This is not a standard PAKE — not SPAKE2, CPace or OPAQUE, none of which can be built from what CryptoKit exposes (it offers X25519 key agreement but no general point arithmetic). It follows the idea of Encrypted Key Exchange (Bellovin–Merritt): the Diffie-Hellman public keys are hidden under the short secret, so a wrong guess of the code unmasks a value for which nobody knows a private key. It has no security proof and has not been reviewed by a cryptographer. Treat the statements below as the design intent.
Why the public keys are masked rather than simply confirmed with a MAC keyed by the code: with a plain "Diffie-Hellman, then HMAC over the code" confirmation, an attacker in the middle who lets one device send its confirmation can compute the code offline (10⁶ tries) and then use it, still valid, against the other device. Masking removes that offline computation: checking a guess requires a key agreement the attacker cannot do.
What it is designed to give:
- Passive eavesdropper: sees nonces, masked keys and confirmations. Testing a candidate code against the confirmations requires the X25519 shared secret of the two unmasked keys, which it cannot compute.
- Active attacker (impersonating either device, or in the middle), not knowing the code: it has to embed one guess of the code in the masked key it sends. A wrong guess makes the victim derive a different secret; the confirmation fails and reveals only that this one guess was wrong. One guess per pairing attempt.
- Single-attempt rule:
BridgePairingOffer.acceptworks once. Whatever the outcome, the code is spent and a second call throwscodeAlreadyUsed; the UI must generate a new code. Enforced in memory on the showing device for that offer object: the UI must not create new offers in a loop on its own. On the typing device a failure is reported to the user, who needs a new code from the other device.
Known weaknesses and limits:
- Partition leak, about one bit per masked key. A real X25519 public key is always a point of the curve, never
of its twist, and that is checkable. Unmasking with a wrong code gives a random value, which is on the curve only
about half of the time; so each masked key an attacker sees lets it discard about half of the candidate codes.
Hiding this needs an Elligator-style encoding, which CryptoKit does not provide and which is not implemented.
Consequence: an active attacker's single guess succeeds with probability up to about 2 in 10⁶ against one
device, 4 in 10⁶ against a pairing it sits in the middle of, instead of 1 in 10⁶, with a 6-digit code.
BridgePairingCode.generate(length:)accepts up to 12 digits to lower this. - The pad is a plain XOR, not an ideal cipher over the group; the usual EKE analyses assume the latter.
- No protection if the attacker can read the code (shoulder surfing, a screenshot) before the pairing completes.
- No protection against a compromised device; no post-quantum security (X25519).
- No long-term device identity: a paired device is not remembered, so every transfer needs a new code.
- Because the code is single-use, the partition leak never accumulates over several pairings.
Secure channel
BridgeSecureChannel (actor), one per paired link:
- ChaCha20-Poly1305, a separate key per direction.
- Frame:
sequence (u64, big-endian) ‖ ciphertext ‖ tag. The nonce is the sequence number; the associated data are a protocol label, the direction and the sequence number. - The receiver accepts only the next expected sequence number. A replayed, duplicated, dropped or reordered frame
fails (
sequenceViolation); a modified or truncated frame fails (authenticationFailed). Any failure closes the channel — there is no resynchronisation. - Messages up to 16 MiB. Concurrent
sendcalls go out in the order they were made.
Transports
BridgeTransport is three methods (send, receive, close) carrying whole frames. It is not trusted: it may be
read, modified, reordered or cut without compromising the data, only the availability.
-
InMemoryBridgeTransport.pair()— tests. -
NetworkBridgeTransport+BridgeNetworkListener+BridgeNetworkBrowser— TCP with a 4-byte length prefix, Bonjour service_orixbridge._tcp, peer-to-peer enabled, no TLS (encryption is done above). The app's Info.plist needsNSBonjourServiceswith that type and anNSLocalNetworkUsageDescription.Not verified on two real devices. The code compiles for macOS and iOS and one test runs a whole pairing and sync session over TCP on the loopback interface of one Mac. Bonjour advertising and browsing, the local-network permission prompt, peer-to-peer Wi-Fi and behaviour on a real network (loss, sleep, roaming) are untested.
Session
BridgeSyncSession.run() on both devices at once:
hello(protocol version, device identifier, device name).- Each sends the list of the stamps it holds (deletions included), in slices of 2 000.
- Each computes, with the merge rule, which of the peer's stamps win over its own: live ones are requested
(
request), deletions are kept to apply. - Each answers the other's request with the changes and their payloads (
changes, about 1 MiB per message), thendone. - Each applies what it received through
SyncCoordinator.apply.
Sending and receiving run concurrently, so two large lists cannot block each other. The exchange is symmetric and needs no cursor: comparing full stamp lists is exact even when changes were relayed through a third device. Cost: about 150 bytes per synchronised item per session.
A session that fails (tampering, disconnection) applies nothing: payloads are only applied after done.
A single payload above 12 MiB is skipped and logged (a canvas document that large does not sync in version 1).
Sync core
What is synchronised
Bookmarks, spaces, tab groups, notes, canvases, workflows — and settings only for the keys the app lists in
SyncConfiguration.syncedSettingKeys (none by default; keys under sync., memory., flow., history.,
session. are refused even if listed). Not synchronised: profiles, windows and tabs, history, downloads,
permissions, archives and their files, snapshots, agent runs, canvas attachment files, the memory index, secrets.
Change tracking
One record per (entity, id) in database.sync (SyncRecord): a Lamport version, the writing device, the
modification time, a deletion time (tombstone) and the SHA-256 of the entity's canonical JSON.
SyncCoordinator.detectLocalChanges() compares what is stored with the records and writes a record for every
creation, edit and deletion since the last call. No other module needs to report its writes. It runs at the start
of every export and every apply.
The module keeps one table of its own, sync_engine_payloads: for each record received from another device, the
exact payload received (so it is relayed byte for byte) and the hash of the entity as stored locally (which can
differ: see repairs below). Version in the setting sync.engine_schema_version.
Merge rule
For one key, stamps are totally ordered by
(version, modifiedAt, deviceID, isTombstone, payloadHash) compared left to rightand merging keeps the greatest (SyncMerge). Keeping a maximum is commutative, associative and idempotent: devices
that have seen the same changes hold the same stamps, whatever the order, grouping or repetition. Tests check this
on random histories of two and three devices, at the level of the rule and at the level of real databases.
- A device that has seen a change writes a higher version, so an edit made knowing of another edit wins.
- Edits made without knowledge of each other: the higher version wins, then the later
modifiedAt, then the greater device identifier. Clocks only break ties between equal versions; a wrong clock cannot override a causally later edit. - Deletions: a tombstone is a stamp like any other. It wins over older edits, loses to an edit with a higher version (the item comes back), and wins an exact tie on version, time and device.
Per entity:
| Entity | Resolution |
|---|---|
| note, workflow, tab group, listed setting | last writer wins on the whole item |
| canvas | whole-document last writer wins: two devices editing the same canvas at the same time do not get a card-by-card merge; one version replaces the other |
| space | last writer wins; applying a space's deletion deletes the space, its windows and tabs on the receiving device |
| bookmark | last writer wins per bookmark (title, URL, tags, parent, order), plus the tree rules below |
Bookmark tree rules, applied identically on every device:
- Missing parent: a bookmark whose folder does not exist on the receiving device (deleted, or of another profile) is placed at the top level.
- Cycle: if applying a move would close a loop (two devices each moved a folder into the other), the bookmark of the loop whose stamp is the smallest in the merge order is placed at the top level.
- Folder deletion: deleting a folder deletes what it contained on the deleting device (each with its own tombstone). A bookmark another device moved into, or edited inside, that folder without knowing of the deletion survives, at the top level.
These placements are repairs: they change how the bookmark is stored locally, not its record, so they are not re-broadcast as edits and cannot cause ping-pong.
Profiles are device-local. A bookmark or space keeps its profile on a device that has it; otherwise it goes to
SyncConfiguration.fallbackProfileID; with neither, the change is deferred (reported, not applied, requested
again at the next session). An entity never changes profile through sync.
Applying
apply(changes): detect local changes; keep, per key, the incoming change that wins over what is held; verify each
payload against its stamp's hash (mismatch → rejected); apply live changes in the order space, tab group, bookmark
(parents first), note, canvas, workflow, setting; then deletions in the reverse order. Each entity is written
through the public stores, then its record. Applying the same change again is a no-op.
Not atomic across the batch: an interruption leaves some changes applied. Since applying is idempotent and the next session compares full stamp lists, the remainder is applied then.
Tombstones and leaving sync
purgeTombstones()forgets deletions older thantombstoneRetention(180 days by default). A device that has not synchronised for longer than that can bring a deleted item back, because nothing remembers the deletion.removeLocalSyncState()— "remove this device from sync": deletes every sync record and kept payload on this device and gives it a new device identifier. The user's data stays on the device. Other devices are not contacted and keep what they have; nothing is deleted elsewhere (there is no server to delete from). With iCloud sync,CloudKitBridge.removeAllRemoteData()deletes the zone in the user's iCloud — that removes the cloud copy for all of the user's devices, not only this one.
iCloud adapter
CloudSyncAdapter (protocol), DisabledCloudSync (the default) and CloudKitBridge: one record per sync key in a
custom zone (OrixBridge) of the user's private CloudKit database, payloads in encrypted fields (CKAsset above
512 KiB), incremental fetch with a server change token stored in the setting sync.cloudkit.change_token. The sync
core does not depend on it.
Off by default and not verified. The app has no iCloud container entitlement, so this adapter has never
contacted CloudKit: it only compiles. Every call throws CloudSyncError.disabled unless the adapter is created
with isEnabled: true, which must not be done before the entitlement exists (creating a CKContainer without it
terminates the process). Untested, among other things: zone creation, record size limits, change-token handling,
account changes, rate limiting, behaviour when two devices push the same key.
Not verified
- Two real devices: never. Everything was tested in memory and over loopback TCP on one Mac.
- The pairing construction has had no external cryptographic review and has no proof; its known partition leak is described above.
- The CloudKit adapter (above).
- Large data sets: a session with 2 500 notes is covered; tens of thousands of items and multi-megabyte canvases are not measured.
- No UI exists for pairing, device discovery, progress or conflict reporting.
- Sync has no hook in the rest of the app yet: nothing calls
SyncCoordinator, and applying a remote change does not notify open windows (a live tab strip or bookmark view would have to reload from the database).