VaultAdopt.kt

34.4 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    suspend fun deriveLocalIdentity(): LocalDeviceIdentity284    /** Only called after a successful, SAS-confirmed direct pairing. */285    suspend fun clearPairedDeviceRevocation(deviceId: String) {}286    suspend fun upsertPairedDevice(device: PairedDevice)287    suspend fun applyLicense(license: String) {}288    /** Return this receiver's locally validated Pro key, if present. */289    suspend fun license(): String? = null290    val pairState: AdoptionPairState? get() = null291    fun onError(error: String)292    /** Apply encrypted entries + tombstones from the inline snapshot. */293    suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}294    /**295     * Apply the source's signed device graph so the receiver graduates into the296     * mesh. The [authenticatedRemoteStaticPublicKey] is the source's Noise297     * transport static key (NOT the signing key); [applyIncomingDeviceManifest]298     * resolves it to the source's [PairedDevice] locally and uses the stored299     * signing key to verify the manifest signature. Default no-op preserves300     * the contract for callers that haven't wired the mesh path yet.301     */302    suspend fun applyIncomingDeviceManifest(303        manifest: SignedDeviceManifest,304        authenticatedRemoteStaticPublicKey: ByteArray,305    ) {}306    /** Mark the paired device as synced after a successful snapshot. */307    suspend fun markSynced(deviceId: String) {}308}309310/** What the SOURCE (existing device) needs to grant its vault to a receiver. */311interface AdoptionSourceDeps {312    val sourceIdentity: LocalDeviceIdentity313    suspend fun rootKeyHex(): String314    suspend fun vaultId(): String315    suspend fun license(): String? = null316    /** Validate and durably store a Pro key offered by the receiver. */317    suspend fun applyLicense(license: String) {}318319    /**320     * Ask the user to approve handing this vault to the requesting device. The321     * request's name/type/label are for the human to read; the decision must not322     * be made by recognising [AdoptionFrame.Request.sessionRequestId], which323     * carries no continuity between attempts.324     */325    suspend fun onConsent(request: AdoptionFrame.Request): Boolean326    suspend fun upsertPairedDevice(device: PairedDevice)327    fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false328    /**329     * Rotate the source's identity after the receiver reports a collision on330     * the source's own identity. Returns the fresh identity for the resent331     * ADOPT_GRANT.332     */333    suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")334    val pairState: AdoptionPairState? get() = null335    /** Return all encrypted entries + tombstones for the inline snapshot. */336    suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null337    /** Return the signed device manifest for the graph, if available. */338    suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null339    /** Mark the paired device as synced after a successful snapshot. */340    suspend fun markSynced(deviceId: String) {}341    /** Browser-shaped sealed duress slot JSON for the snapshot, if duress is configured. */342    suspend fun duressSlotJson(): String? = null343}344345private val Hex64 = Regex("^[0-9a-f]{64}\$")346347fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)348349fun isAdoptRequest(frame: AdoptionFrame?): Boolean =350    frame is AdoptionFrame.Request &&351        frame.sessionRequestId.isNotEmpty() &&352        isDeviceType(frame.deviceType)353354fun isAdoptGrant(frame: AdoptionFrame?): Boolean =355    frame is AdoptionFrame.Grant &&356        validateRootKeyHex(frame.rootKeyHex) &&357        Hex64.matches(frame.vaultId) &&358        isDeviceType(frame.source.deviceType) &&359        Hex64.matches(frame.source.longTermPublicKeyHex) &&360        (frame.source.relayUrl == null ||361            runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)362363fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =364    frame is AdoptionFrame.Confirm365366fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =367    frame is AdoptionFrame.Identity &&368        frame.deviceId.isNotEmpty() &&369        isDeviceType(frame.deviceType) &&370        Hex64.matches(frame.longTermPublicKeyHex)371372fun isAdoptComplete(frame: AdoptionFrame?): Boolean =373    frame is AdoptionFrame.Complete374375fun isAdoptApplied(frame: AdoptionFrame?): Boolean =376    frame is AdoptionFrame.Applied377378fun isAdoptReject(frame: AdoptionFrame?): Boolean =379    frame is AdoptionFrame.Reject &&380        (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")381382fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =383    frame is AdoptionFrame.Snapshot &&384        frame.chunkIndex >= 0 &&385        frame.chunkCount >= 1386387/**388 * RECEIVER side: ask a source to adopt us. Sends ADOPT_REQUEST, verifies the389 * granted root key actually derives the advertised vault id (catching a lying or390 * corrupted source before it can seal a mismatched vault), seals the local vault,391 * applies any carried license, returns our identity, and records the source as a392 * paired device. Returns null on any protocol failure (reason via [deps.onError]).393 */394suspend fun requestAdoption(395    channel: PairingTransport,396    deps: AdoptionReceiverDeps,397    // Called once after a valid ADOPT_GRANT is decoded and validated, before398    // any side effects (vault creation, paired-device upsert). Used by the399    // receiver to inspect the grant's snapshot_capable flag and skip the 15s400    // inline-snapshot wait when the source has nothing to send. Defaults to no-op401    // for callers (tests, other helpers) that don't need to inspect the grant.402    onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,403    nowMs: () -> Long = { System.currentTimeMillis() },404): PairedDevice? {405    val receiverLicense = deps.license()406    // Fresh every attempt, and deliberately not our real device id: no identity407    // exists yet at this point in the protocol.408    sendFrame(channel, AdoptionFrame.Request(409        sessionRequestId = deps.generateDeviceId(),410        deviceName = deps.deviceName,411        deviceType = deps.deviceType.wireValue,412        license = receiverLicense,413        snapshotCapable = true,414    ))415416    val confirmed = deps.confirmSas()417    sendFrame(channel, AdoptionFrame.Confirm(confirmed))418    if (!confirmed) {419        deps.onError("ADOPT_SAS_REJECTED")420        return null421    }422423    val frame = receiveFrame(channel)424    if (isAdoptReject(frame)) {425        deps.onError((frame as AdoptionFrame.Reject).reason)426        return null427    }428    if (!isAdoptGrant(frame)) {429        deps.onError("ADOPT_UNEXPECTED_FRAME")430        return null431    }432    val grant = frame as AdoptionFrame.Grant433    onGrant?.invoke(grant)434435    val rootKeyBytes = hexToPubkey(grant.rootKeyHex)436    try {437        if (computeVaultId(rootKeyBytes) != grant.vaultId) {438            deps.onError("ADOPT_VAULT_ID_MISMATCH")439            return null440        }441    } finally {442        rootKeyBytes.fill(0)443    }444    if (receiverLicense == null && grant.license == null) {445        deps.onError("ADOPT_PRO_REQUIRED")446        return null447    }448449    deps.validateSource(grant.source)450451    // Check the source's identity against the local revocation ledger. A452    // previously-revoked device must present a fresh identity so that stale453    // signed revocations held by other mesh peers cannot remove it after454    // re-pair. If the source's identity is revoked, send ADOPT_DEVICE_ID_COLLISION455    // and wait for a fresh grant (one retry).456    var acceptedGrant = grant457    if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {458        sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))459        val retry = receiveFrame(channel)460        if (!isAdoptGrant(retry)) {461            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")462            return null463        }464        acceptedGrant = retry as AdoptionFrame.Grant465        if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {466            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))467            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")468            return null469        }470        // Re-validate the fresh grant's vault id.471        val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)472        try {473            if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {474                deps.onError("ADOPT_VAULT_ID_MISMATCH")475                return null476            }477        } finally {478            freshRootBytes.fill(0)479        }480    }481482    val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)483    if (vaultId != acceptedGrant.vaultId) {484        deps.onError("ADOPT_VAULT_ID_MISMATCH")485        return null486    }487488    if (receiverLicense == null) {489        acceptedGrant.license?.let { deps.applyLicense(it) }490    }491492    val identity = deps.deriveLocalIdentity()493    sendFrame(channel, AdoptionFrame.Identity(494        deviceId = identity.deviceId,495        deviceName = identity.deviceName,496        deviceType = identity.deviceType.wireValue,497        longTermPublicKeyHex = identity.longTermPublicKeyHex,498        signingPublicKeyHex = identity.signingPublicKeyHex,499    ))500501    if (!isAdoptComplete(receiveFrame(channel))) {502        deps.onError("ADOPT_COMPLETION_MISSING")503        return null504    }505506    val sourceDevice = PairedDevice(507        deviceId = acceptedGrant.source.deviceId,508        deviceName = acceptedGrant.source.deviceName,509        deviceType = acceptedGrant.source.deviceType,510        longTermPublicKeyHex = acceptedGrant.source.longTermPublicKeyHex,511        signingPublicKeyHex = acceptedGrant.source.signingPublicKeyHex,512        trustSource = "direct",513        wsPort = acceptedGrant.source.wsPort,514        rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,515        relayUrl = deps.pairState?.relayUrl ?: acceptedGrant.source.relayUrl,516        pairedAt = nowMs(),517    )518    // A physically confirmed direct re-pair is the sole path allowed to lift519    // terminal revocation. Clear before upsert so storage can never expose the520    // source as both paired and revoked, even transiently.521    deps.clearPairedDeviceRevocation(sourceDevice.deviceId)522    deps.upsertPairedDevice(sourceDevice)523    sendFrame(channel, AdoptionFrame.Applied)524    return sourceDevice525}526527/**528 * SOURCE side: respond to an ADOPT_REQUEST. Gates on user consent, hands over the529 * root key, then records the receiver's returned identity as a paired device.530 * Returns null if consent is denied or the receiver's identity frame is invalid.531 */532suspend fun grantAdoption(533    channel: PairingTransport,534    request: AdoptionFrame.Request,535    deps: AdoptionSourceDeps,536    nowMs: () -> Long = { System.currentTimeMillis() },537): PairedDevice? {538    if (!deps.onConsent(request)) return null539540    val confirmation = receiveFrame(channel)541    if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {542        return null543    }544545    var sourceLicense = deps.license()546    if (sourceLicense == null && request.license != null) {547        sourceLicense = runCatching {548            deps.applyLicense(request.license)549            deps.license()550        }.getOrNull()551    }552    if (sourceLicense == null) {553        sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))554        throw IllegalStateException("ADOPT_PRO_REQUIRED")555    }556557    val rootKeyHex = deps.rootKeyHex()558    if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")559560    var sourceIdentity = deps.sourceIdentity561    var grantAttempts = 0562    while (true) {563        sendFrame(channel, AdoptionFrame.Grant(564            rootKeyHex = rootKeyHex,565            vaultId = deps.vaultId(),566            license = sourceLicense,567            source = AdoptionFrame.Source(568                deviceId = sourceIdentity.deviceId,569                deviceName = sourceIdentity.deviceName,570                deviceType = sourceIdentity.deviceType.wireValue,571                longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,572                signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,573                wsPort = sourceIdentity.wsPort,574                relayUrl = deps.pairState?.relayUrl,575            ),576            snapshotCapable = request.snapshotCapable == true,577        ))578579        var identity = receiveFrame(channel)580581        // Receiver may reject the source's identity if it is in the receiver's582        // revocation ledger. Rotate and resend (one retry).583        if (identity is AdoptionFrame.Reject &&584            identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&585            grantAttempts == 0586        ) {587            sourceIdentity = deps.rotateSourceIdentity()588            grantAttempts++589            continue590        }591592        if (!isAdoptIdentity(identity)) return null593        identity as AdoptionFrame.Identity594595        var device = PairedDevice(596            deviceId = identity.deviceId,597            deviceName = identity.deviceName,598            deviceType = identity.deviceType,599            longTermPublicKeyHex = identity.longTermPublicKeyHex,600            signingPublicKeyHex = identity.signingPublicKeyHex,601            trustSource = "direct",602            rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,603            relayUrl = deps.pairState?.relayUrl,604            pairedAt = nowMs(),605        )606        if (deps.hasDeviceIdentityCollision(device)) {607            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))608            identity = receiveFrame(channel)609            if (!isAdoptIdentity(identity)) return null610            identity as AdoptionFrame.Identity611            device = device.copy(612                deviceId = identity.deviceId,613                deviceName = identity.deviceName,614                deviceType = identity.deviceType,615                longTermPublicKeyHex = identity.longTermPublicKeyHex,616                signingPublicKeyHex = identity.signingPublicKeyHex,617            )618            if (deps.hasDeviceIdentityCollision(device)) {619                sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))620                return null621            }622        }623        deps.upsertPairedDevice(device)624        sendFrame(channel, AdoptionFrame.Complete)625        if (!isAdoptApplied(receiveFrame(channel))) return null626        return device627    }628}629630/**631 * Wire codec. `classDiscriminator = "type"` reproduces the browser's flat632 * `{ "type": "ADOPT_…", … }` shape; `encodeDefaults = false` omits absent633 * optionals exactly like `JSON.stringify` drops `undefined`.634 */635val AdoptJson: Json = Json {636    classDiscriminator = "type"637    encodeDefaults = false638    ignoreUnknownKeys = true639}640641suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {642    channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))643}644645/** Decode one frame, tolerating a malformed/unknown payload by returning null. */646suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =647    runCatching {648        AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))649    }.getOrNull()650651/**652 * Source side: chunk the vault snapshot and send it over the pairing channel.653 *654 * Wire shape (v2.9.9+, supplemental frame; mirrors browser v4.6.4):655 *   - N entries frames, each <= [MAX_SNAPSHOT_CHUNK_BYTES] serialized entries.656 *   - One supplemental frame always follows the entries. It carries the657 *     tombstones and, when configured, the duress slot. Sending the same frame658 *     count in both cases prevents a relay from learning duress presence.659 *     Keeping duress off the entries frame also prevents a sizeable sealed660 *     duress vault from pushing the entries frame over the wire ceiling.661 *662 * Frame budget ([MAX_SNAPSHOT_CHUNKS] = 200):663 *   - ONE of the 200 frames is always reserved for the supplemental frame;664 *     entries use at most 199 chunks. Excess entries are deferred to the sync665 *     fallback pipeline (sync carries entries and tombstones on Android too,666 *     so this is a graceful truncation). The supplemental frame is required667 *     even without duress so its presence cannot disclose configuration. When668 *     configured, it carries the duress slot; omitting it would leave the669 *     adopted device permanently without its duress vault.670 *671 * Oversized duress: duress that itself exceeds [SNAPSHOT_FRAME_WIRE_CEILING]672 * is rejected with a thrown error BEFORE any snapshot frame is sent. Hard stop;673 * the caller must split duress out of band. We do not silently truncate674 * duress; sync cannot restore it.675 *676 * Backward compat: pre-v2.9.9 senders put `duress_slot` on the entries677 * final chunk. `receiveVaultSnapshot` reads `duress_slot` off any chunk (a678 * duress-only frame has empty `entries` and the complete tombstone map),679 * so both shapes decode and both new->old / old->new directions interoperate.680 */681suspend fun sendVaultSnapshot(682    channel: PairingTransport,683    entries: Map<String, String>,684    tombstones: Map<String, Long>,685    duressSlot: String? = null,686) {687    val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)688    // PB-26-206 preflight with the SAME helper the receiver enforces: nothing689    // is sent until every frame fits the aggregate budget, so an over-budget690    // snapshot is never partially sent or silently truncated. The caller falls691    // through to the regular sync pipeline (deny-only: no wire-field change,692    // invitation prefix unchanged).693    val acc = createAdoptSnapshotBudget()694    val encoded = frames.map {695        AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()696    }697    for (i in frames.indices) {698        val frame = frames[i]699        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)700    }701    for (raw in encoded) channel.send(SyncPadding.pad(raw))702}703704/**705 * Pure frame construction for [sendVaultSnapshot]: chunking, the duress-frame706 * reservation, and the oversized-duress hard stop. No I/O happens here, so707 * the preflight above can reject before the first byte goes out.708 */709private fun buildAdoptSnapshotFrames(710    entries: Map<String, String>,711    tombstones: Map<String, Long>,712    duressSlot: String?,713): List<AdoptionFrame.Snapshot> {714    val includeDuress = !duressSlot.isNullOrBlank()715    // Always reserve the supplemental frame so its presence cannot disclose716    // whether the source has a duress vault.717    val entryCap = MAX_SNAPSHOT_CHUNKS - 1718719    val chunks = mutableListOf<Map<String, String>>()720    var current = LinkedHashMap<String, String>()721    var currentBytes = 2 // "{}"722    for ((id, envelope) in entries) {723        // +1 for the separating comma; an overestimate only shrinks chunks.724        val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1725        if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {726            chunks.add(current)727            current = LinkedHashMap()728            currentBytes = 2729        }730        current[id] = envelope731        currentBytes += entryBytes732    }733    chunks.add(current)734735    val entriesChunkCount = minOf(chunks.size, entryCap)736    val totalChunks = entriesChunkCount + 1737    val supplementalFrame = AdoptionFrame.Snapshot(738        chunkIndex = entriesChunkCount,739        chunkCount = totalChunks,740        entries = emptyMap(),741        tombstones = tombstones,742        duressSlot = duressSlot.takeIf { includeDuress },743    )744745    if (746        AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)747            .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING748    ) {749        if (includeDuress) throw SnapshotDuressFrameTooLargeException()750        throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")751    }752753    val frames = mutableListOf<AdoptionFrame.Snapshot>()754    for (index in 0 until entriesChunkCount) {755        frames.add(AdoptionFrame.Snapshot(756            chunkIndex = index,757            chunkCount = totalChunks,758            entries = chunks[index],759            tombstones = emptyMap(),760            duressSlot = null,761        ))762    }763    frames.add(supplementalFrame)764    return frames765}766767internal class SnapshotDuressFrameTooLargeException :768    IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")769770/**771 * Receiver side: receive and reassemble every snapshot chunk. Adds raw frame772 * bytes to the aggregate counter before decoding (rejecting before JSON773 * deserialization when the next frame exceeds the remaining budget), then774 * enforces the per-frame wire ceiling, sequential 0-based chunk_index775 * ordering, a stable chunk_count within [MAX_SNAPSHOT_CHUNKS], and structural776 * validity of each frame. Merging goes through the shared aggregate helper:777 * every key/value and projected count is validated in one bounded pass before778 * anything lands in the accumulator, so a rejection leaves no partial adopted779 * state and the caller can fall back to the sync pipeline.780 */781suspend fun receiveVaultSnapshot(782    channel: PairingTransport,783): ReceivedSnapshot {784    val acc = createAdoptSnapshotBudget()785    var chunkCount = -1786    var received = 0787    while (chunkCount == -1 || received < chunkCount) {788        val wire = channel.receive()789        if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {790            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")791        }792        val raw = runCatching { SyncPadding.unpad(wire) }793            .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }794        if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {795            throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")796        }797        if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {798            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")799        }800        val frame = runCatching {801            AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))802        }.getOrNull()803        if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")804        frame as AdoptionFrame.Snapshot805        if (chunkCount == -1) {806            chunkCount = frame.chunkCount807            if (chunkCount > MAX_SNAPSHOT_CHUNKS) {808                throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")809            }810        } else if (frame.chunkCount != chunkCount) {811            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")812        }813        if (frame.chunkIndex != received) {814            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")815        }816        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)817        received++818    }819    return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)820}821822private fun isDeviceType(value: String): Boolean =823    DeviceType.entries.any { it.wireValue == value }