1package com.peachpasswords.sync23import kotlinx.serialization.SerialName4import kotlinx.serialization.Serializable5678910111213141516171819const val ADOPTION_VERSION = 22021private const val REASON_PRO_REQUIRED = "ADOPT_PRO_REQUIRED"22private const val REASON_DEVICE_ID_COLLISION = "ADOPT_DEVICE_ID_COLLISION"23242526272829private const val LEGACY_V1_ALLOWED = true3031323334353637383940@Serializable41data class AdoptGrantV2(42 val type: String,43 @SerialName("root_key_hex") val rootKeyHex: String,44 @SerialName("vault_id") val vaultId: String,45 val license: String? = null,46)4748private const val GRANT_TYPE = "ADOPT_GRANT"4950515253545556interface AdoptionReceiverV2Deps : AdoptionReceiverDeps {57 58 fun localIdentity(): LocalDeviceIdentity5960 suspend fun rotateLocalIdentity(): LocalDeviceIdentity6162 suspend fun validateSource(prepare: AdoptionFrame.Prepare)6364 suspend fun hasSourceIdentityCollision(prepare: AdoptionFrame.Prepare): Boolean65}666768interface AdoptionSourceV2Deps : AdoptionSourceDeps {69 suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean7071 72 73 override suspend fun rotateSourceIdentity(): LocalDeviceIdentity7475 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean7677 78798081 suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long): Boolean8283 84 suspend fun completePendingIdentity(device: PairedDevice): Boolean8586 fun snapshotCapable(): Boolean87}8889fun AdoptionReceiverV2Deps.allowLegacyV1(): Boolean = LEGACY_V1_ALLOWED9091fun AdoptionSourceV2Deps.allowLegacyV1(): Boolean = LEGACY_V1_ALLOWED9293private fun AdoptionFrame.RequestV2.valid(): Boolean =94 adoptionVersion == ADOPTION_VERSION &&95 deviceId.isNotEmpty() &&96 Hex64.matches(longTermPublicKeyHex) &&97 Hex64.matches(signingPublicKeyHex) &&98 isDeviceType(deviceType)99100private fun AdoptionFrame.Prepare.valid(): Boolean =101 deviceId.isNotEmpty() &&102 Hex64.matches(longTermPublicKeyHex) &&103 Hex64.matches(signingPublicKeyHex) &&104 isDeviceType(deviceType) &&105 Hex64.matches(vaultId)106107108109110111112suspend fun requestAdoptionV2(113 channel: PairingTransport,114 deps: AdoptionReceiverV2Deps,115 116 117 onPrepare: ((AdoptionFrame.Prepare) -> Unit)? = null,118 nowMs: Long = System.currentTimeMillis(),119): PairedDevice? {120 val receiverLicense = deps.license()121122 fun requestFrame(identity: LocalDeviceIdentity): AdoptionFrame.RequestV2 =123 AdoptionFrame.RequestV2(124 adoptionVersion = ADOPTION_VERSION,125 deviceId = identity.deviceId,126 deviceName = identity.deviceName,127 deviceType = identity.deviceType.wireValue,128 longTermPublicKeyHex = identity.longTermPublicKeyHex,129 signingPublicKeyHex = identity.signingPublicKeyHex,130 license = receiverLicense,131 snapshotCapable = true,132 )133134 135 136 fun rootKeyMatchesVault(rootKeyHex: String, vaultId: String): Boolean {137 if (!validateRootKeyHex(rootKeyHex) || !Hex64.matches(vaultId)) return false138 val rootKeyBytes = hexToPubkey(rootKeyHex)139 return try {140 computeVaultId(rootKeyBytes) == vaultId141 } finally {142 rootKeyBytes.fill(0)143 }144 }145146 sendFrame(channel, requestFrame(deps.localIdentity()))147148 if (receiveFrame(channel) !is AdoptionFrame.ConfirmRequired) {149 deps.onError("ADOPT_UNEXPECTED_FRAME")150 return null151 }152153 val confirmed = deps.confirmSas()154 sendFrame(channel, AdoptionFrame.Confirm(confirmed))155 if (!confirmed) {156 deps.onError("ADOPT_SAS_REJECTED")157 return null158 }159160 161 162 var prepared = receiveFrame(channel)163 if (prepared is AdoptionFrame.Reject && prepared.reason == REASON_DEVICE_ID_COLLISION) {164 sendFrame(channel, requestFrame(deps.rotateLocalIdentity()))165 prepared = receiveFrame(channel)166 }167 if (prepared is AdoptionFrame.Reject) {168 deps.onError(prepared.reason)169 return null170 }171 if (prepared !is AdoptionFrame.Prepare || !prepared.valid()) {172 deps.onError("ADOPT_UNEXPECTED_FRAME")173 return null174 }175176 deps.validateSource(prepared)177178 179 180 if (deps.hasSourceIdentityCollision(prepared)) {181 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))182 val rotated = receiveFrame(channel)183 if (rotated !is AdoptionFrame.Prepare || !rotated.valid()) {184 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")185 return null186 }187 deps.validateSource(rotated)188 if (deps.hasSourceIdentityCollision(rotated)) {189 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))190 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")191 return null192 }193 prepared = rotated194 }195196 if (receiverLicense == null && prepared.license == null) {197 deps.onError(REASON_PRO_REQUIRED)198 return null199 }200201 onPrepare?.invoke(prepared)202203 sendFrame(channel, AdoptionFrame.Ready)204205 val raw = String(channel.receive(), Charsets.UTF_8)206 207 val rejection = runCatching {208 AdoptJson.decodeFromString(AdoptionFrame.serializer(), raw)209 }.getOrNull() as? AdoptionFrame.Reject210 if (rejection != null) {211 deps.onError(rejection.reason)212 return null213 }214 val grant = runCatching {215 AdoptJson.decodeFromString(AdoptGrantV2.serializer(), raw)216 }.getOrNull()217 if (grant == null || grant.type != GRANT_TYPE) {218 deps.onError("ADOPT_UNEXPECTED_FRAME")219 return null220 }221 222 223 if (grant.vaultId != prepared.vaultId || !rootKeyMatchesVault(grant.rootKeyHex, grant.vaultId)) {224 deps.onError("ADOPT_VAULT_ID_MISMATCH")225 return null226 }227228 val vaultId = deps.createVaultFromRootKey(grant.rootKeyHex)229 if (vaultId != grant.vaultId) {230 deps.onError("ADOPT_VAULT_ID_MISMATCH")231 return null232 }233 if (receiverLicense == null) {234 grant.license?.let { deps.applyLicense(it) }235 }236237 238 239 val sourceDevice = PairedDevice(240 deviceId = prepared.deviceId,241 deviceName = prepared.deviceName,242 deviceType = prepared.deviceType,243 longTermPublicKeyHex = prepared.longTermPublicKeyHex,244 signingPublicKeyHex = prepared.signingPublicKeyHex,245 trustSource = "direct",246 wsPort = prepared.wsPort,247 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,248 relayUrl = deps.pairState?.relayUrl ?: prepared.relayUrl,249 pairedAt = nowMs,250 )251 deps.upsertPairedDeviceAndClearRevocation(sourceDevice)252 sendFrame(channel, AdoptionFrame.Applied)253254 if (receiveFrame(channel) !is AdoptionFrame.Complete) {255 deps.onError("ADOPT_COMPLETION_MISSING")256 return null257 }258 return sourceDevice259}260261262263264265266suspend fun grantAdoptionV2(267 channel: PairingTransport,268 request: AdoptionFrame.RequestV2,269 deps: AdoptionSourceV2Deps,270 nowMs: Long = System.currentTimeMillis(),271): PairedDevice? {272 if (!request.valid()) return null273274 275 276 sendFrame(channel, AdoptionFrame.ConfirmRequired)277 if (!deps.onConsent(request)) return null278279 val confirmation = receiveFrame(channel)280 if (confirmation !is AdoptionFrame.Confirm || !confirmation.confirmed) return null281282 fun receiverFrom(identity: AdoptionFrame.RequestV2): PairedDevice =283 PairedDevice(284 deviceId = identity.deviceId,285 deviceName = identity.deviceName,286 deviceType = identity.deviceType,287 longTermPublicKeyHex = identity.longTermPublicKeyHex,288 signingPublicKeyHex = identity.signingPublicKeyHex,289 trustSource = "direct",290 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,291 relayUrl = deps.pairState?.relayUrl,292 pairedAt = nowMs,293 )294295 296 297 var receiver = receiverFrom(request)298 if (deps.hasDeviceIdentityCollision(receiver)) {299 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))300 val rotated = receiveFrame(channel)301 if (rotated !is AdoptionFrame.RequestV2 || !rotated.valid()) return null302 receiver = receiverFrom(rotated)303 if (deps.hasDeviceIdentityCollision(receiver)) {304 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))305 return null306 }307 }308309 var license = deps.license()310 if (license == null && request.license != null) {311 deps.applyLicense(request.license)312 license = deps.license()313 }314 if (license == null) {315 sendFrame(channel, AdoptionFrame.Reject(REASON_PRO_REQUIRED))316 return null317 }318319 320 321 if (!deps.persistPendingIdentity(receiver, nowMs)) return null322323 val rootKeyHex = deps.rootKeyHex()324 if (!validateRootKeyHex(rootKeyHex)) return null325326 var sourceIdentity = deps.sourceIdentity327 var sourceRotations = 0328 while (true) {329 sendFrame(330 channel,331 AdoptionFrame.Prepare(332 deviceId = sourceIdentity.deviceId,333 deviceName = sourceIdentity.deviceName,334 deviceType = sourceIdentity.deviceType.wireValue,335 longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,336 signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,337 vaultId = deps.vaultId(),338 wsPort = sourceIdentity.wsPort,339 relayUrl = deps.pairState?.relayUrl,340 license = license,341 snapshotCapable = deps.snapshotCapable(),342 ),343 )344345 val next = receiveFrame(channel)346 if (next is AdoptionFrame.Reject &&347 next.reason == REASON_DEVICE_ID_COLLISION &&348 sourceRotations == 0349 ) {350 sourceIdentity = deps.rotateSourceIdentity()351 sourceRotations++352 continue353 }354 if (next !is AdoptionFrame.Ready) return null355 break356 }357358 359 360 channel.send(361 AdoptJson.encodeToString(362 AdoptGrantV2.serializer(),363 AdoptGrantV2(364 type = GRANT_TYPE,365 rootKeyHex = rootKeyHex,366 vaultId = deps.vaultId(),367 license = license,368 ),369 ).toByteArray(Charsets.UTF_8),370 )371372 if (receiveFrame(channel) !is AdoptionFrame.Applied) return null373374 375 if (!deps.completePendingIdentity(receiver)) return null376 deps.upsertPairedDevice(receiver)377 sendFrame(channel, AdoptionFrame.Complete)378 return receiver379}