VaultAdopt.kt

35.1 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 persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean = true332    suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean = true333    suspend fun upsertPairedDevice(device: PairedDevice)334    fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false335    /**336     * Rotate the source's identity after the receiver reports a collision on337     * the source's own identity. Returns the fresh identity for the resent338     * ADOPT_GRANT.339     */340    suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")341    val pairState: AdoptionPairState? get() = null342    /** Return all encrypted entries + tombstones for the inline snapshot. */343    suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null344    /** Return the signed device manifest for the graph, if available. */345    suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null346    /** Mark the paired device as synced after a successful snapshot. */347    suspend fun markSynced(deviceId: String) {}348    /** Browser-shaped sealed duress slot JSON for the snapshot, if duress is configured. */349    suspend fun duressSlotJson(): String? = null350}351352private val Hex64 = Regex("^[0-9a-f]{64}\$")353354fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)355356fun isAdoptRequest(frame: AdoptionFrame?): Boolean =357    frame is AdoptionFrame.Request &&358        frame.sessionRequestId.isNotEmpty() &&359        isDeviceType(frame.deviceType)360361fun isAdoptGrant(frame: AdoptionFrame?): Boolean =362    frame is AdoptionFrame.Grant &&363        validateRootKeyHex(frame.rootKeyHex) &&364        Hex64.matches(frame.vaultId) &&365        isDeviceType(frame.source.deviceType) &&366        Hex64.matches(frame.source.longTermPublicKeyHex) &&367        (frame.source.relayUrl == null ||368            runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)369370fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =371    frame is AdoptionFrame.Confirm372373fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =374    frame is AdoptionFrame.Identity &&375        frame.deviceId.isNotEmpty() &&376        isDeviceType(frame.deviceType) &&377        Hex64.matches(frame.longTermPublicKeyHex)378379fun isAdoptComplete(frame: AdoptionFrame?): Boolean =380    frame is AdoptionFrame.Complete381382fun isAdoptApplied(frame: AdoptionFrame?): Boolean =383    frame is AdoptionFrame.Applied384385fun isAdoptReject(frame: AdoptionFrame?): Boolean =386    frame is AdoptionFrame.Reject &&387        (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")388389fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =390    frame is AdoptionFrame.Snapshot &&391        frame.chunkIndex >= 0 &&392        frame.chunkCount >= 1393394/**395 * RECEIVER side: ask a source to adopt us. Sends ADOPT_REQUEST, verifies the396 * granted root key actually derives the advertised vault id (catching a lying or397 * corrupted source before it can seal a mismatched vault), seals the local vault,398 * applies any carried license, returns our identity, and records the source as a399 * paired device. Returns null on any protocol failure (reason via [deps.onError]).400 */401suspend fun requestAdoption(402    channel: PairingTransport,403    deps: AdoptionReceiverDeps,404    // Called once after a valid ADOPT_GRANT is decoded and validated, before405    // any side effects (vault creation, paired-device upsert). Used by the406    // receiver to inspect the grant's snapshot_capable flag and skip the 15s407    // inline-snapshot wait when the source has nothing to send. Defaults to no-op408    // for callers (tests, other helpers) that don't need to inspect the grant.409    onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,410    nowMs: () -> Long = { System.currentTimeMillis() },411): PairedDevice? {412    val receiverLicense = deps.license()413    // Fresh every attempt, and deliberately not our real device id: no identity414    // exists yet at this point in the protocol.415    sendFrame(channel, AdoptionFrame.Request(416        sessionRequestId = deps.generateDeviceId(),417        deviceName = deps.deviceName,418        deviceType = deps.deviceType.wireValue,419        license = receiverLicense,420        snapshotCapable = true,421    ))422423    val confirmed = deps.confirmSas()424    sendFrame(channel, AdoptionFrame.Confirm(confirmed))425    if (!confirmed) {426        deps.onError("ADOPT_SAS_REJECTED")427        return null428    }429430    val frame = receiveFrame(channel)431    if (isAdoptReject(frame)) {432        deps.onError((frame as AdoptionFrame.Reject).reason)433        return null434    }435    if (!isAdoptGrant(frame)) {436        deps.onError("ADOPT_UNEXPECTED_FRAME")437        return null438    }439    val grant = frame as AdoptionFrame.Grant440    onGrant?.invoke(grant)441442    val rootKeyBytes = hexToPubkey(grant.rootKeyHex)443    try {444        if (computeVaultId(rootKeyBytes) != grant.vaultId) {445            deps.onError("ADOPT_VAULT_ID_MISMATCH")446            return null447        }448    } finally {449        rootKeyBytes.fill(0)450    }451    if (receiverLicense == null && grant.license == null) {452        deps.onError("ADOPT_PRO_REQUIRED")453        return null454    }455456    deps.validateSource(grant.source)457458    // Check the source's identity against the local revocation ledger. A459    // previously-revoked device must present a fresh identity so that stale460    // signed revocations held by other mesh peers cannot remove it after461    // re-pair. If the source's identity is revoked, send ADOPT_DEVICE_ID_COLLISION462    // and wait for a fresh grant (one retry).463    var acceptedGrant = grant464    if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {465        sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))466        val retry = receiveFrame(channel)467        if (!isAdoptGrant(retry)) {468            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")469            return null470        }471        acceptedGrant = retry as AdoptionFrame.Grant472        if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {473            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))474            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")475            return null476        }477        // Re-validate the fresh grant's vault id.478        val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)479        try {480            if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {481                deps.onError("ADOPT_VAULT_ID_MISMATCH")482                return null483            }484        } finally {485            freshRootBytes.fill(0)486        }487    }488    if (receiverLicense == null && acceptedGrant.license == null) {489        deps.onError("ADOPT_PRO_REQUIRED")490        return null491    }492493494    if (receiverLicense == null) {495        acceptedGrant.license?.let { deps.applyLicense(it) }496    }497    val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)498    if (vaultId != acceptedGrant.vaultId) {499        deps.onError("ADOPT_VAULT_ID_MISMATCH")500        return null501    }502503504    val identity = deps.deriveLocalIdentity()505    sendFrame(channel, AdoptionFrame.Identity(506        deviceId = identity.deviceId,507        deviceName = identity.deviceName,508        deviceType = identity.deviceType.wireValue,509        longTermPublicKeyHex = identity.longTermPublicKeyHex,510        signingPublicKeyHex = identity.signingPublicKeyHex,511    ))512513    if (!isAdoptComplete(receiveFrame(channel))) {514        deps.onError("ADOPT_COMPLETION_MISSING")515        return null516    }517518    val sourceDevice = PairedDevice(519        deviceId = acceptedGrant.source.deviceId,520        deviceName = acceptedGrant.source.deviceName,521        deviceType = acceptedGrant.source.deviceType,522        longTermPublicKeyHex = acceptedGrant.source.longTermPublicKeyHex,523        signingPublicKeyHex = acceptedGrant.source.signingPublicKeyHex,524        trustSource = "direct",525        wsPort = acceptedGrant.source.wsPort,526        rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,527        relayUrl = deps.pairState?.relayUrl ?: acceptedGrant.source.relayUrl,528        pairedAt = nowMs(),529    )530    // A physically confirmed direct re-pair is the sole path allowed to lift531    // terminal revocation. The registry validates identity before either value532    // is changed, so a mismatch leaves the revocation intact.533    deps.upsertPairedDeviceAndClearRevocation(sourceDevice)534    sendFrame(channel, AdoptionFrame.Applied)535    return sourceDevice536}537538/**539 * SOURCE side: respond to an ADOPT_REQUEST. Gates on user consent, hands over the540 * root key, then records the receiver's returned identity as a paired device.541 * Returns null if consent is denied or the receiver's identity frame is invalid.542 */543suspend fun grantAdoption(544    channel: PairingTransport,545    request: AdoptionFrame.Request,546    deps: AdoptionSourceDeps,547    nowMs: () -> Long = { System.currentTimeMillis() },548): PairedDevice? {549    if (!deps.onConsent(request)) return null550551    val confirmation = receiveFrame(channel)552    if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {553        return null554    }555556    var sourceLicense = deps.license()557    if (sourceLicense == null && request.license != null) {558        sourceLicense = runCatching {559            deps.applyLicense(request.license)560            deps.license()561        }.getOrNull()562    }563    if (sourceLicense == null) {564        sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))565        throw IllegalStateException("ADOPT_PRO_REQUIRED")566    }567568    if (!deps.persistPendingHolder(request, nowMs())) return null569    val rootKeyHex = deps.rootKeyHex()570    if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")571572    var sourceIdentity = deps.sourceIdentity573    var grantAttempts = 0574    while (true) {575        sendFrame(channel, AdoptionFrame.Grant(576            rootKeyHex = rootKeyHex,577            vaultId = deps.vaultId(),578            license = sourceLicense,579            source = AdoptionFrame.Source(580                deviceId = sourceIdentity.deviceId,581                deviceName = sourceIdentity.deviceName,582                deviceType = sourceIdentity.deviceType.wireValue,583                longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,584                signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,585                wsPort = sourceIdentity.wsPort,586                relayUrl = deps.pairState?.relayUrl,587            ),588            snapshotCapable = request.snapshotCapable == true,589        ))590591        var identity = receiveFrame(channel)592593        // Receiver may reject the source's identity if it is in the receiver's594        // revocation ledger. Rotate and resend (one retry).595        if (identity is AdoptionFrame.Reject &&596            identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&597            grantAttempts == 0598        ) {599            sourceIdentity = deps.rotateSourceIdentity()600            grantAttempts++601            continue602        }603604        if (!isAdoptIdentity(identity)) return null605        identity as AdoptionFrame.Identity606607        var device = PairedDevice(608            deviceId = identity.deviceId,609            deviceName = identity.deviceName,610            deviceType = identity.deviceType,611            longTermPublicKeyHex = identity.longTermPublicKeyHex,612            signingPublicKeyHex = identity.signingPublicKeyHex,613            trustSource = "direct",614            rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,615            relayUrl = deps.pairState?.relayUrl,616            pairedAt = nowMs(),617        )618        if (deps.hasDeviceIdentityCollision(device)) {619            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))620            identity = receiveFrame(channel)621            if (!isAdoptIdentity(identity)) return null622            identity as AdoptionFrame.Identity623            device = device.copy(624                deviceId = identity.deviceId,625                deviceName = identity.deviceName,626                deviceType = identity.deviceType,627                longTermPublicKeyHex = identity.longTermPublicKeyHex,628                signingPublicKeyHex = identity.signingPublicKeyHex,629            )630            if (deps.hasDeviceIdentityCollision(device)) {631                sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))632                return null633            }634        }635        deps.upsertPairedDevice(device)636        sendFrame(channel, AdoptionFrame.Complete)637        if (!isAdoptApplied(receiveFrame(channel))) return null638        if (!deps.completePendingHolder(request, device)) return null639        return device640    }641}642643/**644 * Wire codec. `classDiscriminator = "type"` reproduces the browser's flat645 * `{ "type": "ADOPT_…", … }` shape; `encodeDefaults = false` omits absent646 * optionals exactly like `JSON.stringify` drops `undefined`.647 */648val AdoptJson: Json = Json {649    classDiscriminator = "type"650    encodeDefaults = false651    ignoreUnknownKeys = true652}653654suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {655    channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))656}657658/** Decode one frame, tolerating a malformed/unknown payload by returning null. */659suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =660    runCatching {661        AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))662    }.getOrNull()663664/**665 * Source side: chunk the vault snapshot and send it over the pairing channel.666 *667 * Wire shape (v2.9.9+, supplemental frame; mirrors browser v4.6.4):668 *   - N entries frames, each <= [MAX_SNAPSHOT_CHUNK_BYTES] serialized entries.669 *   - One supplemental frame always follows the entries. It carries the670 *     tombstones and, when configured, the duress slot. Sending the same frame671 *     count in both cases prevents a relay from learning duress presence.672 *     Keeping duress off the entries frame also prevents a sizeable sealed673 *     duress vault from pushing the entries frame over the wire ceiling.674 *675 * Frame budget ([MAX_SNAPSHOT_CHUNKS] = 200):676 *   - ONE of the 200 frames is always reserved for the supplemental frame;677 *     entries use at most 199 chunks. Excess entries are deferred to the sync678 *     fallback pipeline (sync carries entries and tombstones on Android too,679 *     so this is a graceful truncation). The supplemental frame is required680 *     even without duress so its presence cannot disclose configuration. When681 *     configured, it carries the duress slot; omitting it would leave the682 *     adopted device permanently without its duress vault.683 *684 * Oversized duress: duress that itself exceeds [SNAPSHOT_FRAME_WIRE_CEILING]685 * is rejected with a thrown error BEFORE any snapshot frame is sent. Hard stop;686 * the caller must split duress out of band. We do not silently truncate687 * duress; sync cannot restore it.688 *689 * Backward compat: pre-v2.9.9 senders put `duress_slot` on the entries690 * final chunk. `receiveVaultSnapshot` reads `duress_slot` off any chunk (a691 * duress-only frame has empty `entries` and the complete tombstone map),692 * so both shapes decode and both new->old / old->new directions interoperate.693 */694suspend fun sendVaultSnapshot(695    channel: PairingTransport,696    entries: Map<String, String>,697    tombstones: Map<String, Long>,698    duressSlot: String? = null,699) {700    val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)701    // PB-26-206 preflight with the SAME helper the receiver enforces: nothing702    // is sent until every frame fits the aggregate budget, so an over-budget703    // snapshot is never partially sent or silently truncated. The caller falls704    // through to the regular sync pipeline (deny-only: no wire-field change,705    // invitation prefix unchanged).706    val acc = createAdoptSnapshotBudget()707    val encoded = frames.map {708        AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()709    }710    for (i in frames.indices) {711        val frame = frames[i]712        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)713    }714    for (raw in encoded) channel.send(SyncPadding.pad(raw))715}716717/**718 * Pure frame construction for [sendVaultSnapshot]: chunking, the duress-frame719 * reservation, and the oversized-duress hard stop. No I/O happens here, so720 * the preflight above can reject before the first byte goes out.721 */722private fun buildAdoptSnapshotFrames(723    entries: Map<String, String>,724    tombstones: Map<String, Long>,725    duressSlot: String?,726): List<AdoptionFrame.Snapshot> {727    val includeDuress = !duressSlot.isNullOrBlank()728    // Always reserve the supplemental frame so its presence cannot disclose729    // whether the source has a duress vault.730    val entryCap = MAX_SNAPSHOT_CHUNKS - 1731732    val chunks = mutableListOf<Map<String, String>>()733    var current = LinkedHashMap<String, String>()734    var currentBytes = 2 // "{}"735    for ((id, envelope) in entries) {736        // +1 for the separating comma; an overestimate only shrinks chunks.737        val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1738        if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {739            chunks.add(current)740            current = LinkedHashMap()741            currentBytes = 2742        }743        current[id] = envelope744        currentBytes += entryBytes745    }746    chunks.add(current)747748    val entriesChunkCount = minOf(chunks.size, entryCap)749    val totalChunks = entriesChunkCount + 1750    val supplementalFrame = AdoptionFrame.Snapshot(751        chunkIndex = entriesChunkCount,752        chunkCount = totalChunks,753        entries = emptyMap(),754        tombstones = tombstones,755        duressSlot = duressSlot.takeIf { includeDuress },756    )757758    if (759        AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)760            .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING761    ) {762        if (includeDuress) throw SnapshotDuressFrameTooLargeException()763        throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")764    }765766    val frames = mutableListOf<AdoptionFrame.Snapshot>()767    for (index in 0 until entriesChunkCount) {768        frames.add(AdoptionFrame.Snapshot(769            chunkIndex = index,770            chunkCount = totalChunks,771            entries = chunks[index],772            tombstones = emptyMap(),773            duressSlot = null,774        ))775    }776    frames.add(supplementalFrame)777    return frames778}779780internal class SnapshotDuressFrameTooLargeException :781    IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")782783/**784 * Receiver side: receive and reassemble every snapshot chunk. Adds raw frame785 * bytes to the aggregate counter before decoding (rejecting before JSON786 * deserialization when the next frame exceeds the remaining budget), then787 * enforces the per-frame wire ceiling, sequential 0-based chunk_index788 * ordering, a stable chunk_count within [MAX_SNAPSHOT_CHUNKS], and structural789 * validity of each frame. Merging goes through the shared aggregate helper:790 * every key/value and projected count is validated in one bounded pass before791 * anything lands in the accumulator, so a rejection leaves no partial adopted792 * state and the caller can fall back to the sync pipeline.793 */794suspend fun receiveVaultSnapshot(795    channel: PairingTransport,796): ReceivedSnapshot {797    val acc = createAdoptSnapshotBudget()798    var chunkCount = -1799    var received = 0800    while (chunkCount == -1 || received < chunkCount) {801        val wire = channel.receive()802        if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {803            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")804        }805        val raw = runCatching { SyncPadding.unpad(wire) }806            .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }807        if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {808            throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")809        }810        if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {811            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")812        }813        val frame = runCatching {814            AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))815        }.getOrNull()816        if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")817        frame as AdoptionFrame.Snapshot818        if (chunkCount == -1) {819            chunkCount = frame.chunkCount820            if (chunkCount > MAX_SNAPSHOT_CHUNKS) {821                throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")822            }823        } else if (frame.chunkCount != chunkCount) {824            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")825        }826        if (frame.chunkIndex != received) {827            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")828        }829        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)830        received++831    }832    return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)833}834835private fun isDeviceType(value: String): Boolean =836    DeviceType.entries.any { it.wireValue == value }