VaultAdopt.kt

31.7 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    /** Seal a fresh local vault under the receiver's password, reusing [rootKeyHex]. Returns the vault id. */275    suspend fun createVaultFromRootKey(rootKeyHex: String): String276    suspend fun deriveLocalIdentity(): LocalDeviceIdentity277    /** Only called after a successful, SAS-confirmed direct pairing. */278    suspend fun clearPairedDeviceRevocation(deviceId: String) {}279    suspend fun upsertPairedDevice(device: PairedDevice)280    suspend fun applyLicense(license: String) {}281    /** Return this receiver's locally validated Pro key, if present. */282    suspend fun license(): String? = null283    val pairState: AdoptionPairState? get() = null284    fun onError(error: String)285    /** Apply encrypted entries + tombstones from the inline snapshot. */286    suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}287    /**288     * Apply the source's signed device graph so the receiver graduates into the289     * mesh. The [authenticatedRemoteStaticPublicKey] is the source's Noise290     * transport static key (NOT the signing key); [applyIncomingDeviceManifest]291     * resolves it to the source's [PairedDevice] locally and uses the stored292     * signing key to verify the manifest signature. Default no-op preserves293     * the contract for callers that haven't wired the mesh path yet.294     */295    suspend fun applyIncomingDeviceManifest(296        manifest: SignedDeviceManifest,297        authenticatedRemoteStaticPublicKey: ByteArray,298    ) {}299    /** Mark the paired device as synced after a successful snapshot. */300    suspend fun markSynced(deviceId: String) {}301}302303/** What the SOURCE (existing device) needs to grant its vault to a receiver. */304interface AdoptionSourceDeps {305    val sourceIdentity: LocalDeviceIdentity306    suspend fun rootKeyHex(): String307    suspend fun vaultId(): String308    suspend fun license(): String? = null309    /** Validate and durably store a Pro key offered by the receiver. */310    suspend fun applyLicense(license: String) {}311312    /**313     * Ask the user to approve handing this vault to the requesting device. The314     * request's name/type/label are for the human to read; the decision must not315     * be made by recognising [AdoptionFrame.Request.sessionRequestId], which316     * carries no continuity between attempts.317     */318    suspend fun onConsent(request: AdoptionFrame.Request): Boolean319    suspend fun upsertPairedDevice(device: PairedDevice)320    fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false321    val pairState: AdoptionPairState? get() = null322    /** Return all encrypted entries + tombstones for the inline snapshot. */323    suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null324    /** Return the signed device manifest for the graph, if available. */325    suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null326    /** Mark the paired device as synced after a successful snapshot. */327    suspend fun markSynced(deviceId: String) {}328    /** Browser-shaped sealed duress slot JSON for the snapshot, if duress is configured. */329    suspend fun duressSlotJson(): String? = null330}331332private val Hex64 = Regex("^[0-9a-f]{64}\$")333334fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)335336fun isAdoptRequest(frame: AdoptionFrame?): Boolean =337    frame is AdoptionFrame.Request &&338        frame.sessionRequestId.isNotEmpty() &&339        isDeviceType(frame.deviceType)340341fun isAdoptGrant(frame: AdoptionFrame?): Boolean =342    frame is AdoptionFrame.Grant &&343        validateRootKeyHex(frame.rootKeyHex) &&344        Hex64.matches(frame.vaultId) &&345        isDeviceType(frame.source.deviceType) &&346        Hex64.matches(frame.source.longTermPublicKeyHex) &&347        (frame.source.relayUrl == null ||348            runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)349350fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =351    frame is AdoptionFrame.Confirm352353fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =354    frame is AdoptionFrame.Identity &&355        frame.deviceId.isNotEmpty() &&356        isDeviceType(frame.deviceType) &&357        Hex64.matches(frame.longTermPublicKeyHex)358359fun isAdoptComplete(frame: AdoptionFrame?): Boolean =360    frame is AdoptionFrame.Complete361362fun isAdoptApplied(frame: AdoptionFrame?): Boolean =363    frame is AdoptionFrame.Applied364365fun isAdoptReject(frame: AdoptionFrame?): Boolean =366    frame is AdoptionFrame.Reject && frame.reason == "ADOPT_PRO_REQUIRED"367368fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =369    frame is AdoptionFrame.Snapshot &&370        frame.chunkIndex >= 0 &&371        frame.chunkCount >= 1372373/**374 * RECEIVER side: ask a source to adopt us. Sends ADOPT_REQUEST, verifies the375 * granted root key actually derives the advertised vault id (catching a lying or376 * corrupted source before it can seal a mismatched vault), seals the local vault,377 * applies any carried license, returns our identity, and records the source as a378 * paired device. Returns null on any protocol failure (reason via [deps.onError]).379 */380suspend fun requestAdoption(381    channel: PairingTransport,382    deps: AdoptionReceiverDeps,383    // Called once after a valid ADOPT_GRANT is decoded and validated, before384    // any side effects (vault creation, paired-device upsert). Used by the385    // receiver to inspect the grant's snapshot_capable flag and skip the 15s386    // inline-snapshot wait when the source has nothing to send. Defaults to no-op387    // for callers (tests, other helpers) that don't need to inspect the grant.388    onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,389    nowMs: () -> Long = { System.currentTimeMillis() },390): PairedDevice? {391    val receiverLicense = deps.license()392    // Fresh every attempt, and deliberately not our real device id: no identity393    // exists yet at this point in the protocol.394    sendFrame(channel, AdoptionFrame.Request(395        sessionRequestId = deps.generateDeviceId(),396        deviceName = deps.deviceName,397        deviceType = deps.deviceType.wireValue,398        license = receiverLicense,399        snapshotCapable = true,400    ))401402    val confirmed = deps.confirmSas()403    sendFrame(channel, AdoptionFrame.Confirm(confirmed))404    if (!confirmed) {405        deps.onError("ADOPT_SAS_REJECTED")406        return null407    }408409    val frame = receiveFrame(channel)410    if (isAdoptReject(frame)) {411        deps.onError((frame as AdoptionFrame.Reject).reason)412        return null413    }414    if (!isAdoptGrant(frame)) {415        deps.onError("ADOPT_UNEXPECTED_FRAME")416        return null417    }418    val grant = frame as AdoptionFrame.Grant419    onGrant?.invoke(grant)420421    val rootKeyBytes = hexToPubkey(grant.rootKeyHex)422    try {423        if (computeVaultId(rootKeyBytes) != grant.vaultId) {424            deps.onError("ADOPT_VAULT_ID_MISMATCH")425            return null426        }427    } finally {428        rootKeyBytes.fill(0)429    }430    if (receiverLicense == null && grant.license == null) {431        deps.onError("ADOPT_PRO_REQUIRED")432        return null433    }434435    deps.validateSource(grant.source)436    val vaultId = deps.createVaultFromRootKey(grant.rootKeyHex)437    if (vaultId != grant.vaultId) {438        deps.onError("ADOPT_VAULT_ID_MISMATCH")439        return null440    }441442    if (receiverLicense == null) {443        grant.license?.let { deps.applyLicense(it) }444    }445446    val identity = deps.deriveLocalIdentity()447    sendFrame(channel, AdoptionFrame.Identity(448        deviceId = identity.deviceId,449        deviceName = identity.deviceName,450        deviceType = identity.deviceType.wireValue,451        longTermPublicKeyHex = identity.longTermPublicKeyHex,452        signingPublicKeyHex = identity.signingPublicKeyHex,453    ))454455    if (!isAdoptComplete(receiveFrame(channel))) {456        deps.onError("ADOPT_COMPLETION_MISSING")457        return null458    }459460    val sourceDevice = PairedDevice(461        deviceId = grant.source.deviceId,462        deviceName = grant.source.deviceName,463        deviceType = grant.source.deviceType,464        longTermPublicKeyHex = grant.source.longTermPublicKeyHex,465        signingPublicKeyHex = grant.source.signingPublicKeyHex,466        trustSource = "direct",467        wsPort = grant.source.wsPort,468        rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,469        relayUrl = deps.pairState?.relayUrl ?: grant.source.relayUrl,470        pairedAt = nowMs(),471    )472    // A physically confirmed direct re-pair is the sole path allowed to lift473    // terminal revocation. Clear before upsert so storage can never expose the474    // source as both paired and revoked, even transiently.475    deps.clearPairedDeviceRevocation(sourceDevice.deviceId)476    deps.upsertPairedDevice(sourceDevice)477    sendFrame(channel, AdoptionFrame.Applied)478    return sourceDevice479}480481/**482 * SOURCE side: respond to an ADOPT_REQUEST. Gates on user consent, hands over the483 * root key, then records the receiver's returned identity as a paired device.484 * Returns null if consent is denied or the receiver's identity frame is invalid.485 */486suspend fun grantAdoption(487    channel: PairingTransport,488    request: AdoptionFrame.Request,489    deps: AdoptionSourceDeps,490    nowMs: () -> Long = { System.currentTimeMillis() },491): PairedDevice? {492    if (!deps.onConsent(request)) return null493494    val confirmation = receiveFrame(channel)495    if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {496        return null497    }498499    var sourceLicense = deps.license()500    if (sourceLicense == null && request.license != null) {501        sourceLicense = runCatching {502            deps.applyLicense(request.license)503            deps.license()504        }.getOrNull()505    }506    if (sourceLicense == null) {507        sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))508        throw IllegalStateException("ADOPT_PRO_REQUIRED")509    }510511    val rootKeyHex = deps.rootKeyHex()512    if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")513514    sendFrame(channel, AdoptionFrame.Grant(515        rootKeyHex = rootKeyHex,516        vaultId = deps.vaultId(),517        license = sourceLicense,518        source = AdoptionFrame.Source(519            deviceId = deps.sourceIdentity.deviceId,520            deviceName = deps.sourceIdentity.deviceName,521            deviceType = deps.sourceIdentity.deviceType.wireValue,522            longTermPublicKeyHex = deps.sourceIdentity.longTermPublicKeyHex,523            signingPublicKeyHex = deps.sourceIdentity.signingPublicKeyHex,524            wsPort = deps.sourceIdentity.wsPort,525            relayUrl = deps.pairState?.relayUrl,526        ),527        snapshotCapable = request.snapshotCapable == true,528    ))529530    var identity = receiveFrame(channel)531    if (!isAdoptIdentity(identity)) return null532    identity as AdoptionFrame.Identity533534    var device = PairedDevice(535        deviceId = identity.deviceId,536        deviceName = identity.deviceName,537        deviceType = identity.deviceType,538        longTermPublicKeyHex = identity.longTermPublicKeyHex,539        signingPublicKeyHex = identity.signingPublicKeyHex,540        trustSource = "direct",541        rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,542        relayUrl = deps.pairState?.relayUrl,543        pairedAt = nowMs(),544    )545    if (deps.hasDeviceIdentityCollision(device)) {546        sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))547        identity = receiveFrame(channel)548        if (!isAdoptIdentity(identity)) return null549        identity as AdoptionFrame.Identity550        device = device.copy(551            deviceId = identity.deviceId,552            deviceName = identity.deviceName,553            deviceType = identity.deviceType,554            longTermPublicKeyHex = identity.longTermPublicKeyHex,555            signingPublicKeyHex = identity.signingPublicKeyHex,556        )557        if (deps.hasDeviceIdentityCollision(device)) {558            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))559            return null560        }561    }562    deps.upsertPairedDevice(device)563    sendFrame(channel, AdoptionFrame.Complete)564    if (!isAdoptApplied(receiveFrame(channel))) return null565    return device566}567568/**569 * Wire codec. `classDiscriminator = "type"` reproduces the browser's flat570 * `{ "type": "ADOPT_…", … }` shape; `encodeDefaults = false` omits absent571 * optionals exactly like `JSON.stringify` drops `undefined`.572 */573val AdoptJson: Json = Json {574    classDiscriminator = "type"575    encodeDefaults = false576    ignoreUnknownKeys = true577}578579suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {580    channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))581}582583/** Decode one frame, tolerating a malformed/unknown payload by returning null. */584suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =585    runCatching {586        AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))587    }.getOrNull()588589/**590 * Source side: chunk the vault snapshot and send it over the pairing channel.591 *592 * Wire shape (v2.9.9+, supplemental frame; mirrors browser v4.6.4):593 *   - N entries frames, each <= [MAX_SNAPSHOT_CHUNK_BYTES] serialized entries.594 *   - One supplemental frame always follows the entries. It carries the595 *     tombstones and, when configured, the duress slot. Sending the same frame596 *     count in both cases prevents a relay from learning duress presence.597 *     Keeping duress off the entries frame also prevents a sizeable sealed598 *     duress vault from pushing the entries frame over the wire ceiling.599 *600 * Frame budget ([MAX_SNAPSHOT_CHUNKS] = 200):601 *   - ONE of the 200 frames is always reserved for the supplemental frame;602 *     entries use at most 199 chunks. Excess entries are deferred to the sync603 *     fallback pipeline (sync carries entries and tombstones on Android too,604 *     so this is a graceful truncation). The supplemental frame is required605 *     even without duress so its presence cannot disclose configuration. When606 *     configured, it carries the duress slot; omitting it would leave the607 *     adopted device permanently without its duress vault.608 *609 * Oversized duress: duress that itself exceeds [SNAPSHOT_FRAME_WIRE_CEILING]610 * is rejected with a thrown error BEFORE any snapshot frame is sent. Hard stop;611 * the caller must split duress out of band. We do not silently truncate612 * duress; sync cannot restore it.613 *614 * Backward compat: pre-v2.9.9 senders put `duress_slot` on the entries615 * final chunk. `receiveVaultSnapshot` reads `duress_slot` off any chunk (a616 * duress-only frame has empty `entries` and the complete tombstone map),617 * so both shapes decode and both new->old / old->new directions interoperate.618 */619suspend fun sendVaultSnapshot(620    channel: PairingTransport,621    entries: Map<String, String>,622    tombstones: Map<String, Long>,623    duressSlot: String? = null,624) {625    val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)626    // PB-26-206 preflight with the SAME helper the receiver enforces: nothing627    // is sent until every frame fits the aggregate budget, so an over-budget628    // snapshot is never partially sent or silently truncated. The caller falls629    // through to the regular sync pipeline (deny-only: no wire-field change,630    // invitation prefix unchanged).631    val acc = createAdoptSnapshotBudget()632    val encoded = frames.map {633        AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()634    }635    for (i in frames.indices) {636        val frame = frames[i]637        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)638    }639    for (raw in encoded) channel.send(SyncPadding.pad(raw))640}641642/**643 * Pure frame construction for [sendVaultSnapshot]: chunking, the duress-frame644 * reservation, and the oversized-duress hard stop. No I/O happens here, so645 * the preflight above can reject before the first byte goes out.646 */647private fun buildAdoptSnapshotFrames(648    entries: Map<String, String>,649    tombstones: Map<String, Long>,650    duressSlot: String?,651): List<AdoptionFrame.Snapshot> {652    val includeDuress = !duressSlot.isNullOrBlank()653    // Always reserve the supplemental frame so its presence cannot disclose654    // whether the source has a duress vault.655    val entryCap = MAX_SNAPSHOT_CHUNKS - 1656657    val chunks = mutableListOf<Map<String, String>>()658    var current = LinkedHashMap<String, String>()659    var currentBytes = 2 // "{}"660    for ((id, envelope) in entries) {661        // +1 for the separating comma; an overestimate only shrinks chunks.662        val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1663        if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {664            chunks.add(current)665            current = LinkedHashMap()666            currentBytes = 2667        }668        current[id] = envelope669        currentBytes += entryBytes670    }671    chunks.add(current)672673    val entriesChunkCount = minOf(chunks.size, entryCap)674    val totalChunks = entriesChunkCount + 1675    val supplementalFrame = AdoptionFrame.Snapshot(676        chunkIndex = entriesChunkCount,677        chunkCount = totalChunks,678        entries = emptyMap(),679        tombstones = tombstones,680        duressSlot = duressSlot.takeIf { includeDuress },681    )682683    if (684        AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)685            .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING686    ) {687        if (includeDuress) throw SnapshotDuressFrameTooLargeException()688        throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")689    }690691    val frames = mutableListOf<AdoptionFrame.Snapshot>()692    for (index in 0 until entriesChunkCount) {693        frames.add(AdoptionFrame.Snapshot(694            chunkIndex = index,695            chunkCount = totalChunks,696            entries = chunks[index],697            tombstones = emptyMap(),698            duressSlot = null,699        ))700    }701    frames.add(supplementalFrame)702    return frames703}704705internal class SnapshotDuressFrameTooLargeException :706    IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")707708/**709 * Receiver side: receive and reassemble every snapshot chunk. Adds raw frame710 * bytes to the aggregate counter before decoding (rejecting before JSON711 * deserialization when the next frame exceeds the remaining budget), then712 * enforces the per-frame wire ceiling, sequential 0-based chunk_index713 * ordering, a stable chunk_count within [MAX_SNAPSHOT_CHUNKS], and structural714 * validity of each frame. Merging goes through the shared aggregate helper:715 * every key/value and projected count is validated in one bounded pass before716 * anything lands in the accumulator, so a rejection leaves no partial adopted717 * state and the caller can fall back to the sync pipeline.718 */719suspend fun receiveVaultSnapshot(720    channel: PairingTransport,721): ReceivedSnapshot {722    val acc = createAdoptSnapshotBudget()723    var chunkCount = -1724    var received = 0725    while (chunkCount == -1 || received < chunkCount) {726        val wire = channel.receive()727        if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {728            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")729        }730        val raw = runCatching { SyncPadding.unpad(wire) }731            .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }732        if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {733            throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")734        }735        if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {736            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")737        }738        val frame = runCatching {739            AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))740        }.getOrNull()741        if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")742        frame as AdoptionFrame.Snapshot743        if (chunkCount == -1) {744            chunkCount = frame.chunkCount745            if (chunkCount > MAX_SNAPSHOT_CHUNKS) {746                throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")747            }748        } else if (frame.chunkCount != chunkCount) {749            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")750        }751        if (frame.chunkIndex != received) {752            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")753        }754        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)755        received++756    }757    return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)758}759760private fun isDeviceType(value: String): Boolean =761    DeviceType.entries.any { it.wireValue == value }