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_ALLOWED9293949596979899100101102103104105internal fun bindSourceSessionDeps(106 sourceDeps: AdoptionSourceV2Deps,107 sourceIdentity: LocalDeviceIdentity,108 pairState: AdoptionPairState,109 sas: String,110 snapshotCapable: Boolean,111 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,112): AdoptionSourceV2Deps = object : AdoptionSourceV2Deps {113 override val sourceIdentity = sourceIdentity114 override val pairState = pairState115 override suspend fun rootKeyHex() = sourceDeps.rootKeyHex()116 override suspend fun vaultId() = sourceDeps.vaultId()117 override suspend fun license() = sourceDeps.license()118 override suspend fun applyLicense(license: String) = sourceDeps.applyLicense(license)119 override suspend fun onConsent(request: AdoptionFrame.Request) = true120121 122 123 124 125 126 override suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean =127 confirm(128 sas,129 AdoptionFrame.Request(130 sessionRequestId = request.deviceId,131 deviceName = request.deviceName,132 deviceType = request.deviceType,133 license = request.license,134 snapshotCapable = request.snapshotCapable,135 ),136 )137138 override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long) =139 sourceDeps.persistPendingHolder(request, nowMs)140141 override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice) =142 sourceDeps.completePendingHolder(request, device)143144 override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long) =145 sourceDeps.persistPendingIdentity(device, nowMs)146147 override suspend fun completePendingIdentity(device: PairedDevice) =148 sourceDeps.completePendingIdentity(device)149150 override suspend fun upsertPairedDevice(device: PairedDevice) =151 sourceDeps.upsertPairedDevice(device)152153 override fun hasDeviceIdentityCollision(device: PairedDevice) =154 sourceDeps.hasDeviceIdentityCollision(device)155156 override suspend fun rotateSourceIdentity() = sourceDeps.rotateSourceIdentity()157 override fun snapshotCapable() = snapshotCapable158 override suspend fun vaultSnapshot() = sourceDeps.vaultSnapshot()159 override suspend fun outgoingDeviceManifest() = sourceDeps.outgoingDeviceManifest()160 override suspend fun markSynced(deviceId: String) = sourceDeps.markSynced(deviceId)161 override suspend fun duressSlotJson() = sourceDeps.duressSlotJson()162}163164private fun AdoptionFrame.RequestV2.valid(): Boolean =165 adoptionVersion == ADOPTION_VERSION &&166 deviceId.isNotEmpty() &&167 Hex64.matches(longTermPublicKeyHex) &&168 Hex64.matches(signingPublicKeyHex) &&169 isDeviceType(deviceType)170171private fun AdoptionFrame.Prepare.valid(): Boolean =172 deviceId.isNotEmpty() &&173 Hex64.matches(longTermPublicKeyHex) &&174 Hex64.matches(signingPublicKeyHex) &&175 isDeviceType(deviceType) &&176 Hex64.matches(vaultId)177178179180181182183suspend fun requestAdoptionV2(184 channel: PairingTransport,185 deps: AdoptionReceiverV2Deps,186 187 188 onPrepare: ((AdoptionFrame.Prepare) -> Unit)? = null,189 nowMs: Long = System.currentTimeMillis(),190): PairedDevice? {191 val receiverLicense = deps.license()192193 fun requestFrame(identity: LocalDeviceIdentity): AdoptionFrame.RequestV2 =194 AdoptionFrame.RequestV2(195 adoptionVersion = ADOPTION_VERSION,196 deviceId = identity.deviceId,197 deviceName = identity.deviceName,198 deviceType = identity.deviceType.wireValue,199 longTermPublicKeyHex = identity.longTermPublicKeyHex,200 signingPublicKeyHex = identity.signingPublicKeyHex,201 license = receiverLicense,202 snapshotCapable = true,203 )204205 206 207 fun rootKeyMatchesVault(rootKeyHex: String, vaultId: String): Boolean {208 if (!validateRootKeyHex(rootKeyHex) || !Hex64.matches(vaultId)) return false209 val rootKeyBytes = hexToPubkey(rootKeyHex)210 return try {211 computeVaultId(rootKeyBytes) == vaultId212 } finally {213 rootKeyBytes.fill(0)214 }215 }216217 sendFrame(channel, requestFrame(deps.localIdentity()))218219 if (receiveFrame(channel) !is AdoptionFrame.ConfirmRequired) {220 deps.onError("ADOPT_UNEXPECTED_FRAME")221 return null222 }223224 val confirmed = deps.confirmSas()225 sendFrame(channel, AdoptionFrame.Confirm(confirmed))226 if (!confirmed) {227 deps.onError("ADOPT_SAS_REJECTED")228 return null229 }230231 232 233 var prepared = receiveFrame(channel)234 if (prepared is AdoptionFrame.Reject && prepared.reason == REASON_DEVICE_ID_COLLISION) {235 sendFrame(channel, requestFrame(deps.rotateLocalIdentity()))236 prepared = receiveFrame(channel)237 }238 if (prepared is AdoptionFrame.Reject) {239 deps.onError(prepared.reason)240 return null241 }242 if (prepared !is AdoptionFrame.Prepare || !prepared.valid()) {243 deps.onError("ADOPT_UNEXPECTED_FRAME")244 return null245 }246247 deps.validateSource(prepared)248249 250 251 if (deps.hasSourceIdentityCollision(prepared)) {252 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))253 val rotated = receiveFrame(channel)254 if (rotated !is AdoptionFrame.Prepare || !rotated.valid()) {255 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")256 return null257 }258 deps.validateSource(rotated)259 if (deps.hasSourceIdentityCollision(rotated)) {260 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))261 deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")262 return null263 }264 prepared = rotated265 }266267 if (receiverLicense == null && prepared.license == null) {268 deps.onError(REASON_PRO_REQUIRED)269 return null270 }271272 onPrepare?.invoke(prepared)273274 sendFrame(channel, AdoptionFrame.Ready)275276 val raw = String(channel.receive(), Charsets.UTF_8)277 278 val rejection = runCatching {279 AdoptJson.decodeFromString(AdoptionFrame.serializer(), raw)280 }.getOrNull() as? AdoptionFrame.Reject281 if (rejection != null) {282 deps.onError(rejection.reason)283 return null284 }285 val grant = runCatching {286 AdoptJson.decodeFromString(AdoptGrantV2.serializer(), raw)287 }.getOrNull()288 if (grant == null || grant.type != GRANT_TYPE) {289 deps.onError("ADOPT_UNEXPECTED_FRAME")290 return null291 }292 293 294 if (grant.vaultId != prepared.vaultId || !rootKeyMatchesVault(grant.rootKeyHex, grant.vaultId)) {295 deps.onError("ADOPT_VAULT_ID_MISMATCH")296 return null297 }298299 val vaultId = deps.createVaultFromRootKey(grant.rootKeyHex)300 if (vaultId != grant.vaultId) {301 deps.onError("ADOPT_VAULT_ID_MISMATCH")302 return null303 }304 if (receiverLicense == null) {305 grant.license?.let { deps.applyLicense(it) }306 }307308 309 310 val sourceDevice = PairedDevice(311 deviceId = prepared.deviceId,312 deviceName = prepared.deviceName,313 deviceType = prepared.deviceType,314 longTermPublicKeyHex = prepared.longTermPublicKeyHex,315 signingPublicKeyHex = prepared.signingPublicKeyHex,316 trustSource = "direct",317 wsPort = prepared.wsPort,318 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,319 relayUrl = deps.pairState?.relayUrl ?: prepared.relayUrl,320 pairedAt = nowMs,321 )322 deps.upsertPairedDeviceAndClearRevocation(sourceDevice)323 sendFrame(channel, AdoptionFrame.Applied)324325 if (receiveFrame(channel) !is AdoptionFrame.Complete) {326 deps.onError("ADOPT_COMPLETION_MISSING")327 return null328 }329 return sourceDevice330}331332333334335336337suspend fun grantAdoptionV2(338 channel: PairingTransport,339 request: AdoptionFrame.RequestV2,340 deps: AdoptionSourceV2Deps,341 nowMs: Long = System.currentTimeMillis(),342): PairedDevice? {343 if (!request.valid()) return null344345 346 347 sendFrame(channel, AdoptionFrame.ConfirmRequired)348 if (!deps.onConsent(request)) return null349350 val confirmation = receiveFrame(channel)351 if (confirmation !is AdoptionFrame.Confirm || !confirmation.confirmed) return null352353 fun receiverFrom(identity: AdoptionFrame.RequestV2): PairedDevice =354 PairedDevice(355 deviceId = identity.deviceId,356 deviceName = identity.deviceName,357 deviceType = identity.deviceType,358 longTermPublicKeyHex = identity.longTermPublicKeyHex,359 signingPublicKeyHex = identity.signingPublicKeyHex,360 trustSource = "direct",361 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,362 relayUrl = deps.pairState?.relayUrl,363 pairedAt = nowMs,364 )365366 367 368 var receiver = receiverFrom(request)369 if (deps.hasDeviceIdentityCollision(receiver)) {370 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))371 val rotated = receiveFrame(channel)372 if (rotated !is AdoptionFrame.RequestV2 || !rotated.valid()) return null373 receiver = receiverFrom(rotated)374 if (deps.hasDeviceIdentityCollision(receiver)) {375 sendFrame(channel, AdoptionFrame.Reject(REASON_DEVICE_ID_COLLISION))376 return null377 }378 }379380 var license = deps.license()381 if (license == null && request.license != null) {382 deps.applyLicense(request.license)383 license = deps.license()384 }385 if (license == null) {386 sendFrame(channel, AdoptionFrame.Reject(REASON_PRO_REQUIRED))387 return null388 }389390 391 392 if (!deps.persistPendingIdentity(receiver, nowMs)) return null393394 val rootKeyHex = deps.rootKeyHex()395 if (!validateRootKeyHex(rootKeyHex)) return null396397 var sourceIdentity = deps.sourceIdentity398 var sourceRotations = 0399 while (true) {400 sendFrame(401 channel,402 AdoptionFrame.Prepare(403 deviceId = sourceIdentity.deviceId,404 deviceName = sourceIdentity.deviceName,405 deviceType = sourceIdentity.deviceType.wireValue,406 longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,407 signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,408 vaultId = deps.vaultId(),409 wsPort = sourceIdentity.wsPort,410 relayUrl = deps.pairState?.relayUrl,411 license = license,412 snapshotCapable = deps.snapshotCapable(),413 ),414 )415416 val next = receiveFrame(channel)417 if (next is AdoptionFrame.Reject &&418 next.reason == REASON_DEVICE_ID_COLLISION &&419 sourceRotations == 0420 ) {421 sourceIdentity = deps.rotateSourceIdentity()422 sourceRotations++423 continue424 }425 if (next !is AdoptionFrame.Ready) return null426 break427 }428429 430 431 channel.send(432 AdoptJson.encodeToString(433 AdoptGrantV2.serializer(),434 AdoptGrantV2(435 type = GRANT_TYPE,436 rootKeyHex = rootKeyHex,437 vaultId = deps.vaultId(),438 license = license,439 ),440 ).toByteArray(Charsets.UTF_8),441 )442443 if (receiveFrame(channel) !is AdoptionFrame.Applied) return null444445 446 if (!deps.completePendingIdentity(receiver)) return null447 deps.upsertPairedDevice(receiver)448 sendFrame(channel, AdoptionFrame.Complete)449 return receiver450}