AdoptionProtocol.kt

14.1 KB · raw

1package com.peachpasswords.sync23import kotlinx.serialization.SerialName4import kotlinx.serialization.Serializable56/**7 * Adoption transcript v2.8 *9 * v1 hands over the root-bearing `ADOPT_GRANT` before the receiver's identity10 * has been exchanged or validated, so the source's pending record is keyed on a11 * session label that is explicitly not an identity — the source can list and12 * revoke nothing durable. v2 places a validated identity before every13 * root-bearing frame.14 *15 * Frozen contract: `peach-browser/docs/sync-protocol.md` section 10.16 */1718/** Adoption transcript version. A v1 request carries no version field at all. */19const val ADOPTION_VERSION = 22021private const val REASON_PRO_REQUIRED = "ADOPT_PRO_REQUIRED"22private const val REASON_DEVICE_ID_COLLISION = "ADOPT_DEVICE_ID_COLLISION"2324/**25 * Legacy v1 adoption stays accepted until the secure-reset state machine lands.26 * v1 cannot establish the revocation guarantee, so the UI labels it27 * non-ejectable. Phase 3.1 replaces this constant with the durable reset state.28 */29private const val LEGACY_V1_ALLOWED = true3031/**32 * The v2 grant as it appears on the wire.33 *34 * It is deliberately NOT part of [AdoptionFrame]: the frozen v1 `Grant` carries35 * a required `source`, a sealed hierarchy can bind only one class to the36 * `ADOPT_GRANT` discriminator, and widening the v1 type to satisfy a v2 shape37 * would let v1-only code accept a grant it can never receive. The v2 transcript38 * therefore reads and writes this shape directly.39 */40@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"4950/**51 * What the RECEIVER (joining device) needs to adopt a vault over the v252 * transcript: the v1 surface plus the v2 additions. Extending the v1 interface53 * is what makes the union compile-time visible — delegating through a cast54 * would fail only once a peer triggered the missing callback.55 */56interface AdoptionReceiverV2Deps : AdoptionReceiverDeps {57    /** The receiver's durable device identity. Available with no vault present. */58    fun localIdentity(): LocalDeviceIdentity5960    suspend fun rotateLocalIdentity(): LocalDeviceIdentity6162    suspend fun validateSource(prepare: AdoptionFrame.Prepare)6364    suspend fun hasSourceIdentityCollision(prepare: AdoptionFrame.Prepare): Boolean65}6667/** What the SOURCE (existing device) needs to grant its vault over the v2 transcript. */68interface AdoptionSourceV2Deps : AdoptionSourceDeps {69    suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean7071    // Re-declared abstract: the v1 defaults would silently accept an unrotated72    // identity or throw only after a peer asked for the callback.73    override suspend fun rotateSourceIdentity(): LocalDeviceIdentity7475    override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean7677    /**78     * Durably record the validated receiver identity before any root-bearing79     * frame. Named apart from the v1 member, which is keyed on a request label.80     */81    suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long): Boolean8283    /** Promote the pending identity to a direct paired device. */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)106107/**108 * RECEIVER side: present our durable identity, then adopt the vault the source109 * prepares. Returns null on any protocol failure, with the reason via110 * [AdoptionReceiverV2Deps.onError].111 */112suspend fun requestAdoptionV2(113    channel: PairingTransport,114    deps: AdoptionReceiverV2Deps,115    // Called with the accepted ADOPT_PREPARE once it has been validated, so the116    // caller can read the source's capabilities before the root is granted.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    // A malformed root key must not escape as an exception; every failure here135    // is the same protocol outcome.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    // The source rejects our identity once if it is already in its terminal161    // ledger; we rotate exactly once and present the fresh identity.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    // The source's identity may be in our terminal ledger. Reject once, accept179    // only a rotated preparation, and treat a second collision as terminal.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    // Either the v2 grant or a terminal rejection.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    // The source may not change the vault between preparing and granting, and222    // the granted root key must actually derive that vault id.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    // The source is recorded from the validated preparation, never from the238    // grant: the preparation is what we validated against our terminal ledger.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}260261/**262 * SOURCE side: answer a v2 request. The receiver's validated identity is263 * durably recorded before any root-bearing frame, and is promoted to a direct264 * paired device only once the receiver acknowledges the vault.265 */266suspend 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    // Acknowledge before asking the human, so the receiver can raise its own275    // SAS prompt instead of waiting on this device's consent dialog.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    // The receiver's identity may collide with a paired device or a terminal296    // revocation. Reject once, accept only a rotated request, then stop.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    // No root-bearing frame before this commit: afterwards the receiver is320    // listable and revocable even if the session dies mid-grant.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    // Sent with its own serializer: the v2 grant carries no source, so it is359    // not a member of the AdoptionFrame hierarchy (see AdoptGrantV2).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    // Promotion is legal only now: the receiver holds the vault and has said so.375    if (!deps.completePendingIdentity(receiver)) return null376    deps.upsertPairedDevice(receiver)377    sendFrame(channel, AdoptionFrame.Complete)378    return receiver379}