VaultAdopt.kt

36.3 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        // v1-only receiver capability metadata.58        @SerialName("snapshot_capable") val snapshotCapable: Boolean = false,59    ) : AdoptionFrame()6061    @Serializable62    @SerialName("ADOPT_IDENTITY")63    data class Identity(64        @SerialName("device_id") val deviceId: String,65        @SerialName("device_name") val deviceName: String,66        @SerialName("device_type") val deviceType: String,67        @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,68        @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,69    ) : AdoptionFrame()7071    /**72     * Encrypted source-to-receiver acknowledgement emitted only after the source73     * has durably recorded the receiver. The receiver cannot truthfully report a74     * successful pair before this arrives.75     */76    @Serializable77    @SerialName("ADOPT_COMPLETE")78    data object Complete : AdoptionFrame()7980    /** Encrypted receiver-to-source acknowledgement after the source row is durable. */81    @Serializable82    @SerialName("ADOPT_APPLIED")83    data object Applied : AdoptionFrame()8485    /** Neither peer proved Pro, so the pairing must not commit. */86    @Serializable87    @SerialName("ADOPT_REJECT")88    data class Reject(89        val reason: String,90    ) : AdoptionFrame()9192    /**93     * One chunk of the inline vault snapshot sent by the source after94     * ADOPT_APPLIED over the same authenticated Noise NK channel. Entries are95     * opaque base64 ciphertext envelopes; tombstones ride the final chunk only.96     */97    @Serializable98    @SerialName("ADOPT_SNAPSHOT")99    data class Snapshot(100        @SerialName("chunk_index") val chunkIndex: Int,101        @SerialName("chunk_count") val chunkCount: Int,102        val entries: Map<String, String>,103        val tombstones: Map<String, Long>,104        @SerialName("duress_slot") val duressSlot: String? = null,105    ) : AdoptionFrame()106107    /** Receiver acknowledgement sent after all snapshot chunks are applied. */108    @Serializable109    @SerialName("ADOPT_SNAPSHOT_APPLIED")110    data class SnapshotApplied(111        @SerialName("entries_received") val entriesReceived: Int,112        @SerialName("tombstones_received") val tombstonesReceived: Int,113    ) : AdoptionFrame()114115    /** Optional signed device graph appended after the snapshot (manifest v3+). */116    @Serializable117    @SerialName("ADOPT_DEVICE_MANIFEST")118    data class DeviceManifestFrame(119        val manifest: SignedDeviceManifest,120    ) : AdoptionFrame()121122    /** Receiver acknowledgement for an applied device manifest. */123    @Serializable124    @SerialName("ADOPT_DEVICE_MANIFEST_APPLIED")125    data object DeviceManifestApplied : AdoptionFrame()126    @Serializable127    @SerialName("ADOPT_REQUEST_V2")128    data class RequestV2(129        @SerialName("adoptionVersion") val adoptionVersion: Int,130        @SerialName("device_id") val deviceId: String,131        @SerialName("device_name") val deviceName: String,132        @SerialName("device_type") val deviceType: String,133        @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,134        @SerialName("signing_public_key_hex") val signingPublicKeyHex: String,135        val license: String? = null,136        @SerialName("snapshot_capable") val snapshotCapable: Boolean? = null,137    ) : AdoptionFrame()138139    @Serializable @SerialName("ADOPT_CONFIRM_REQUIRED")140    data object ConfirmRequired : AdoptionFrame()141142    @Serializable @SerialName("ADOPT_PREPARE")143    data class Prepare(144        @SerialName("device_id") val deviceId: String,145        @SerialName("device_name") val deviceName: String,146        @SerialName("device_type") val deviceType: String,147        @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,148        @SerialName("signing_public_key_hex") val signingPublicKeyHex: String,149        @SerialName("vault_id") val vaultId: String,150        @SerialName("ws_port") val wsPort: Int? = null,151        @SerialName("relay_url") val relayUrl: String? = null,152        val license: String? = null,153        @SerialName("snapshot_capable") val snapshotCapable: Boolean? = null,154    ) : AdoptionFrame()155    @Serializable @SerialName("ADOPT_READY")156    data object Ready : AdoptionFrame()157    @Serializable158    data class Source(159        @SerialName("device_id") val deviceId: String,160        @SerialName("device_name") val deviceName: String,161        @SerialName("device_type") val deviceType: String,162        @SerialName("long_term_public_key_hex") val longTermPublicKeyHex: String,163        @SerialName("signing_public_key_hex") val signingPublicKeyHex: String? = null,164        @SerialName("ws_port") val wsPort: Int? = null,165        @SerialName("relay_url") val relayUrl: String? = null,166    )167}168169data class AdoptionPairState(170    val rendezvousSecretHex: String,171    val relayUrl: String? = null,172)173174/**175 * Receiver-side reassembly result from [receiveVaultSnapshot]. Carries the176 * aggregated entries and tombstones plus the optional browser duress slot177 * JSON (present on the final chunk only, when the source has duress configured).178 */179data class ReceivedSnapshot(180    val entries: Map<String, String>,181    val tombstones: Map<String, Long>,182    val duressSlot: String? = null,183)184185/**186 * Wire guardrails for the inline snapshot. A chunk's serialized entries map187 * stays under [MAX_SNAPSHOT_CHUNK_BYTES]; the whole transfer is capped at188 * [MAX_SNAPSHOT_CHUNKS] frames so a compromised source cannot exhaust receiver189 * memory (mirrors SYNC_LIMITS.MAX_FRAME_BYTES in the sync coordinator).190 */191const val MAX_SNAPSHOT_CHUNK_BYTES = 512 * 1024 // 512 KiB192const val MAX_SNAPSHOT_CHUNKS = 200193194// Headroom added to the per-chunk entries budget when validating an encoded195// frame on the wire: JSON envelope plus the final chunk's tombstone map.196internal const val SNAPSHOT_FRAME_WIRE_CEILING = MAX_SNAPSHOT_CHUNK_BYTES + 256 * 1024197internal val MAX_PADDED_SNAPSHOT_FRAME_BYTES = SyncPadding.bucket(SNAPSHOT_FRAME_WIRE_CEILING + 4)198199/**200 * PB-26-206 aggregate budget shared by sender and receiver — exact mirror of201 * the browser's `vault-adopt.ts` ceilings. The per-frame guard above bounds202 * one frame; this bounds the whole transfer independently of the 200-frame203 * count, so many individually valid frames cannot OOM the receiver.204 */205const val MAX_ADOPT_SNAPSHOT_BYTES = 10 * 1024 * 1024 // 10 MiB206const val MAX_ADOPT_SNAPSHOT_ENTRIES = 25_000207const val MAX_ADOPT_SNAPSHOT_TOMBSTONES = 25_000208/** Same value as [SyncLimits.MAX_ID_LENGTH]; named here so vectors read identically on both clients. */209const val MAX_ADOPT_SNAPSHOT_ID_CHARS = SyncLimits.MAX_ID_LENGTH210/**211 * Maximum encrypted entry envelope: plaintext ceiling plus the existing212 * base64 overhead allowance. Int arithmetic gives 699,114 — the browser's213 * float comparison accepts and rejects at exactly the same lengths.214 */215const val MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES = SyncLimits.MAX_ENTRY_ENVELOPE_BYTES216217/**218 * Running aggregate for one snapshot transfer. Counts ride alongside the maps219 * (never re-derived per frame) so the bound stays O(n).220 */221class AdoptSnapshotBudget {222    val entries = LinkedHashMap<String, String>()223    val tombstones = LinkedHashMap<String, Long>()224    var duressSlot: String? = null225    /** Sum of encoded wire-frame bytes consumed so far. */226    var bytes: Int = 0227    var entryCount: Int = 0228    var tombstoneCount: Int = 0229}230231fun createAdoptSnapshotBudget(): AdoptSnapshotBudget = AdoptSnapshotBudget()232233/**234 * PB-26-206 shared preflight/merge helper used by BOTH the sender (preflight235 * before the first frame goes out) and the receiver (per frame, after the236 * byte-budget check, before decoded maps are merged).237 *238 * One bounded pass per attacker-controlled map: each key/value is validated239 * and projected counts are enforced inside the same loop that merges, so the240 * maps are never iterated count→size→merge repeatedly. Throws before merging241 * the offending frame, leaving no partial adopted state.242 */243fun applyAdoptSnapshotFrame(244    acc: AdoptSnapshotBudget,245    entries: Map<String, String>,246    tombstones: Map<String, Long>,247    duressSlot: String?,248    frameBytes: Int,249) {250    if (frameBytes > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {251        throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")252    }253    for ((id, envelope) in entries) {254        if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")255        if (envelope.length > MAX_ADOPT_SNAPSHOT_ENVELOPE_BYTES) {256            throw IllegalStateException("ADOPT_SNAPSHOT_ENVELOPE_TOO_LARGE")257        }258        if (acc.entryCount >= MAX_ADOPT_SNAPSHOT_ENTRIES) {259            throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_ENTRIES")260        }261        acc.entryCount++262        acc.entries[id] = envelope263    }264    for ((id, ts) in tombstones) {265        if (id.length > MAX_ADOPT_SNAPSHOT_ID_CHARS) throw IllegalStateException("ADOPT_SNAPSHOT_ID_TOO_LONG")266        // Long is always finite, so non-finite hostile JSON dies at the267        // strict codec decode before reaching this merge (see V7).268        if (acc.tombstoneCount >= MAX_ADOPT_SNAPSHOT_TOMBSTONES) {269            throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_TOMBSTONES")270        }271        acc.tombstoneCount++272        acc.tombstones[id] = ts273    }274    if (!duressSlot.isNullOrEmpty()) {275        // The duress slot rides inside wire frames already bounded by the276        // frame ceiling, and its raw bytes count against the aggregate above.277        if (duressSlot.length > SNAPSHOT_FRAME_WIRE_CEILING) {278            throw IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")279        }280        acc.duressSlot = duressSlot281    }282    acc.bytes += frameBytes283}284285/** What the RECEIVER (joining device) needs to adopt a vault from a source. */286interface AdoptionReceiverDeps {287    val deviceName: String288    val deviceType: DeviceType289    fun generateDeviceId(): String290    /** Root-key transfer cannot begin until this device confirms the SAS. */291    suspend fun confirmSas(): Boolean292    /**293     * Local safety policy evaluated after the authenticated grant is validated294     * but before any vault state changes.295     */296    suspend fun validateSource(source: AdoptionFrame.Source) {}297298    /**299     * True when the source's identity (from ADOPT_GRANT) is in the local300     * terminal revocation ledger. When true, the receiver sends301     * ADOPT_DEVICE_ID_COLLISION so the source rotates and resends the grant.302     */303    suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean = false304305    /** Seal a fresh local vault under the receiver's password, reusing [rootKeyHex]. Returns the vault id. */306    suspend fun createVaultFromRootKey(rootKeyHex: String): String307    /** Build the receiver's local identity after the adopted vault exists. */308    suspend fun deriveLocalIdentity(): LocalDeviceIdentity309    /** Persist the direct pairing and lift its terminal revocation as one store operation. */310    suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {311        upsertPairedDevice(device)312        clearPairedDeviceRevocation(device.deviceId)313    }314    suspend fun clearPairedDeviceRevocation(deviceId: String) {}315    suspend fun upsertPairedDevice(device: PairedDevice)316    suspend fun applyLicense(license: String) {}317    /** Return this receiver's locally validated Pro key, if present. */318    suspend fun license(): String? = null319    val pairState: AdoptionPairState? get() = null320    fun onError(error: String)321    /** Apply encrypted entries + tombstones from the inline snapshot. */322    suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String? = null) {}323    /**324     * Apply the source's signed device graph so the receiver graduates into the325     * mesh. The [authenticatedRemoteStaticPublicKey] is the source's Noise326     * transport static key (NOT the signing key); [applyIncomingDeviceManifest]327     * resolves it to the source's [PairedDevice] locally and uses the stored328     * signing key to verify the manifest signature. Default no-op preserves329     * the contract for callers that haven't wired the mesh path yet.330     */331    suspend fun applyIncomingDeviceManifest(332        manifest: SignedDeviceManifest,333        authenticatedRemoteStaticPublicKey: ByteArray,334    ) {}335    /** Mark the paired device as synced after a successful snapshot. */336    suspend fun markSynced(deviceId: String) {}337}338339/** What the SOURCE (existing device) needs to grant its vault to a receiver. */340interface AdoptionSourceDeps {341    val sourceIdentity: LocalDeviceIdentity342    suspend fun rootKeyHex(): String343    suspend fun vaultId(): String344    suspend fun license(): String? = null345    /** Validate and durably store a Pro key offered by the receiver. */346    suspend fun applyLicense(license: String) {}347    /**348     * Ask the user to approve handing this vault to the requesting device. The349     * request's name/type/label are for the human to read; the decision must not350     * be made by recognising [AdoptionFrame.Request.sessionRequestId], which351     * carries no continuity between attempts.352     */353    suspend fun onConsent(request: AdoptionFrame.Request): Boolean354    suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean = true355    suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean = true356    suspend fun upsertPairedDevice(device: PairedDevice)357    fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false358    /**359     * Rotate the source's identity after the receiver reports a collision on360     * the source's own identity. Returns the fresh identity for the resent361     * ADOPT_GRANT.362     */363    suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")364    val pairState: AdoptionPairState? get() = null365    /** Return all encrypted entries + tombstones for the inline snapshot. */366    suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null367    /** Return the signed device manifest for the graph, if available. */368    suspend fun outgoingDeviceManifest(): SignedDeviceManifest? = null369    /** Mark the paired device as synced after a successful snapshot. */370    suspend fun markSynced(deviceId: String) {}371    /** Browser-shaped sealed duress slot JSON for the snapshot, if duress is configured. */372    suspend fun duressSlotJson(): String? = null373}374375internal val Hex64 = Regex("^[0-9a-f]{64}$")376377fun validateRootKeyHex(rootKeyHex: String?): Boolean = rootKeyHex != null && Hex64.matches(rootKeyHex)378379fun isAdoptRequest(frame: AdoptionFrame?): Boolean =380    frame is AdoptionFrame.Request &&381        frame.sessionRequestId.isNotEmpty() &&382        isDeviceType(frame.deviceType)383384fun isAdoptGrant(frame: AdoptionFrame?): Boolean =385    frame is AdoptionFrame.Grant &&386        validateRootKeyHex(frame.rootKeyHex) &&387        Hex64.matches(frame.vaultId) &&388        isDeviceType(frame.source.deviceType) &&389        Hex64.matches(frame.source.longTermPublicKeyHex) &&390        (frame.source.relayUrl == null ||391            runCatching { Rendezvous.normalizeRelayUrl(frame.source.relayUrl) }.isSuccess)392393fun isAdoptConfirm(frame: AdoptionFrame?): Boolean =394    frame is AdoptionFrame.Confirm395396fun isAdoptIdentity(frame: AdoptionFrame?): Boolean =397    frame is AdoptionFrame.Identity &&398        frame.deviceId.isNotEmpty() &&399        isDeviceType(frame.deviceType) &&400        Hex64.matches(frame.longTermPublicKeyHex)401402fun isAdoptComplete(frame: AdoptionFrame?): Boolean =403    frame is AdoptionFrame.Complete404405fun isAdoptApplied(frame: AdoptionFrame?): Boolean =406    frame is AdoptionFrame.Applied407408fun isAdoptReject(frame: AdoptionFrame?): Boolean =409    frame is AdoptionFrame.Reject &&410        (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")411412fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =413    frame is AdoptionFrame.Snapshot &&414        frame.chunkIndex >= 0 &&415        frame.chunkCount >= 1416417/**418 * RECEIVER side: ask a source to adopt us. Sends ADOPT_REQUEST, verifies the419 * granted root key actually derives the advertised vault id (catching a lying or420 * corrupted source before it can seal a mismatched vault), seals the local vault,421 * applies any carried license, returns our identity, and records the source as a422 * paired device. Returns null on any protocol failure (reason via [deps.onError]).423 */424suspend fun requestAdoption(425    channel: PairingTransport,426    deps: AdoptionReceiverDeps,427    // Called once after a valid ADOPT_GRANT is decoded and validated, before428    // any side effects (vault creation, paired-device upsert). Used by the429    // receiver to inspect the grant's snapshot_capable flag and skip the 15s430    // inline-snapshot wait when the source has nothing to send. Defaults to no-op431    // for callers (tests, other helpers) that don't need to inspect the grant.432    onGrant: ((AdoptionFrame.Grant) -> Unit)? = null,433    nowMs: () -> Long = { System.currentTimeMillis() },434): PairedDevice? {435    val receiverLicense = deps.license()436    // Fresh every attempt, and deliberately not our real device id: no identity437    // exists yet at this point in the protocol.438    sendFrame(channel, AdoptionFrame.Request(439        sessionRequestId = deps.generateDeviceId(),440        deviceName = deps.deviceName,441        deviceType = deps.deviceType.wireValue,442        license = receiverLicense,443        snapshotCapable = true,444    ))445446    val confirmed = deps.confirmSas()447    sendFrame(channel, AdoptionFrame.Confirm(confirmed))448    if (!confirmed) {449        deps.onError("ADOPT_SAS_REJECTED")450        return null451    }452453    val frame = receiveFrame(channel)454    if (isAdoptReject(frame)) {455        deps.onError((frame as AdoptionFrame.Reject).reason)456        return null457    }458    if (!isAdoptGrant(frame)) {459        deps.onError("ADOPT_UNEXPECTED_FRAME")460        return null461    }462    val grant = frame as AdoptionFrame.Grant463    onGrant?.invoke(grant)464465    val rootKeyBytes = hexToPubkey(grant.rootKeyHex)466    try {467        if (computeVaultId(rootKeyBytes) != grant.vaultId) {468            deps.onError("ADOPT_VAULT_ID_MISMATCH")469            return null470        }471    } finally {472        rootKeyBytes.fill(0)473    }474    if (receiverLicense == null && grant.license == null) {475        deps.onError("ADOPT_PRO_REQUIRED")476        return null477    }478479    var acceptedGrant = grant480    var acceptedSource = grant.source ?: run {481        deps.onError("ADOPT_UNEXPECTED_FRAME")482        return null483    }484    deps.validateSource(acceptedSource)485486    // Check the source's identity against the local revocation ledger. A487    // previously-revoked device must present a fresh identity so that stale488    // signed revocations held by other mesh peers cannot remove it after489    // re-pair. If the source's identity is revoked, send ADOPT_DEVICE_ID_COLLISION490    // and wait for a fresh grant (one retry).491    if (deps.hasSourceIdentityCollision(acceptedSource)) {492        sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))493        val retry = receiveFrame(channel)494        if (!isAdoptGrant(retry)) {495            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")496            return null497        }498        acceptedGrant = retry as AdoptionFrame.Grant499        acceptedSource = acceptedGrant.source ?: run {500            deps.onError("ADOPT_UNEXPECTED_FRAME")501            return null502        }503        if (deps.hasSourceIdentityCollision(acceptedSource)) {504            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))505            deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")506            return null507        }508        // Re-validate the fresh grant's vault id.509        val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)510        try {511            if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {512                deps.onError("ADOPT_VAULT_ID_MISMATCH")513                return null514            }515        } finally {516            freshRootBytes.fill(0)517        }518    }519    if (receiverLicense == null && acceptedGrant.license == null) {520        deps.onError("ADOPT_PRO_REQUIRED")521        return null522    }523524525    if (receiverLicense == null) {526        acceptedGrant.license?.let { deps.applyLicense(it) }527    }528    val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)529    if (vaultId != acceptedGrant.vaultId) {530        deps.onError("ADOPT_VAULT_ID_MISMATCH")531        return null532    }533534535    val identity = deps.deriveLocalIdentity()536    sendFrame(channel, AdoptionFrame.Identity(537        deviceId = identity.deviceId,538        deviceName = identity.deviceName,539        deviceType = identity.deviceType.wireValue,540        longTermPublicKeyHex = identity.longTermPublicKeyHex,541        signingPublicKeyHex = identity.signingPublicKeyHex,542    ))543544    if (!isAdoptComplete(receiveFrame(channel))) {545        deps.onError("ADOPT_COMPLETION_MISSING")546        return null547    }548549    val sourceDevice = PairedDevice(550        deviceId = acceptedSource.deviceId,551        deviceName = acceptedSource.deviceName,552        deviceType = acceptedSource.deviceType,553        longTermPublicKeyHex = acceptedSource.longTermPublicKeyHex,554        signingPublicKeyHex = acceptedSource.signingPublicKeyHex,555        trustSource = "direct",556        wsPort = acceptedSource.wsPort,557        rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,558        relayUrl = deps.pairState?.relayUrl ?: acceptedSource.relayUrl,559        pairedAt = nowMs(),560    )561    // A physically confirmed direct re-pair is the sole path allowed to lift562    // terminal revocation. The registry validates identity before either value563    // is changed, so a mismatch leaves the revocation intact.564    deps.upsertPairedDeviceAndClearRevocation(sourceDevice)565    sendFrame(channel, AdoptionFrame.Applied)566    return sourceDevice567}568569/**570 * SOURCE side: respond to an ADOPT_REQUEST. Gates on user consent, hands over the571 * root key, then records the receiver's returned identity as a paired device.572 * Returns null if consent is denied or the receiver's identity frame is invalid.573 */574suspend fun grantAdoption(575    channel: PairingTransport,576    request: AdoptionFrame.Request,577    deps: AdoptionSourceDeps,578    nowMs: () -> Long = { System.currentTimeMillis() },579): PairedDevice? {580    if (!deps.onConsent(request)) return null581582    val confirmation = receiveFrame(channel)583    if (!isAdoptConfirm(confirmation) || !(confirmation as AdoptionFrame.Confirm).confirmed) {584        return null585    }586587    var sourceLicense = deps.license()588    if (sourceLicense == null && request.license != null) {589        sourceLicense = runCatching {590            deps.applyLicense(request.license)591            deps.license()592        }.getOrNull()593    }594    if (sourceLicense == null) {595        sendFrame(channel, AdoptionFrame.Reject("ADOPT_PRO_REQUIRED"))596        throw IllegalStateException("ADOPT_PRO_REQUIRED")597    }598599    if (!deps.persistPendingHolder(request, nowMs())) return null600    val rootKeyHex = deps.rootKeyHex()601    if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")602603    var sourceIdentity = deps.sourceIdentity604    var grantAttempts = 0605    while (true) {606        sendFrame(channel, AdoptionFrame.Grant(607            rootKeyHex = rootKeyHex,608            vaultId = deps.vaultId(),609            license = sourceLicense,610            source = AdoptionFrame.Source(611                deviceId = sourceIdentity.deviceId,612                deviceName = sourceIdentity.deviceName,613                deviceType = sourceIdentity.deviceType.wireValue,614                longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,615                signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,616                wsPort = sourceIdentity.wsPort,617                relayUrl = deps.pairState?.relayUrl,618            ),619            snapshotCapable = request.snapshotCapable == true,620        ))621622        var identity = receiveFrame(channel)623624        // Receiver may reject the source's identity if it is in the receiver's625        // revocation ledger. Rotate and resend (one retry).626        if (identity is AdoptionFrame.Reject &&627            identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&628            grantAttempts == 0629        ) {630            sourceIdentity = deps.rotateSourceIdentity()631            grantAttempts++632            continue633        }634635        if (!isAdoptIdentity(identity)) return null636        identity as AdoptionFrame.Identity637638        var device = PairedDevice(639            deviceId = identity.deviceId,640            deviceName = identity.deviceName,641            deviceType = identity.deviceType,642            longTermPublicKeyHex = identity.longTermPublicKeyHex,643            signingPublicKeyHex = identity.signingPublicKeyHex,644            trustSource = "direct",645            rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,646            relayUrl = deps.pairState?.relayUrl,647            pairedAt = nowMs(),648        )649        if (deps.hasDeviceIdentityCollision(device)) {650            sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))651            identity = receiveFrame(channel)652            if (!isAdoptIdentity(identity)) return null653            identity as AdoptionFrame.Identity654            device = device.copy(655                deviceId = identity.deviceId,656                deviceName = identity.deviceName,657                deviceType = identity.deviceType,658                longTermPublicKeyHex = identity.longTermPublicKeyHex,659                signingPublicKeyHex = identity.signingPublicKeyHex,660            )661            if (deps.hasDeviceIdentityCollision(device)) {662                sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))663                return null664            }665        }666        deps.upsertPairedDevice(device)667        sendFrame(channel, AdoptionFrame.Complete)668        if (!isAdoptApplied(receiveFrame(channel))) return null669        if (!deps.completePendingHolder(request, device)) return null670        return device671    }672}673674/**675 * Wire codec. `classDiscriminator = "type"` reproduces the browser's flat676 * `{ "type": "ADOPT_…", … }` shape; `encodeDefaults = false` omits absent677 * optionals exactly like `JSON.stringify` drops `undefined`.678 */679val AdoptJson: Json = Json {680    classDiscriminator = "type"681    encodeDefaults = false682    ignoreUnknownKeys = true683}684685suspend fun sendFrame(channel: PairingTransport, frame: AdoptionFrame) {686    channel.send(AdoptJson.encodeToString(AdoptionFrame.serializer(), frame).toByteArray(Charsets.UTF_8))687}688689/** Decode one frame, tolerating a malformed/unknown payload by returning null. */690suspend fun receiveFrame(channel: PairingTransport): AdoptionFrame? =691    runCatching {692        AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(channel.receive(), Charsets.UTF_8))693    }.getOrNull()694695/**696 * Source side: chunk the vault snapshot and send it over the pairing channel.697 *698 * Wire shape (v2.9.9+, supplemental frame; mirrors browser v4.6.4):699 *   - N entries frames, each <= [MAX_SNAPSHOT_CHUNK_BYTES] serialized entries.700 *   - One supplemental frame always follows the entries. It carries the701 *     tombstones and, when configured, the duress slot. Sending the same frame702 *     count in both cases prevents a relay from learning duress presence.703 *     Keeping duress off the entries frame also prevents a sizeable sealed704 *     duress vault from pushing the entries frame over the wire ceiling.705 *706 * Frame budget ([MAX_SNAPSHOT_CHUNKS] = 200):707 *   - ONE of the 200 frames is always reserved for the supplemental frame;708 *     entries use at most 199 chunks. Excess entries are deferred to the sync709 *     fallback pipeline (sync carries entries and tombstones on Android too,710 *     so this is a graceful truncation). The supplemental frame is required711 *     even without duress so its presence cannot disclose configuration. When712 *     configured, it carries the duress slot; omitting it would leave the713 *     adopted device permanently without its duress vault.714 *715 * Oversized duress: duress that itself exceeds [SNAPSHOT_FRAME_WIRE_CEILING]716 * is rejected with a thrown error BEFORE any snapshot frame is sent. Hard stop;717 * the caller must split duress out of band. We do not silently truncate718 * duress; sync cannot restore it.719 *720 * Backward compat: pre-v2.9.9 senders put `duress_slot` on the entries721 * final chunk. `receiveVaultSnapshot` reads `duress_slot` off any chunk (a722 * duress-only frame has empty `entries` and the complete tombstone map),723 * so both shapes decode and both new->old / old->new directions interoperate.724 */725suspend fun sendVaultSnapshot(726    channel: PairingTransport,727    entries: Map<String, String>,728    tombstones: Map<String, Long>,729    duressSlot: String? = null,730) {731    val frames = buildAdoptSnapshotFrames(entries, tombstones, duressSlot)732    // PB-26-206 preflight with the SAME helper the receiver enforces: nothing733    // is sent until every frame fits the aggregate budget, so an over-budget734    // snapshot is never partially sent or silently truncated. The caller falls735    // through to the regular sync pipeline (deny-only: no wire-field change,736    // invitation prefix unchanged).737    val acc = createAdoptSnapshotBudget()738    val encoded = frames.map {739        AdoptJson.encodeToString(AdoptionFrame.serializer(), it).encodeToByteArray()740    }741    for (i in frames.indices) {742        val frame = frames[i]743        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, encoded[i].size)744    }745    for (raw in encoded) channel.send(SyncPadding.pad(raw))746}747748/**749 * Pure frame construction for [sendVaultSnapshot]: chunking, the duress-frame750 * reservation, and the oversized-duress hard stop. No I/O happens here, so751 * the preflight above can reject before the first byte goes out.752 */753private fun buildAdoptSnapshotFrames(754    entries: Map<String, String>,755    tombstones: Map<String, Long>,756    duressSlot: String?,757): List<AdoptionFrame.Snapshot> {758    val includeDuress = !duressSlot.isNullOrBlank()759    // Always reserve the supplemental frame so its presence cannot disclose760    // whether the source has a duress vault.761    val entryCap = MAX_SNAPSHOT_CHUNKS - 1762763    val chunks = mutableListOf<Map<String, String>>()764    var current = LinkedHashMap<String, String>()765    var currentBytes = 2 // "{}"766    for ((id, envelope) in entries) {767        // +1 for the separating comma; an overestimate only shrinks chunks.768        val entryBytes = AdoptJson.encodeToString(mapOf(id to envelope)).length + 1769        if (current.isNotEmpty() && currentBytes + entryBytes >= MAX_SNAPSHOT_CHUNK_BYTES) {770            chunks.add(current)771            current = LinkedHashMap()772            currentBytes = 2773        }774        current[id] = envelope775        currentBytes += entryBytes776    }777    chunks.add(current)778779    val entriesChunkCount = minOf(chunks.size, entryCap)780    val totalChunks = entriesChunkCount + 1781    val supplementalFrame = AdoptionFrame.Snapshot(782        chunkIndex = entriesChunkCount,783        chunkCount = totalChunks,784        entries = emptyMap(),785        tombstones = tombstones,786        duressSlot = duressSlot.takeIf { includeDuress },787    )788789    if (790        AdoptJson.encodeToString(AdoptionFrame.serializer(), supplementalFrame)791            .encodeToByteArray().size > SNAPSHOT_FRAME_WIRE_CEILING792    ) {793        if (includeDuress) throw SnapshotDuressFrameTooLargeException()794        throw IllegalStateException("ADOPT_SNAPSHOT_SUPPLEMENTAL_FRAME_TOO_LARGE")795    }796797    val frames = mutableListOf<AdoptionFrame.Snapshot>()798    for (index in 0 until entriesChunkCount) {799        frames.add(AdoptionFrame.Snapshot(800            chunkIndex = index,801            chunkCount = totalChunks,802            entries = chunks[index],803            tombstones = emptyMap(),804            duressSlot = null,805        ))806    }807    frames.add(supplementalFrame)808    return frames809}810811internal class SnapshotDuressFrameTooLargeException :812    IllegalStateException("ADOPT_SNAPSHOT_DURESS_FRAME_TOO_LARGE")813814/**815 * Receiver side: receive and reassemble every snapshot chunk. Adds raw frame816 * bytes to the aggregate counter before decoding (rejecting before JSON817 * deserialization when the next frame exceeds the remaining budget), then818 * enforces the per-frame wire ceiling, sequential 0-based chunk_index819 * ordering, a stable chunk_count within [MAX_SNAPSHOT_CHUNKS], and structural820 * validity of each frame. Merging goes through the shared aggregate helper:821 * every key/value and projected count is validated in one bounded pass before822 * anything lands in the accumulator, so a rejection leaves no partial adopted823 * state and the caller can fall back to the sync pipeline.824 */825suspend fun receiveVaultSnapshot(826    channel: PairingTransport,827): ReceivedSnapshot {828    val acc = createAdoptSnapshotBudget()829    var chunkCount = -1830    var received = 0831    while (chunkCount == -1 || received < chunkCount) {832        val wire = channel.receive()833        if (wire.size > MAX_PADDED_SNAPSHOT_FRAME_BYTES) {834            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")835        }836        val raw = runCatching { SyncPadding.unpad(wire) }837            .getOrElse { throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME", it) }838        if (raw.size > MAX_ADOPT_SNAPSHOT_BYTES - acc.bytes) {839            throw IllegalStateException("ADOPT_SNAPSHOT_OVER_BUDGET")840        }841        if (raw.size > SNAPSHOT_FRAME_WIRE_CEILING) {842            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_TOO_LARGE")843        }844        val frame = runCatching {845            AdoptJson.decodeFromString(AdoptionFrame.serializer(), String(raw, Charsets.UTF_8))846        }.getOrNull()847        if (!isAdoptSnapshot(frame)) throw IllegalStateException("ADOPT_SNAPSHOT_INVALID_FRAME")848        frame as AdoptionFrame.Snapshot849        if (chunkCount == -1) {850            chunkCount = frame.chunkCount851            if (chunkCount > MAX_SNAPSHOT_CHUNKS) {852                throw IllegalStateException("ADOPT_SNAPSHOT_TOO_MANY_CHUNKS")853            }854        } else if (frame.chunkCount != chunkCount) {855            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_COUNT_MISMATCH")856        }857        if (frame.chunkIndex != received) {858            throw IllegalStateException("ADOPT_SNAPSHOT_CHUNK_OUT_OF_ORDER")859        }860        applyAdoptSnapshotFrame(acc, frame.entries, frame.tombstones, frame.duressSlot, raw.size)861        received++862    }863    return ReceivedSnapshot(acc.entries, acc.tombstones, acc.duressSlot)864}865866fun isDeviceType(value: String): Boolean =867    DeviceType.entries.any { it.wireValue == value }