1package com.peachpasswords.sync23import kotlinx.serialization.SerialName4import kotlinx.serialization.Serializable5import kotlinx.serialization.encodeToString6import kotlinx.serialization.json.Json78910111213141516171819202122@Serializable23sealed class AdoptionFrame {24 25262728293031323334 @Serializable35 @SerialName("ADOPT_REQUEST")36 data class Request(37 @SerialName("device_id") val sessionRequestId: String,38 @SerialName("device_name") val deviceName: String,39 @SerialName("device_type") val deviceType: String,40 val license: String? = null,41 @SerialName("snapshot_capable") val snapshotCapable: Boolean? = null,42 ) : AdoptionFrame()4344 @Serializable45 @SerialName("ADOPT_CONFIRM")46 data class Confirm(47 val confirmed: Boolean,48 ) : AdoptionFrame()4950 @Serializable51 @SerialName("ADOPT_GRANT")52 data class Grant(53 @SerialName("root_key_hex") val rootKeyHex: String,54 @SerialName("vault_id") val vaultId: String,55 val license: String? = null,56 val source: Source,57 58 59 60 61 62 63 64 @SerialName("snapshot_capable") val snapshotCapable: Boolean = false,65 ) : AdoptionFrame()6667 @Serializable68 @SerialName("ADOPT_IDENTITY")69 data class Identity(70 @SerialName("device_id") val deviceId: String,71 @SerialName("device_name") val deviceName: String,72 @SerialName("device_type") val deviceType: String,73 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,74 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,75 ) : AdoptionFrame()7677 7879808182 @Serializable83 @SerialName("ADOPT_COMPLETE")84 data object Complete : AdoptionFrame()8586 87 @Serializable88 @SerialName("ADOPT_APPLIED")89 data object Applied : AdoptionFrame()9091 92 @Serializable93 @SerialName("ADOPT_REJECT")94 data class Reject(95 val reason: String,96 ) : AdoptionFrame()9798 99100101102103 @Serializable104 @SerialName("ADOPT_SNAPSHOT")105 data class Snapshot(106 @SerialName("chunk_index") val chunkIndex: Int,107 @SerialName("chunk_count") val chunkCount: Int,108 val entries: Map<String, String>,109 val tombstones: Map<String, Long>,110 @SerialName("duress_slot") val duressSlot: String? = null,111 ) : AdoptionFrame()112113 114 @Serializable115 @SerialName("ADOPT_SNAPSHOT_APPLIED")116 data class SnapshotApplied(117 @SerialName("entries_received") val entriesReceived: Int,118 @SerialName("tombstones_received") val tombstonesReceived: Int,119 ) : AdoptionFrame()120121 122 @Serializable123 @SerialName("ADOPT_DEVICE_MANIFEST")124 data class DeviceManifestFrame(125 val manifest: SignedDeviceManifest,126 ) : AdoptionFrame()127128 129 @Serializable130 @SerialName("ADOPT_DEVICE_MANIFEST_APPLIED")131 data object DeviceManifestApplied : AdoptionFrame()132133 @Serializable134 data class Source(135 @SerialName("device_id") val deviceId: String,136 @SerialName("device_name") val deviceName: String,137 @SerialName("device_type") val deviceType: String,138 @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,139 @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,140 @SerialName("ws_port") val wsPort: Int? = null,141 @SerialName("relay_url") val relayUrl: String? = null,142 )143}144145data class AdoptionPairState(146 val rendezvousSecretHex: String,147 val relayUrl: String? = null,148)149150151152153154155data class ReceivedSnapshot(156 val entries: Map<String, String>,157 val tombstones: Map<String, Long>,158 val duressSlot: String? = null,159)160161162163164165166167const val MAX_SNAPSHOT_CHUNK_BYTES = 512 * 1024 168const val MAX_SNAPSHOT_CHUNKS = 200169170171172internal const val SNAPSHOT_FRAME_WIRE_CEILING = MAX_SNAPSHOT_CHUNK_BYTES + 256 * 1024173internal val MAX_PADDED_SNAPSHOT_FRAME_BYTES = SyncPadding.bucket(SNAPSHOT_FRAME_WIRE_CEILING + 4)174175176177178179180181const val MAX_ADOPT_SNAPSHOT_BYTES = 10 * 1024 * 1024 182const val MAX_ADOPT_SNAPSHOT_ENTRIES = 25_000183const val MAX_ADOPT_SNAPSHOT_TOMBSTONES = 25_000184185const val MAX_ADOPT_SNAPSHOT_ID_CHARS = SyncLimits.MAX_ID_LENGTH186187188189190191const val MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES = SyncLimits.MAX_ENTRY_ENVELOPE_BYTES192193194195196197class AdoptSnapshotBudget {198 val entries = LinkedHashMap<String, String>()199 val tombstones = LinkedHashMap<String, Long>()200 var duressSlot: String? = null201 202 var bytes: Int = 0203 var entryCount: Int = 0204 var tombstoneCount: Int = 0205}206207fun createAdoptSnapshotBudget(): AdoptSnapshotBudget = AdoptSnapshotBudget()208209210211212213214215216217218219fun applyAdoptSnapshotFrame(220 acc: AdoptSnapshotBudget,221 entries: Map<String, String>,222 tombstones: Map<String, Long>,223 duressSlot: String?,224 frameBytes: Int,225) {226 if (frameBytes > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {227 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")228 }229 for ((id, envelope) in entries) {230 if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")231 if (envelope.length > MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES) {232 throw IllegalStateException("ADOPT_SNAPSHOT_ENVELOPE_TOO_LARGE")233 }234 if (acc.entryCount >= MAX_ADOPT_SNAPSHOT_ENTRIES) {235 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_ENTRIES")236 }237 acc.entryCount++238 acc.entries[id] = envelope239 }240 for ((id, ts) in tombstones) {241 if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")242 243 244 if (acc.tombstoneCount >= MAX_ADOPT_SNAPSHOT_TOMBSTONES) {245 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_TOMBSTONES")246 }247 acc.tombstoneCount++248 acc.tombstones[id] = ts249 }250 if (!duressSlot.isNullOrEmpty()) {251 252 253 if (duressSlot.length > SNAPSHOT_FRAME_WIRE_CEILING) {254 throw IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")255 }256 acc.duressSlot = duressSlot257 }258 acc.bytes += frameBytes259}260261262interface AdoptionReceiverDeps {263 val deviceName: String264 val deviceType: DeviceType265 fun generateDeviceId(): String266 267 suspend fun confirmSas(): Boolean268 269270271272 suspend fun validateSource(source: AdoptionFrame.Source) {}273274 275 suspend fun createVaultFromRootKey(rootKeyHex: String): String276 suspend fun deriveLocalIdentity(): LocalDeviceIdentity277 278 suspend fun clearPairedDeviceRevocation(deviceId: String) {}279 suspend fun upsertPairedDevice(device: PairedDevice)280 suspend fun applyLicense(license: String) {}281 282 suspend fun license(): String? = null283 val pairState: AdoptionPairState? get() = null284 fun onError(error: String)285 286 suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}287 288289290291292293294295 suspend fun applyIncomingDeviceManifest(296 manifest: SignedDeviceManifest,297 authenticatedRemoteStaticPublicKey: ByteArray,298 ) {}299 300 suspend fun markSynced(deviceId: String) {}301}302303304interface AdoptionSourceDeps {305 val sourceIdentity: LocalDeviceIdentity306 suspend fun rootKeyHex(): String307 suspend fun vaultId(): String308 suspend fun license(): String? = null309 310 suspend fun applyLicense(license: String) {}311312 313314315316317318 suspend fun onConsent(request: AdoptionFrame.Request): Boolean319 suspend fun upsertPairedDevice(device: PairedDevice)320 fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false321 val pairState: AdoptionPairState? get() = null322 323 suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null324 325 suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null326 327 suspend fun markSynced(deviceId: String) {}328 329 suspend fun duressSlotJson(): String? = null330}331332private val Hex64 = Regex("^[0-9a-f]{64}\$")333334fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)335336fun isAdoptRequest(frame: AdoptionFrame?): Boolean =337 frame is AdoptionFrame.Request &&338 frame.sessionRequestId.isNotEmpty() &&339 isDeviceType(frame.deviceType)340341fun isAdoptGrant(frame: AdoptionFrame?): Boolean =342 frame is AdoptionFrame.Grant &&343 validateRootKeyHex(frame.rootKeyHex) &&344 Hex64.matches(frame.vaultId) &&345 isDeviceType(frame.source.deviceType) &&346 Hex64.matches(frame.source.longTermPublicKeyHex) &&347 (frame.source.relayUrl == null ||348 runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)349350fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =351 frame is AdoptionFrame.Confirm352353fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =354 frame is AdoptionFrame.Identity &&355 frame.deviceId.isNotEmpty() &&356 isDeviceType(frame.deviceType) &&357 Hex64.matches(frame.longTermPublicKeyHex)358359fun isAdoptComplete(frame: AdoptionFrame?): Boolean =360 frame is AdoptionFrame.Complete361362fun isAdoptApplied(frame: AdoptionFrame?): Boolean =363 frame is AdoptionFrame.Applied364365fun isAdoptReject(frame: AdoptionFrame?): Boolean =366 frame is AdoptionFrame.Reject && frame.reason == "ADOPT_PRO_REQUIRED"367368fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =369 frame is AdoptionFrame.Snapshot &&370 frame.chunkIndex >= 0 &&371 frame.chunkCount >= 1372373374375376377378379380suspend fun requestAdoption(381 channel: PairingTransport,382 deps: AdoptionReceiverDeps,383 384 385 386 387 388 onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,389 nowMs: () -> Long = { System.currentTimeMillis() },390): PairedDevice? {391 val receiverLicense = deps.license()392 393 394 sendFrame(channel, AdoptionFrame.Request(395 sessionRequestId = deps.generateDeviceId(),396 deviceName = deps.deviceName,397 deviceType = deps.deviceType.wireValue,398 license = receiverLicense,399 snapshotCapable = true,400 ))401402 val confirmed = deps.confirmSas()403 sendFrame(channel, AdoptionFrame.Confirm(confirmed))404 if (!confirmed) {405 deps.onError("ADOPT_SAS_REJECTED")406 return null407 }408409 val frame = receiveFrame(channel)410 if (isAdoptReject(frame)) {411 deps.onError((frame as AdoptionFrame.Reject).reason)412 return null413 }414 if (!isAdoptGrant(frame)) {415 deps.onError("ADOPT_UNEXPECTED_FRAME")416 return null417 }418 val grant = frame as AdoptionFrame.Grant419 onGrant?.invoke(grant)420421 val rootKeyBytes = hexToPubkey(grant.rootKeyHex)422 try {423 if (computeVaultId(rootKeyBytes) != grant.vaultId) {424 deps.onError("ADOPT_VAULT_ID_MISMATCH")425 return null426 }427 } finally {428 rootKeyBytes.fill(0)429 }430 if (receiverLicense == null && grant.license == null) {431 deps.onError("ADOPT_PRO_REQUIRED")432 return null433 }434435 deps.validateSource(grant.source)436 val vaultId = deps.createVaultFromRootKey(grant.rootKeyHex)437 if (vaultId != grant.vaultId) {438 deps.onError("ADOPT_VAULT_ID_MISMATCH")439 return null440 }441442 if (receiverLicense == null) {443 grant.license?.let { deps.applyLicense(it) }444 }445446 val identity = deps.deriveLocalIdentity()447 sendFrame(channel, AdoptionFrame.Identity(448 deviceId = identity.deviceId,449 deviceName = identity.deviceName,450 deviceType = identity.deviceType.wireValue,451 longTermPublicKeyHex = identity.longTermPublicKeyHex,452 signingPublicKeyHex = identity.signingPublicKeyHex,453 ))454455 if (!isAdoptComplete(receiveFrame(channel))) {456 deps.onError("ADOPT_COMPLETION_MISSING")457 return null458 }459460 val sourceDevice = PairedDevice(461 deviceId = grant.source.deviceId,462 deviceName = grant.source.deviceName,463 deviceType = grant.source.deviceType,464 longTermPublicKeyHex = grant.source.longTermPublicKeyHex,465 signingPublicKeyHex = grant.source.signingPublicKeyHex,466 trustSource = "direct",467 wsPort = grant.source.wsPort,468 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,469 relayUrl = deps.pairState?.relayUrl ?: grant.source.relayUrl,470 pairedAt = nowMs(),471 )472 473 474 475 deps.clearPairedDeviceRevocation(sourceDevice.deviceId)476 deps.upsertPairedDevice(sourceDevice)477 sendFrame(channel, AdoptionFrame.Applied)478 return sourceDevice479}480481482483484485486suspend fun grantAdoption(487 channel: PairingTransport,488 request: AdoptionFrame.Request,489 deps: AdoptionSourceDeps,490 nowMs: () -> Long = { System.currentTimeMillis() },491): PairedDevice? {492 if (!deps.onConsent(request)) return null493494 val confirmation = receiveFrame(channel)495 if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {496 return null497 }498499 var sourceLicense = deps.license()500 if (sourceLicense == null && request.license != null) {501 sourceLicense = runCatching {502 deps.applyLicense(request.license)503 deps.license()504 }.getOrNull()505 }506 if (sourceLicense == null) {507 sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))508 throw IllegalStateException("ADOPT_PRO_REQUIRED")509 }510511 val rootKeyHex = deps.rootKeyHex()512 if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")513514 sendFrame(channel, AdoptionFrame.Grant(515 rootKeyHex = rootKeyHex,516 vaultId = deps.vaultId(),517 license = sourceLicense,518 source = AdoptionFrame.Source(519 deviceId = deps.sourceIdentity.deviceId,520 deviceName = deps.sourceIdentity.deviceName,521 deviceType = deps.sourceIdentity.deviceType.wireValue,522 longTermPublicKeyHex = deps.sourceIdentity.longTermPublicKeyHex,523 signingPublicKeyHex = deps.sourceIdentity.signingPublicKeyHex,524 wsPort = deps.sourceIdentity.wsPort,525 relayUrl = deps.pairState?.relayUrl,526 ),527 snapshotCapable = request.snapshotCapable == true,528 ))529530 var identity = receiveFrame(channel)531 if (!isAdoptIdentity(identity)) return null532 identity as AdoptionFrame.Identity533534 var device = PairedDevice(535 deviceId = identity.deviceId,536 deviceName = identity.deviceName,537 deviceType = identity.deviceType,538 longTermPublicKeyHex = identity.longTermPublicKeyHex,539 signingPublicKeyHex = identity.signingPublicKeyHex,540 trustSource = "direct",541 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,542 relayUrl = deps.pairState?.relayUrl,543 pairedAt = nowMs(),544 )545 if (deps.hasDeviceIdentityCollision(device)) {546 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))547 identity = receiveFrame(channel)548 if (!isAdoptIdentity(identity)) return null549 identity as AdoptionFrame.Identity550 device = device.copy(551 deviceId = identity.deviceId,552 deviceName = identity.deviceName,553 deviceType = identity.deviceType,554 longTermPublicKeyHex = identity.longTermPublicKeyHex,555 signingPublicKeyHex = identity.signingPublicKeyHex,556 )557 if (deps.hasDeviceIdentityCollision(device)) {558 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))559 return null560 }561 }562 deps.upsertPairedDevice(device)563 sendFrame(channel, AdoptionFrame.Complete)564 if (!isAdoptApplied(receiveFrame(channel))) return null565 return device566}567568569570571572573val AdoptJson: Json = Json {574 classDiscriminator = "type"575 encodeDefaults = false576 ignoreUnknownKeys = true577}578579suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {580 channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))581}582583584suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =585 runCatching {586 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))587 }.getOrNull()588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619suspend fun sendVaultSnapshot(620 channel: PairingTransport,621 entries: Map<String, String>,622 tombstones: Map<String, Long>,623 duressSlot: String? = null,624) {625 val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)626 627 628 629 630 631 val acc = createAdoptSnapshotBudget()632 val encoded = frames.map {633 AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()634 }635 for (i in frames.indices) {636 val frame = frames[i]637 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)638 }639 for (raw in encoded) channel.send(SyncPadding.pad(raw))640}641642643644645646647private fun buildAdoptSnapshotFrames(648 entries: Map<String, String>,649 tombstones: Map<String, Long>,650 duressSlot: String?,651): List<AdoptionFrame.Snapshot> {652 val includeDuress = !duressSlot.isNullOrBlank()653 654 655 val entryCap = MAX_SNAPSHOT_CHUNKS - 1656657 val chunks = mutableListOf<Map<String, String>>()658 var current = LinkedHashMap<String, String>()659 var currentBytes = 2 660 for ((id, envelope) in entries) {661 662 val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1663 if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {664 chunks.add(current)665 current = LinkedHashMap()666 currentBytes = 2667 }668 current[id] = envelope669 currentBytes += entryBytes670 }671 chunks.add(current)672673 val entriesChunkCount = minOf(chunks.size, entryCap)674 val totalChunks = entriesChunkCount + 1675 val supplementalFrame = AdoptionFrame.Snapshot(676 chunkIndex = entriesChunkCount,677 chunkCount = totalChunks,678 entries = emptyMap(),679 tombstones = tombstones,680 duressSlot = duressSlot.takeIf { includeDuress },681 )682683 if (684 AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)685 .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING686 ) {687 if (includeDuress) throw SnapshotDuressFrameTooLargeException()688 throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")689 }690691 val frames = mutableListOf<AdoptionFrame.Snapshot>()692 for (index in 0 until entriesChunkCount) {693 frames.add(AdoptionFrame.Snapshot(694 chunkIndex = index,695 chunkCount = totalChunks,696 entries = chunks[index],697 tombstones = emptyMap(),698 duressSlot = null,699 ))700 }701 frames.add(supplementalFrame)702 return frames703}704705internal class SnapshotDuressFrameTooLargeException :706 IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")707708709710711712713714715716717718719suspend fun receiveVaultSnapshot(720 channel: PairingTransport,721): ReceivedSnapshot {722 val acc = createAdoptSnapshotBudget()723 var chunkCount = -1724 var received = 0725 while (chunkCount == -1 || received < chunkCount) {726 val wire = channel.receive()727 if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {728 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")729 }730 val raw = runCatching { SyncPadding.unpad(wire) }731 .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }732 if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {733 throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")734 }735 if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {736 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")737 }738 val frame = runCatching {739 AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))740 }.getOrNull()741 if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")742 frame as AdoptionFrame.Snapshot743 if (chunkCount == -1) {744 chunkCount = frame.chunkCount745 if (chunkCount > MAX_SNAPSHOT_CHUNKS) {746 throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")747 }748 } else if (frame.chunkCount != chunkCount) {749 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")750 }751 if (frame.chunkIndex != received) {752 throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")753 }754 applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)755 received++756 }757 return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)758}759760private fun isDeviceType(value: String): Boolean =761 DeviceType.entries.any { it.wireValue == value }