SPB Git

Repository Public License

BRIDGE.md 14.5 KB 236 lines markdown

1# Bridge (device-to-device sync)23Bridge moves selected data between two of the user's devices, directly, with no server and no account. Module:4`SyncEngine`. Three layers:56```7SyncCoordinator        what changed, how two versions merge, how a change is applied8BridgeSyncSession      one exchange between two devices9BridgeSecureChannel    encryption, authentication, ordering10BridgeTransport        bytes between two devices (in memory for tests, TCP + Bonjour, or anything else)11```1213The capsule (a file) is the other way to move data: [CAPSULE_FORMAT.md](CAPSULE_FORMAT.md).1415## Pairing1617One device shows a 6-digit code (`BridgePairingOffer`), the user types it on the other18(`BridgePairing.initiate`). Then, over the unprotected transport:1920```21typing device (I)                                      showing device (R)22  1. version, nonceI, mI = pkI ⊕ pad(code, nonceI, "I")        ──▶23                                   R: pkI = mI ⊕ pad(code, nonceI, "I")24                              ◀──  2. version, nonceR, mR = pkR ⊕ pad(code, nonceI ‖ nonceR, "R"), confR25  I: pkR = mR ⊕ pad(code, nonceI ‖ nonceR, "R"); checks confR26  3. confI                                                      ──▶   R checks confI2728  pkX        ephemeral X25519 public keys (new for every pairing)29  pad(…)     HKDF-SHA256(code, salt = label ‖ nonces, info = role), 32 bytes; bit 255 is left unmasked30  shared     X25519(own private key, unmasked peer public key)31  transcript SHA-256(label ‖ nonceI ‖ nonceR ‖ mI ‖ mR ‖ pkI ‖ pkR)32  keys       HKDF-SHA256(shared, salt = transcript), then HKDF again with the code mixed in33  confX      HMAC-SHA256(confirmation key, role ‖ transcript)34```3536Both sides then hold two ChaCha20-Poly1305 keys (one per direction). Any mismatch aborts and closes the link.37Confirmations are compared in constant time. Keys are ephemeral: nothing about a pairing is stored, and each38transfer pairs anew.3940### What this is, and what it is not4142This is **not a standard PAKE** — not SPAKE2, CPace or OPAQUE, none of which can be built from what CryptoKit43exposes (it offers X25519 key agreement but no general point arithmetic). It follows the idea of Encrypted Key44Exchange (Bellovin–Merritt): the Diffie-Hellman public keys are hidden under the short secret, so a wrong guess of45the code unmasks a value for which nobody knows a private key. **It has no security proof and has not been46reviewed by a cryptographer.** Treat the statements below as the design intent.4748Why the public keys are masked rather than simply confirmed with a MAC keyed by the code: with a plain49"Diffie-Hellman, then HMAC over the code" confirmation, an attacker in the middle who lets one device send its50confirmation can compute the code offline (10⁶ tries) and then use it, still valid, against the other device.51Masking removes that offline computation: checking a guess requires a key agreement the attacker cannot do.5253What it is designed to give:5455- **Passive eavesdropper**: sees nonces, masked keys and confirmations. Testing a candidate code against the56  confirmations requires the X25519 shared secret of the two unmasked keys, which it cannot compute.57- **Active attacker (impersonating either device, or in the middle), not knowing the code**: it has to embed one58  guess of the code in the masked key it sends. A wrong guess makes the victim derive a different secret; the59  confirmation fails and reveals only that this one guess was wrong. One guess per pairing attempt.60- **Single-attempt rule**: `BridgePairingOffer.accept` works once. Whatever the outcome, the code is spent and a61  second call throws `codeAlreadyUsed`; the UI must generate a new code. Enforced in memory on the showing device62  for that offer object: the UI must not create new offers in a loop on its own. On the typing device a failure is63  reported to the user, who needs a new code from the other device.6465Known weaknesses and limits:6667- **Partition leak, about one bit per masked key.** A real X25519 public key is always a point of the curve, never68  of its twist, and that is checkable. Unmasking with a wrong code gives a random value, which is on the curve only69  about half of the time; so each masked key an attacker sees lets it discard about half of the candidate codes.70  Hiding this needs an Elligator-style encoding, which CryptoKit does not provide and which is not implemented.71  Consequence: an active attacker's single guess succeeds with probability up to about **2 in 10⁶ against one72  device, 4 in 10⁶ against a pairing it sits in the middle of**, instead of 1 in 10⁶, with a 6-digit code.73  `BridgePairingCode.generate(length:)` accepts up to 12 digits to lower this.74- The pad is a plain XOR, not an ideal cipher over the group; the usual EKE analyses assume the latter.75- No protection if the attacker can read the code (shoulder surfing, a screenshot) before the pairing completes.76- No protection against a compromised device; no post-quantum security (X25519).77- No long-term device identity: a paired device is not remembered, so every transfer needs a new code.78- Because the code is single-use, the partition leak never accumulates over several pairings.7980## Secure channel8182`BridgeSecureChannel` (actor), one per paired link:8384- ChaCha20-Poly1305, a separate key per direction.85- Frame: `sequence (u64, big-endian) ‖ ciphertext ‖ tag`. The nonce is the sequence number; the associated data are86  a protocol label, the direction and the sequence number.87- The receiver accepts only the next expected sequence number. A replayed, duplicated, dropped or reordered frame88  fails (`sequenceViolation`); a modified or truncated frame fails (`authenticationFailed`). **Any failure closes89  the channel** — there is no resynchronisation.90- Messages up to 16 MiB. Concurrent `send` calls go out in the order they were made.9192## Transports9394`BridgeTransport` is three methods (`send`, `receive`, `close`) carrying whole frames. It is not trusted: it may be95read, modified, reordered or cut without compromising the data, only the availability.9697- `InMemoryBridgeTransport.pair()` — tests.98- `NetworkBridgeTransport` + `BridgeNetworkListener` + `BridgeNetworkBrowser` — TCP with a 4-byte length prefix,99  Bonjour service `_orixbridge._tcp`, peer-to-peer enabled, **no TLS** (encryption is done above). The app's100  Info.plist needs `NSBonjourServices` with that type and an `NSLocalNetworkUsageDescription`.101102  **Not verified on two real devices.** The code compiles for macOS and iOS and one test runs a whole pairing and103  sync session over TCP on the loopback interface of one Mac. Bonjour advertising and browsing, the local-network104  permission prompt, peer-to-peer Wi-Fi and behaviour on a real network (loss, sleep, roaming) are untested.105106## Session107108`BridgeSyncSession.run()` on both devices at once:1091101. `hello` (protocol version, device identifier, device name).1112. Each sends the list of the **stamps** it holds (deletions included), in slices of 2 000.1123. Each computes, with the merge rule, which of the peer's stamps win over its own: live ones are requested113   (`request`), deletions are kept to apply.1144. Each answers the other's request with the changes and their payloads (`changes`, about 1 MiB per message), then115   `done`.1165. Each applies what it received through `SyncCoordinator.apply`.117118Sending and receiving run concurrently, so two large lists cannot block each other. The exchange is symmetric and119needs no cursor: comparing full stamp lists is exact even when changes were relayed through a third device. Cost:120about 150 bytes per synchronised item per session.121122A session that fails (tampering, disconnection) applies nothing: payloads are only applied after `done`.123A single payload above 12 MiB is skipped and logged (a canvas document that large does not sync in version 1).124125## Sync core126127### What is synchronised128129Bookmarks, spaces, tab groups, notes, canvases, workflows — and settings **only** for the keys the app lists in130`SyncConfiguration.syncedSettingKeys` (none by default; keys under `sync.`, `memory.`, `flow.`, `history.`,131`session.` are refused even if listed). Not synchronised: profiles, windows and tabs, history, downloads,132permissions, archives and their files, snapshots, agent runs, canvas attachment files, the memory index, secrets.133134### Change tracking135136One record per (entity, id) in `database.sync` (`SyncRecord`): a Lamport version, the writing device, the137modification time, a deletion time (tombstone) and the SHA-256 of the entity's canonical JSON.138139`SyncCoordinator.detectLocalChanges()` compares what is stored with the records and writes a record for every140creation, edit and deletion since the last call. No other module needs to report its writes. It runs at the start141of every export and every apply.142143The module keeps one table of its own, `sync_engine_payloads`: for each record received from another device, the144exact payload received (so it is relayed byte for byte) and the hash of the entity as stored locally (which can145differ: see repairs below). Version in the setting `sync.engine_schema_version`.146147### Merge rule148149For one key, stamps are totally ordered by150151```152(version, modifiedAt, deviceID, isTombstone, payloadHash)      compared left to right153```154155and merging keeps the greatest (`SyncMerge`). Keeping a maximum is commutative, associative and idempotent: devices156that have seen the same changes hold the same stamps, whatever the order, grouping or repetition. Tests check this157on random histories of two and three devices, at the level of the rule and at the level of real databases.158159- A device that has seen a change writes a higher version, so **an edit made knowing of another edit wins**.160- Edits made without knowledge of each other: the higher version wins, then the later `modifiedAt`, then the161  greater device identifier. Clocks only break ties between equal versions; a wrong clock cannot override a162  causally later edit.163- **Deletions**: a tombstone is a stamp like any other. It wins over older edits, loses to an edit with a higher164  version (the item comes back), and **wins an exact tie** on version, time and device.165166Per entity:167168| Entity | Resolution |169|---|---|170| note, workflow, tab group, listed setting | last writer wins on the whole item |171| 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 |172| space | last writer wins; applying a space's deletion deletes the space, its windows and tabs on the receiving device |173| bookmark | last writer wins per bookmark (title, URL, tags, parent, order), plus the tree rules below |174175Bookmark tree rules, applied identically on every device:176177- **Missing parent**: a bookmark whose folder does not exist on the receiving device (deleted, or of another178  profile) is placed at the top level.179- **Cycle**: if applying a move would close a loop (two devices each moved a folder into the other), the bookmark180  of the loop whose stamp is the smallest in the merge order is placed at the top level.181- **Folder deletion**: deleting a folder deletes what it contained on the deleting device (each with its own182  tombstone). A bookmark another device moved into, or edited inside, that folder without knowing of the deletion183  survives, at the top level.184185These placements are *repairs*: they change how the bookmark is stored locally, not its record, so they are not186re-broadcast as edits and cannot cause ping-pong.187188Profiles are device-local. A bookmark or space keeps its profile on a device that has it; otherwise it goes to189`SyncConfiguration.fallbackProfileID`; with neither, the change is **deferred** (reported, not applied, requested190again at the next session). An entity never changes profile through sync.191192### Applying193194`apply(changes)`: detect local changes; keep, per key, the incoming change that wins over what is held; verify each195payload against its stamp's hash (mismatch → rejected); apply live changes in the order space, tab group, bookmark196(parents first), note, canvas, workflow, setting; then deletions in the reverse order. Each entity is written197through the public stores, then its record. Applying the same change again is a no-op.198199Not atomic across the batch: an interruption leaves some changes applied. Since applying is idempotent and the next200session compares full stamp lists, the remainder is applied then.201202### Tombstones and leaving sync203204- `purgeTombstones()` forgets deletions older than `tombstoneRetention` (180 days by default). A device that has205  not synchronised for longer than that can bring a deleted item back, because nothing remembers the deletion.206- `removeLocalSyncState()` — "remove this device from sync": deletes every sync record and kept payload on this207  device and gives it a new device identifier. The user's data stays on the device. Other devices are not208  contacted and keep what they have; nothing is deleted elsewhere (there is no server to delete from).209  With iCloud sync, `CloudKitBridge.removeAllRemoteData()` deletes the zone in the user's iCloud — that removes210  the cloud copy for all of the user's devices, not only this one.211212## iCloud adapter213214`CloudSyncAdapter` (protocol), `DisabledCloudSync` (the default) and `CloudKitBridge`: one record per sync key in a215custom zone (`OrixBridge`) of the user's **private** CloudKit database, payloads in encrypted fields (CKAsset above216512 KiB), incremental fetch with a server change token stored in the setting `sync.cloudkit.change_token`. The sync217core does not depend on it.218219**Off by default and not verified.** The app has no iCloud container entitlement, so this adapter has never220contacted CloudKit: it only compiles. Every call throws `CloudSyncError.disabled` unless the adapter is created221with `isEnabled: true`, which must not be done before the entitlement exists (creating a `CKContainer` without it222terminates the process). Untested, among other things: zone creation, record size limits, change-token handling,223account changes, rate limiting, behaviour when two devices push the same key.224225## Not verified226227- Two real devices: never. Everything was tested in memory and over loopback TCP on one Mac.228- The pairing construction has had no external cryptographic review and has no proof; its known partition leak is229  described above.230- The CloudKit adapter (above).231- Large data sets: a session with 2 500 notes is covered; tens of thousands of items and multi-megabyte canvases232  are not measured.233- No UI exists for pairing, device discovery, progress or conflict reporting.234- Sync has no hook in the rest of the app yet: nothing calls `SyncCoordinator`, and applying a remote change does235  not notify open windows (a live tab strip or bookmark view would have to reload from the database).236
Files main
Menu

Theme