SyncMessage.kt

6.1 KB · raw

1package com.peachpasswords.sync23import kotlinx.serialization.SerialName4import kotlinx.serialization.Serializable5import kotlinx.serialization.json.Json67/**8 * Sync wire protocol — exact port of the browser `SyncMessage`9 * union (shared/sync-types.ts). Each frame is JSON with a `type` discriminator,10 * sent over the Noise-NK-encrypted session. Entries travel as opaque base6411 * ciphertext envelopes; the coordinator never sees plaintext.12 */13@Serializable14sealed class SyncMessage {15    @Serializable16    @SerialName("SYNC_HELLO")17    data class Hello(18        val vaultId: String,19        val deviceId: String,20        val version: Long,21        val deviceTime: Long,22        /**23         * Advertises equal-version device-graph exchange support. Older peers24         * omit this field and retain the legacy SYNC_DONE fast path.25         */26        val deviceManifestVersion: Int? = null,27    ) : SyncMessage()2829    @Serializable30    @SerialName("SYNC_MANIFEST")31    data class Manifest(32        val entries: Map<String, Long>,33        val tombstones: Map<String, Long>,34    ) : SyncMessage()3536    @Serializable37    @SerialName("SYNC_REQUEST")38    data class Request(val entryIds: List<String>) : SyncMessage()3940    @Serializable41    @SerialName("SYNC_ENTRIES")42    data class Entries(val entries: Map<String, String>) : SyncMessage()4344    @Serializable45    @SerialName("SYNC_TOMBSTONES")46    data class Tombstones(val tombstones: Map<String, Long>) : SyncMessage()4748    @Serializable49    @SerialName("SYNC_DEVICE_MANIFEST")50    data class DeviceManifest(val manifest: SignedDeviceManifest?) : SyncMessage()5152    @Serializable53    @SerialName("SYNC_DONE")54    data class Done(55        val entriesReceived: Int = 0,56        val entriesSent: Int = 0,57    ) : SyncMessage()5859    @Serializable60    @SerialName("SYNC_ERROR")61    data class Error(val error: String) : SyncMessage()62}6364@Serializable65data class ManifestDeviceEntry(66    val deviceId: String,67    val deviceName: String,68    val deviceType: String,69    val longTermPublicKeyHex: String,70    val signingPublicKeyHex: String,71    val wsPort: Int? = null,72    val relayUrl: String? = null,73    val pairedAt: Long,74    /** Number of vouching edges from a directly paired device. */75    val vouchDepth: Int = 0,76)7778@Serializable79data class DeviceManifestBody(80    val manifestVersion: Int,81    val issuerDeviceId: String,82    val issuedAt: Long,83    val devices: List<ManifestDeviceEntry>,84    val revoked: List<DeviceRevocation> = emptyList(),85)8687/**88 * A device that must no longer be synced with. Revocation is TERMINAL: once a89 * deviceId OR its long-term key appears here, no manifest may re-vouch it and90 * no pending entry carrying it may be confirmed. Tombstone-style91 * newest-timestamp-wins ordering is deliberately NOT used — every timestamp in92 * a manifest is peer-supplied, so a peer could resurrect a revoked device just93 * by issuing a fresh `pairedAt`. Re-admitting requires a direct, SAS-confirmed94 * re-pair with a physically present user.95 *96 * HONEST LIMIT: signing keys derive from the shared vault root key, so these97 * signatures prove vault membership, not device identity. A revoked device98 * still holds the root key and, running modified software, can ignore its own99 * revocation. This stops honest peers talking to it; it is not a cryptographic100 * ejection. A genuinely compromised device needs the master password and101 * recovery words rotated.102 */103@Serializable104data class DeviceRevocation(105    val deviceId: String,106    /** Load-bearing, not descriptive: `deviceId` is whatever an issuing107     *  manifest says it is, so the key is what re-vouching is matched against.108     *  [NO_KEY_SENTINEL] means no key was ever stored and matches nothing. */109    val longTermPublicKeyHex: String,110    val revokedAt: Long,111    val revokedByDeviceId: String,112)113114@Serializable115data class SignedDeviceManifest(116    val body: DeviceManifestBody,117    /** Hex-encoded 64-byte Ed25519 signature over the canonicalised body. */118    val signatureHex: String,119)120121/**122 * The wire codec. `classDiscriminator = "type"` reproduces the browser's flat123 * `{ "type": "SYNC_HELLO", ... }` shape exactly; `encodeDefaults` keeps the124 * optional SYNC_DONE counters on the wire.125 */126val SyncJson: Json = Json {127    classDiscriminator = "type"128    encodeDefaults = true129    ignoreUnknownKeys = true130}131132fun SyncMessage.encodeToBytes(): ByteArray =133    SyncJson.encodeToString(SyncMessage.serializer(), this).toByteArray(Charsets.UTF_8)134135fun decodeSyncMessage(bytes: ByteArray): SyncMessage =136    SyncJson.decodeFromString(SyncMessage.serializer(), String(bytes, Charsets.UTF_8))137138/**139 * Reject a decoded frame whose declared structure exceeds the protocol's140 * limits, before any diff or persistence work touches it (PAI-2026-003).141 *142 * [requireSyncFrameSize] bounds a frame's bytes, not its shape: a 24 MiB frame143 * of one-character keys carries millions of map entries, and the String and144 * Map allocation for those — plus the diff and apply passes that follow —145 * dwarfs the frame itself. LockedSyncSpoolStore already enforced these same146 * bounds on the locked spool; the unlocked coordinator had none.147 */148fun SyncMessage.requireBounded() {149    fun checkIds(ids: Collection<String>, cap: Int, what: String) {150        if (ids.size > cap) throw SyncStructureTooLargeException(what)151        if (ids.any { it.length > SyncLimits.MAX_ID_LENGTH }) {152            throw SyncStructureTooLargeException("$what identifier length")153        }154    }155    when (this) {156        is SyncMessage.Manifest -> {157            checkIds(entries.keys, SyncLimits.MAX_ENTRY_COUNT, "manifest entries")158            checkIds(tombstones.keys, SyncLimits.MAX_TOMBSTONE_COUNT, "manifest tombstones")159        }160        is SyncMessage.Request -> checkIds(entryIds, SyncLimits.MAX_REQUEST_ENTRY_COUNT, "request ids")161        is SyncMessage.Entries -> {162            checkIds(entries.keys, SyncLimits.MAX_ENTRY_COUNT, "entries")163            if (entries.values.any { it.length > SyncLimits.MAX_ENTRY_ENVELOPE_BYTES }) {164                throw SyncStructureTooLargeException("entry envelope")165            }166        }167        is SyncMessage.Tombstones -> checkIds(tombstones.keys, SyncLimits.MAX_TOMBSTONE_COUNT, "tombstones")168        else -> Unit169    }170}