SyncLimits.kt
1package com.peachpasswords.sync23import java.io.IOException45/**6 * Cloudflare Workers caps one WebSocket message at 32 MiB. Keep a generous7 * margin for the Noise authentication tag and platform framing overhead.8 */9const val MAX_SYNC_FRAME_BYTES: Int = 24 * 1024 * 10241011class SyncFrameTooLargeException(12 message: String = "sync frame too large (WebSocket close 1009)",13) : IOException(message)1415/**16 * A decoded frame whose declared structure exceeds the protocol's limits. An17 * IOException so it lands in the same ERRORED outcome as a transport failure.18 */19class SyncStructureTooLargeException(what: String) : IOException("sync structure exceeds limits: $what")2021fun requireSyncFrameSize(size: Int) {22 if (size > MAX_SYNC_FRAME_BYTES) {23 throw SyncFrameTooLargeException("sync frame exceeds $MAX_SYNC_FRAME_BYTES bytes")24 }25}2627/**28 * Timestamp bounds, ported from peach-browser `src/shared/sync-limits.ts`.29 * Both sides must agree, so change them together.30 */31object SyncLimits {32 const val MAX_ENTRY_COUNT = 100_00033 const val MAX_TOMBSTONE_COUNT = 100_00034 /**35 * Entry and device identifiers are UUID strings (36 chars). The cap exists36 * so a peer cannot pad a map with multi-kilobyte keys — the count limits37 * alone leave the cost of any single key unbounded.38 */39 const val MAX_ID_LENGTH = 12840 const val MAX_ENTRY_PLAINTEXT_BYTES = 512 * 102441 const val MAX_ENTRY_ENVELOPE_BYTES = (MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 6442 /**43 * HV-1: maximum tolerated forward clock skew on any timestamp received from44 * a sync peer. A peer whose clock is slightly ahead still merges cleanly,45 * but a deliberately far-future `modifiedAt`/`deletedAt` can no longer46 * permanently pin a malicious value against honest local edits.47 */48 const val MAX_CLOCK_SKEW_MS = 5 * 60 * 1000L4950 /**51 * Clamp a peer-supplied timestamp to `now + MAX_CLOCK_SKEW_MS`. Applied to52 * every remote `modifiedAt` and `deletedAt` BEFORE it is compared against53 * any local timestamp.54 *55 * See the HOLE 2 coverage audit in the browser's `sync-limits.ts` for the56 * full list of peer-supplied timestamps and what bounds each one.57 */58 fun clampSyncTimestamp(ts: Long, now: Long = System.currentTimeMillis()): Long =59 minOf(ts, now + MAX_CLOCK_SKEW_MS)60}