VaultAdopt.kt

34.8 KB · raw

1package com.peachpasswords.sync23import kotlinx.serialization.SerialName4import kotlinx.serialization.Serializable5import kotlinx.serialization.encodeToString6import kotlinx.serialization.json.Json78/**9 * Vault adoption frame protocol — exact port of the browser `shared/vault-adopt.ts`.10 *11 * Adoption lets a brand-new device join an existing vault: the SOURCE (an already12 * set-up device) hands its root key to the RECEIVER over the pairing channel so13 * both devices end up with the same vault id and can sync. The receiver seals an14 * empty local vault under its own password but reuses the adopted root key15 * ([VaultRepository.createVaultFromRootKey]).16 *17 * Frames travel as JSON with a `type` discriminator and SNAKE_CASE keys — unlike18 * the camelCase [SyncMessage] sync wire — so the keys must match the browser19 * byte-for-byte for cross-platform adoption. Optional fields are omitted when20 * absent (encodeDefaults = false) to mirror `JSON.stringify` dropping `undefined`.21 */22@Serializable23sealed class AdoptionFrame {24    /**25     * [sessionRequestId] carries the wire's `device_id`, but it is NOT an26     * identity: the requester generates it locally before the handshake that27     * establishes any long-term key, so it cannot be the device's real one28     * (see `PEACH_RELAY_AND_DEVICEID_FIXES.md` Part 2). It is a label for the29     * consent prompt and nothing else — never persist it, never compare it30     * against a previous attempt's, never key trust on it. The only identity31     * that may be persisted is `long_term_public_key_hex`, which arrives later32     * in ADOPT_IDENTITY / ADOPT_GRANT.source.33     */34    @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        // SOURCE echoes receiver's ADOPT_REQUEST.snapshot_capable so the receiver58        // can skip its 15s inline-snapshot wait when the source has nothing to send.59        // Default false is OMITTED on the wire (encodeDefaults = false) — the60        // browser always serializes explicit true OR false via JSON.stringify, but61        // Android only serializes true; both receivers default to "skip wait" when62        // the field is absent, so the divergence is invisible to the gate.63        // Pre-C sources never set the field and decode to false here.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    /**78     * Encrypted source-to-receiver acknowledgement emitted only after the source79     * has durably recorded the receiver. The receiver cannot truthfully report a80     * successful pair before this arrives.81     */82    @Serializable83    @SerialName("ADOPT_COMPLETE")84    data object Complete : AdoptionFrame()8586    /** Encrypted receiver-to-source acknowledgement after the source row is durable. */87    @Serializable88    @SerialName("ADOPT_APPLIED")89    data object Applied : AdoptionFrame()9091    /** Neither peer proved Pro, so the pairing must not commit. */92    @Serializable93    @SerialName("ADOPT_REJECT")94    data class Reject(95        val reason: String,96    ) : AdoptionFrame()9798    /**99     * One chunk of the inline vault snapshot sent by the source after100     * ADOPT_APPLIED over the same authenticated Noise NK channel. Entries are101     * opaque base64 ciphertext envelopes; tombstones ride the final chunk only.102     */103    @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    /** Receiver acknowledgement sent after all snapshot chunks are applied. */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    /** Optional signed device graph appended after the snapshot (manifest v3+). */122    @Serializable123    @SerialName("ADOPT_DEVICE_MANIFEST")124    data class DeviceManifestFrame(125        val manifest: SignedDeviceManifest,126    ) : AdoptionFrame()127128    /** Receiver acknowledgement for an applied device manifest. */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)149150/**151 * Receiver-side reassembly result from [receiveVaultSnapshot]. Carries the152 * aggregated entries and tombstones plus the optional browser duress slot153 * JSON (present on the final chunk only, when the source has duress configured).154 */155data class ReceivedSnapshot(156    val entries: Map<String, String>,157    val tombstones: Map<String, Long>,158    val duressSlot: String? = null,159)160161/**162 * Wire guardrails for the inline snapshot. A chunk's serialized entries map163 * stays under [MAX_SNAPSHOT_CHUNK_BYTES]; the whole transfer is capped at164 * [MAX_SNAPSHOT_CHUNKS] frames so a compromised source cannot exhaust receiver165 * memory (mirrors SYNC_LIMITS.MAX_FRAME_BYTES in the sync coordinator).166 */167const val MAX_SNAPSHOT_CHUNK_BYTES = 512 * 1024 // 512 KiB168const val MAX_SNAPSHOT_CHUNKS = 200169170// Headroom added to the per-chunk entries budget when validating an encoded171// frame on the wire: JSON envelope plus the final chunk's tombstone map.172internal 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)174175/**176 * PB-26-206 aggregate budget shared by sender and receiver — exact mirror of177 * the browser's `vault-adopt.ts` ceilings. The per-frame guard above bounds178 * one frame; this bounds the whole transfer independently of the 200-frame179 * count, so many individually valid frames cannot OOM the receiver.180 */181const val MAX_ADOPT_SNAPSHOT_BYTES = 10 * 1024 * 1024 // 10 MiB182const val MAX_ADOPT_SNAPSHOT_ENTRIES = 25_000183const val MAX_ADOPT_SNAPSHOT_TOMBSTONES = 25_000184/** Same value as [SyncLimits.MAX_ID_LENGTH]; named here so vectors read identically on both clients. */185const val MAX_ADOPT_SNAPSHOT_ID_CHARS = SyncLimits.MAX_ID_LENGTH186/**187 * Maximum encrypted entry envelope: plaintext ceiling plus the existing188 * base64 overhead allowance. Int arithmetic gives 699,114 — the browser's189 * float comparison accepts and rejects at exactly the same lengths.190 */191const val MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES = SyncLimits.MAX_ENTRY_ENVELOPE_BYTES192193/**194 * Running aggregate for one snapshot transfer. Counts ride alongside the maps195 * (never re-derived per frame) so the bound stays O(n).196 */197class AdoptSnapshotBudget {198    val entries = LinkedHashMap<String, String>()199    val tombstones = LinkedHashMap<String, Long>()200    var duressSlot: String? = null201    /** Sum of encoded wire-frame bytes consumed so far. */202    var bytes: Int = 0203    var entryCount: Int = 0204    var tombstoneCount: Int = 0205}206207fun createAdoptSnapshotBudget(): AdoptSnapshotBudget = AdoptSnapshotBudget()208209/**210 * PB-26-206 shared preflight/merge helper used by BOTH the sender (preflight211 * before the first frame goes out) and the receiver (per frame, after the212 * byte-budget check, before decoded maps are merged).213 *214 * One bounded pass per attacker-controlled map: each key/value is validated215 * and projected counts are enforced inside the same loop that merges, so the216 * maps are never iterated count→size→merge repeatedly. Throws before merging217 * the offending frame, leaving no partial adopted state.218 */219fun 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        // Long is always finite, so non-finite hostile JSON dies at the243        // strict codec decode before reaching this merge (see V7).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        // The duress slot rides inside wire frames already bounded by the252        // frame ceiling, and its raw bytes count against the aggregate above.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}260261/** What the RECEIVER (joining device) needs to adopt a vault from a source. */262interface AdoptionReceiverDeps {263    val deviceName: String264    val deviceType: DeviceType265    fun generateDeviceId(): String266    /** Root-key transfer cannot begin until this device confirms the SAS. */267    suspend fun confirmSas(): Boolean268    /**269     * Local safety policy evaluated after the authenticated grant is validated270     * but before any vault state changes.271     */272    suspend fun validateSource(source: AdoptionFrame.Source) {}273274    /**275     * True when the source's identity (from ADOPT_GRANT) is in the local276     * terminal revocation ledger. When true, the receiver sends277     * ADOPT_DEVICE_ID_COLLISION so the source rotates and resends the grant.278     */279    suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean = false280281    /** Seal a fresh local vault under the receiver's password, reusing [rootKeyHex]. Returns the vault id. */282    suspend fun createVaultFromRootKey(rootKeyHex: String): String283    /** Build the receiver's local identity after the adopted vault exists. */284    suspend fun deriveLocalIdentity(): LocalDeviceIdentity285    /** Persist the direct pairing and lift its terminal revocation as one store operation. */286    suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {287        upsertPairedDevice(device)288        clearPairedDeviceRevocation(device.deviceId)289    }290    suspend fun clearPairedDeviceRevocation(deviceId: String) {}291    suspend fun upsertPairedDevice(device: PairedDevice)292    suspend fun applyLicense(license: String) {}293    /** Return this receiver's locally validated Pro key, if present. */294    suspend fun license(): String? = null295    val pairState: AdoptionPairState? get() = null296    fun onError(error: String)297    /** Apply encrypted entries + tombstones from the inline snapshot. */298    suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}299    /**300     * Apply the source's signed device graph so the receiver graduates into the301     * mesh. The [authenticatedRemoteStaticPublicKey] is the source's Noise302     * transport static key (NOT the signing key); [applyIncomingDeviceManifest]303     * resolves it to the source's [PairedDevice] locally and uses the stored304     * signing key to verify the manifest signature. Default no-op preserves305     * the contract for callers that haven't wired the mesh path yet.306     */307    suspend fun applyIncomingDeviceManifest(308        manifest: SignedDeviceManifest,309        authenticatedRemoteStaticPublicKey: ByteArray,310    ) {}311    /** Mark the paired device as synced after a successful snapshot. */312    suspend fun markSynced(deviceId: String) {}313}314315/** What the SOURCE (existing device) needs to grant its vault to a receiver. */316interface AdoptionSourceDeps {317    val sourceIdentity: LocalDeviceIdentity318    suspend fun rootKeyHex(): String319    suspend fun vaultId(): String320    suspend fun license(): String? = null321    /** Validate and durably store a Pro key offered by the receiver. */322    suspend fun applyLicense(license: String) {}323324    /**325     * Ask the user to approve handing this vault to the requesting device. The326     * request's name/type/label are for the human to read; the decision must not327     * be made by recognising [AdoptionFrame.Request.sessionRequestId], which328     * carries no continuity between attempts.329     */330    suspend fun onConsent(request: AdoptionFrame.Request): Boolean331    suspend fun upsertPairedDevice(device: PairedDevice)332    fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false333    /**334     * Rotate the source's identity after the receiver reports a collision on335     * the source's own identity. Returns the fresh identity for the resent336     * ADOPT_GRANT.337     */338    suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")339    val pairState: AdoptionPairState? get() = null340    /** Return all encrypted entries + tombstones for the inline snapshot. */341    suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null342    /** Return the signed device manifest for the graph, if available. */343    suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null344    /** Mark the paired device as synced after a successful snapshot. */345    suspend fun markSynced(deviceId: String) {}346    /** Browser-shaped sealed duress slot JSON for the snapshot, if duress is configured. */347    suspend fun duressSlotJson(): String? = null348}349350private val Hex64 = Regex("^[0-9a-f]{64}\$")351352fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)353354fun isAdoptRequest(frame: AdoptionFrame?): Boolean =355    frame is AdoptionFrame.Request &&356        frame.sessionRequestId.isNotEmpty() &&357        isDeviceType(frame.deviceType)358359fun isAdoptGrant(frame: AdoptionFrame?): Boolean =360    frame is AdoptionFrame.Grant &&361        validateRootKeyHex(frame.rootKeyHex) &&362        Hex64.matches(frame.vaultId) &&363        isDeviceType(frame.source.deviceType) &&364        Hex64.matches(frame.source.longTermPublicKeyHex) &&365        (frame.source.relayUrl == null ||366            runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)367368fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =369    frame is AdoptionFrame.Confirm370371fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =372    frame is AdoptionFrame.Identity &&373        frame.deviceId.isNotEmpty() &&374        isDeviceType(frame.deviceType) &&375        Hex64.matches(frame.longTermPublicKeyHex)376377fun isAdoptComplete(frame: AdoptionFrame?): Boolean =378    frame is AdoptionFrame.Complete379380fun isAdoptApplied(frame: AdoptionFrame?): Boolean =381    frame is AdoptionFrame.Applied382383fun isAdoptReject(frame: AdoptionFrame?): Boolean =384    frame is AdoptionFrame.Reject &&385        (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")386387fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =388    frame is AdoptionFrame.Snapshot &&389        frame.chunkIndex >= 0 &&390        frame.chunkCount >= 1391392/**393 * RECEIVER side: ask a source to adopt us. Sends ADOPT_REQUEST, verifies the394 * granted root key actually derives the advertised vault id (catching a lying or395 * corrupted source before it can seal a mismatched vault), seals the local vault,396 * applies any carried license, returns our identity, and records the source as a397 * paired device. Returns null on any protocol failure (reason via [deps.onError]).398 */399suspend fun requestAdoption(400    channel: PairingTransport,401    deps: AdoptionReceiverDeps,402    // Called once after a valid ADOPT_GRANT is decoded and validated, before403    // any side effects (vault creation, paired-device upsert). Used by the404    // receiver to inspect the grant's snapshot_capable flag and skip the 15s405    // inline-snapshot wait when the source has nothing to send. Defaults to no-op406    // for callers (tests, other helpers) that don't need to inspect the grant.407    onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,408    nowMs: () -> Long = { System.currentTimeMillis() },409): PairedDevice? {410    val receiverLicense = deps.license()411    // Fresh every attempt, and deliberately not our real device id: no identity412    // exists yet at this point in the protocol.413    sendFrame(channel, AdoptionFrame.Request(414        sessionRequestId = deps.generateDeviceId(),415        deviceName = deps.deviceName,416        deviceType = deps.deviceType.wireValue,417        license = receiverLicense,418        snapshotCapable = true,419    ))420421    val confirmed = deps.confirmSas()422    sendFrame(channel, AdoptionFrame.Confirm(confirmed))423    if (!confirmed) {424        deps.onError("ADOPT_SAS_REJECTED")425        return null426    }427428    val frame = receiveFrame(channel)429    if (isAdoptReject(frame)) {430        deps.onError((frame as AdoptionFrame.Reject).reason)431        return null432    }433    if (!isAdoptGrant(frame)) {434        deps.onError("ADOPT_UNEXPECTED_FRAME")435        return null436    }437    val grant = frame as AdoptionFrame.Grant438    onGrant?.invoke(grant)439440    val rootKeyBytes = hexToPubkey(grant.rootKeyHex)441    try {442        if (computeVaultId(rootKeyBytes) != grant.vaultId) {443            deps.onError("ADOPT_VAULT_ID_MISMATCH")444            return null445        }446    } finally {447        rootKeyBytes.fill(0)448    }449    if (receiverLicense == null && grant.license == null) {450        deps.onError("ADOPT_PRO_REQUIRED")451        return null452    }453454    deps.validateSource(grant.source)455456    // Check the source's identity against the local revocation ledger. A457    // previously-revoked device must present a fresh identity so that stale458    // signed revocations held by other mesh peers cannot remove it after459    // re-pair. If the source's identity is revoked, send ADOPT_DEVICE_ID_COLLISION460    // and wait for a fresh grant (one retry).461    var acceptedGrant = grant462    if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {463        sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))464        val retry = receiveFrame(channel)465        if (!isAdoptGrant(retry)) {466            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")467            return null468        }469        acceptedGrant = retry as AdoptionFrame.Grant470        if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {471            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))472            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")473            return null474        }475        // Re-validate the fresh grant's vault id.476        val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)477        try {478            if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {479                deps.onError("ADOPT_VAULT_ID_MISMATCH")480                return null481            }482        } finally {483            freshRootBytes.fill(0)484        }485    }486    if (receiverLicense == null && acceptedGrant.license == null) {487        deps.onError("ADOPT_PRO_REQUIRED")488        return null489    }490491492    if (receiverLicense == null) {493        acceptedGrant.license?.let { deps.applyLicense(it) }494    }495    val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)496    if (vaultId != acceptedGrant.vaultId) {497        deps.onError("ADOPT_VAULT_ID_MISMATCH")498        return null499    }500501502    val identity = deps.deriveLocalIdentity()503    sendFrame(channel, AdoptionFrame.Identity(504        deviceId = identity.deviceId,505        deviceName = identity.deviceName,506        deviceType = identity.deviceType.wireValue,507        longTermPublicKeyHex = identity.longTermPublicKeyHex,508        signingPublicKeyHex = identity.signingPublicKeyHex,509    ))510511    if (!isAdoptComplete(receiveFrame(channel))) {512        deps.onError("ADOPT_COMPLETION_MISSING")513        return null514    }515516    val sourceDevice = PairedDevice(517        deviceId = acceptedGrant.source.deviceId,518        deviceName = acceptedGrant.source.deviceName,519        deviceType = acceptedGrant.source.deviceType,520        longTermPublicKeyHex = acceptedGrant.source.longTermPublicKeyHex,521        signingPublicKeyHex = acceptedGrant.source.signingPublicKeyHex,522        trustSource = "direct",523        wsPort = acceptedGrant.source.wsPort,524        rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,525        relayUrl = deps.pairState?.relayUrl ?: acceptedGrant.source.relayUrl,526        pairedAt = nowMs(),527    )528    // A physically confirmed direct re-pair is the sole path allowed to lift529    // terminal revocation. The registry validates identity before either value530    // is changed, so a mismatch leaves the revocation intact.531    deps.upsertPairedDeviceAndClearRevocation(sourceDevice)532    sendFrame(channel, AdoptionFrame.Applied)533    return sourceDevice534}535536/**537 * SOURCE side: respond to an ADOPT_REQUEST. Gates on user consent, hands over the538 * root key, then records the receiver's returned identity as a paired device.539 * Returns null if consent is denied or the receiver's identity frame is invalid.540 */541suspend fun grantAdoption(542    channel: PairingTransport,543    request: AdoptionFrame.Request,544    deps: AdoptionSourceDeps,545    nowMs: () -> Long = { System.currentTimeMillis() },546): PairedDevice? {547    if (!deps.onConsent(request)) return null548549    val confirmation = receiveFrame(channel)550    if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {551        return null552    }553554    var sourceLicense = deps.license()555    if (sourceLicense == null && request.license != null) {556        sourceLicense = runCatching {557            deps.applyLicense(request.license)558            deps.license()559        }.getOrNull()560    }561    if (sourceLicense == null) {562        sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))563        throw IllegalStateException("ADOPT_PRO_REQUIRED")564    }565566    val rootKeyHex = deps.rootKeyHex()567    if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")568569    var sourceIdentity = deps.sourceIdentity570    var grantAttempts = 0571    while (true) {572        sendFrame(channel, AdoptionFrame.Grant(573            rootKeyHex = rootKeyHex,574            vaultId = deps.vaultId(),575            license = sourceLicense,576            source = AdoptionFrame.Source(577                deviceId = sourceIdentity.deviceId,578                deviceName = sourceIdentity.deviceName,579                deviceType = sourceIdentity.deviceType.wireValue,580                longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,581                signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,582                wsPort = sourceIdentity.wsPort,583                relayUrl = deps.pairState?.relayUrl,584            ),585            snapshotCapable = request.snapshotCapable == true,586        ))587588        var identity = receiveFrame(channel)589590        // Receiver may reject the source's identity if it is in the receiver's591        // revocation ledger. Rotate and resend (one retry).592        if (identity is AdoptionFrame.Reject &&593            identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&594            grantAttempts == 0595        ) {596            sourceIdentity = deps.rotateSourceIdentity()597            grantAttempts++598            continue599        }600601        if (!isAdoptIdentity(identity)) return null602        identity as AdoptionFrame.Identity603604        var device = PairedDevice(605            deviceId = identity.deviceId,606            deviceName = identity.deviceName,607            deviceType = identity.deviceType,608            longTermPublicKeyHex = identity.longTermPublicKeyHex,609            signingPublicKeyHex = identity.signingPublicKeyHex,610            trustSource = "direct",611            rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,612            relayUrl = deps.pairState?.relayUrl,613            pairedAt = nowMs(),614        )615        if (deps.hasDeviceIdentityCollision(device)) {616            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))617            identity = receiveFrame(channel)618            if (!isAdoptIdentity(identity)) return null619            identity as AdoptionFrame.Identity620            device = device.copy(621                deviceId = identity.deviceId,622                deviceName = identity.deviceName,623                deviceType = identity.deviceType,624                longTermPublicKeyHex = identity.longTermPublicKeyHex,625                signingPublicKeyHex = identity.signingPublicKeyHex,626            )627            if (deps.hasDeviceIdentityCollision(device)) {628                sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))629                return null630            }631        }632        deps.upsertPairedDevice(device)633        sendFrame(channel, AdoptionFrame.Complete)634        if (!isAdoptApplied(receiveFrame(channel))) return null635        return device636    }637}638639/**640 * Wire codec. `classDiscriminator = "type"` reproduces the browser's flat641 * `{ "type": "ADOPT_…", … }` shape; `encodeDefaults = false` omits absent642 * optionals exactly like `JSON.stringify` drops `undefined`.643 */644val AdoptJson: Json = Json {645    classDiscriminator = "type"646    encodeDefaults = false647    ignoreUnknownKeys = true648}649650suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {651    channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))652}653654/** Decode one frame, tolerating a malformed/unknown payload by returning null. */655suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =656    runCatching {657        AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))658    }.getOrNull()659660/**661 * Source side: chunk the vault snapshot and send it over the pairing channel.662 *663 * Wire shape (v2.9.9+, supplemental frame; mirrors browser v4.6.4):664 *   - N entries frames, each <= [MAX_SNAPSHOT_CHUNK_BYTES] serialized entries.665 *   - One supplemental frame always follows the entries. It carries the666 *     tombstones and, when configured, the duress slot. Sending the same frame667 *     count in both cases prevents a relay from learning duress presence.668 *     Keeping duress off the entries frame also prevents a sizeable sealed669 *     duress vault from pushing the entries frame over the wire ceiling.670 *671 * Frame budget ([MAX_SNAPSHOT_CHUNKS] = 200):672 *   - ONE of the 200 frames is always reserved for the supplemental frame;673 *     entries use at most 199 chunks. Excess entries are deferred to the sync674 *     fallback pipeline (sync carries entries and tombstones on Android too,675 *     so this is a graceful truncation). The supplemental frame is required676 *     even without duress so its presence cannot disclose configuration. When677 *     configured, it carries the duress slot; omitting it would leave the678 *     adopted device permanently without its duress vault.679 *680 * Oversized duress: duress that itself exceeds [SNAPSHOT_FRAME_WIRE_CEILING]681 * is rejected with a thrown error BEFORE any snapshot frame is sent. Hard stop;682 * the caller must split duress out of band. We do not silently truncate683 * duress; sync cannot restore it.684 *685 * Backward compat: pre-v2.9.9 senders put `duress_slot` on the entries686 * final chunk. `receiveVaultSnapshot` reads `duress_slot` off any chunk (a687 * duress-only frame has empty `entries` and the complete tombstone map),688 * so both shapes decode and both new->old / old->new directions interoperate.689 */690suspend fun sendVaultSnapshot(691    channel: PairingTransport,692    entries: Map<String, String>,693    tombstones: Map<String, Long>,694    duressSlot: String? = null,695) {696    val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)697    // PB-26-206 preflight with the SAME helper the receiver enforces: nothing698    // is sent until every frame fits the aggregate budget, so an over-budget699    // snapshot is never partially sent or silently truncated. The caller falls700    // through to the regular sync pipeline (deny-only: no wire-field change,701    // invitation prefix unchanged).702    val acc = createAdoptSnapshotBudget()703    val encoded = frames.map {704        AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()705    }706    for (i in frames.indices) {707        val frame = frames[i]708        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)709    }710    for (raw in encoded) channel.send(SyncPadding.pad(raw))711}712713/**714 * Pure frame construction for [sendVaultSnapshot]: chunking, the duress-frame715 * reservation, and the oversized-duress hard stop. No I/O happens here, so716 * the preflight above can reject before the first byte goes out.717 */718private fun buildAdoptSnapshotFrames(719    entries: Map<String, String>,720    tombstones: Map<String, Long>,721    duressSlot: String?,722): List<AdoptionFrame.Snapshot> {723    val includeDuress = !duressSlot.isNullOrBlank()724    // Always reserve the supplemental frame so its presence cannot disclose725    // whether the source has a duress vault.726    val entryCap = MAX_SNAPSHOT_CHUNKS - 1727728    val chunks = mutableListOf<Map<String, String>>()729    var current = LinkedHashMap<String, String>()730    var currentBytes = 2 // "{}"731    for ((id, envelope) in entries) {732        // +1 for the separating comma; an overestimate only shrinks chunks.733        val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1734        if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {735            chunks.add(current)736            current = LinkedHashMap()737            currentBytes = 2738        }739        current[id] = envelope740        currentBytes += entryBytes741    }742    chunks.add(current)743744    val entriesChunkCount = minOf(chunks.size, entryCap)745    val totalChunks = entriesChunkCount + 1746    val supplementalFrame = AdoptionFrame.Snapshot(747        chunkIndex = entriesChunkCount,748        chunkCount = totalChunks,749        entries = emptyMap(),750        tombstones = tombstones,751        duressSlot = duressSlot.takeIf { includeDuress },752    )753754    if (755        AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)756            .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING757    ) {758        if (includeDuress) throw SnapshotDuressFrameTooLargeException()759        throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")760    }761762    val frames = mutableListOf<AdoptionFrame.Snapshot>()763    for (index in 0 until entriesChunkCount) {764        frames.add(AdoptionFrame.Snapshot(765            chunkIndex = index,766            chunkCount = totalChunks,767            entries = chunks[index],768            tombstones = emptyMap(),769            duressSlot = null,770        ))771    }772    frames.add(supplementalFrame)773    return frames774}775776internal class SnapshotDuressFrameTooLargeException :777    IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")778779/**780 * Receiver side: receive and reassemble every snapshot chunk. Adds raw frame781 * bytes to the aggregate counter before decoding (rejecting before JSON782 * deserialization when the next frame exceeds the remaining budget), then783 * enforces the per-frame wire ceiling, sequential 0-based chunk_index784 * ordering, a stable chunk_count within [MAX_SNAPSHOT_CHUNKS], and structural785 * validity of each frame. Merging goes through the shared aggregate helper:786 * every key/value and projected count is validated in one bounded pass before787 * anything lands in the accumulator, so a rejection leaves no partial adopted788 * state and the caller can fall back to the sync pipeline.789 */790suspend fun receiveVaultSnapshot(791    channel: PairingTransport,792): ReceivedSnapshot {793    val acc = createAdoptSnapshotBudget()794    var chunkCount = -1795    var received = 0796    while (chunkCount == -1 || received < chunkCount) {797        val wire = channel.receive()798        if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {799            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")800        }801        val raw = runCatching { SyncPadding.unpad(wire) }802            .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }803        if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {804            throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")805        }806        if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {807            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")808        }809        val frame = runCatching {810            AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))811        }.getOrNull()812        if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")813        frame as AdoptionFrame.Snapshot814        if (chunkCount == -1) {815            chunkCount = frame.chunkCount816            if (chunkCount > MAX_SNAPSHOT_CHUNKS) {817                throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")818            }819        } else if (frame.chunkCount != chunkCount) {820            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")821        }822        if (frame.chunkIndex != received) {823            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")824        }825        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)826        received++827    }828    return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)829}830831private fun isDeviceType(value: String): Boolean =832    DeviceType.entries.any { it.wireValue == value }