AdoptionProtocol.kt

17.5 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_ALLOWED9293/**94 * Bind a source session's deps to the live session facts.95 *96 * Both relay source adapters — the phone showing a QR, and the phone scanning an97 * empty invitation — build the same object; the only differences are which98 * identity is presented and whether snapshot support is advertised, so both are99 * parameters rather than two near-identical anonymous objects.100 *101 * Extracted from the session functions so §10.5 can be proven: the test dirties102 * every member here and asserts each one reaches its sink. A callback that is103 * dropped, or one that returns without calling through, fails that test.104 */105internal 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    // The transcript sends ADOPT_CONFIRM_REQUIRED before calling this, so the122    // receiver's own prompt is already live when we ask our human to compare the123    // same SAS. The request is only a prompt label here — but the call MUST124    // reach `confirm`: returning true without it was a real defect, because the125    // source-side prompt then never appeared.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)177178/**179 * RECEIVER side: present our durable identity, then adopt the vault the source180 * prepares. Returns null on any protocol failure, with the reason via181 * [AdoptionReceiverV2Deps.onError].182 */183suspend fun requestAdoptionV2(184    channel: PairingTransport,185    deps: AdoptionReceiverV2Deps,186    // Called with the accepted ADOPT_PREPARE once it has been validated, so the187    // caller can read the source's capabilities before the root is granted.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    // A malformed root key must not escape as an exception; every failure here206    // is the same protocol outcome.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    // The source rejects our identity once if it is already in its terminal232    // ledger; we rotate exactly once and present the fresh identity.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    // The source's identity may be in our terminal ledger. Reject once, accept250    // only a rotated preparation, and treat a second collision as terminal.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    // Either the v2 grant or a terminal rejection.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    // The source may not change the vault between preparing and granting, and293    // the granted root key must actually derive that vault id.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    // The source is recorded from the validated preparation, never from the309    // grant: the preparation is what we validated against our terminal ledger.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}331332/**333 * SOURCE side: answer a v2 request. The receiver's validated identity is334 * durably recorded before any root-bearing frame, and is promoted to a direct335 * paired device only once the receiver acknowledges the vault.336 */337suspend 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    // Acknowledge before asking the human, so the receiver can raise its own346    // SAS prompt instead of waiting on this device's consent dialog.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    // The receiver's identity may collide with a paired device or a terminal367    // revocation. Reject once, accept only a rotated request, then stop.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    // No root-bearing frame before this commit: afterwards the receiver is391    // listable and revocable even if the session dies mid-grant.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    // Sent with its own serializer: the v2 grant carries no source, so it is430    // not a member of the AdoptionFrame hierarchy (see AdoptGrantV2).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    // Promotion is legal only now: the receiver holds the vault and has said so.446    if (!deps.completePendingIdentity(receiver)) return null447    deps.upsertPairedDevice(receiver)448    sendFrame(channel, AdoptionFrame.Complete)449    return receiver450}