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)1415fun requireSyncFrameSize(size: Int) {16 if (size > MAX_SYNC_FRAME_BYTES) {17 throw SyncFrameTooLargeException("sync frame exceeds $MAX_SYNC_FRAME_BYTES bytes")18 }19}2021/**22 * Timestamp bounds, ported from peach-browser `src/shared/sync-limits.ts`.23 * Both sides must agree, so change them together.24 */25object SyncLimits {26 const val MAX_ENTRY_COUNT = 100_00027 const val MAX_TOMBSTONE_COUNT = 100_00028 const val MAX_ENTRY_PLAINTEXT_BYTES = 512 * 102429 const val MAX_ENTRY_ENVELOPE_BYTES = (MAX_ENTRY_PLAINTEXT_BYTES * 4) / 3 + 6430 /**31 * HV-1: maximum tolerated forward clock skew on any timestamp received from32 * a sync peer. A peer whose clock is slightly ahead still merges cleanly,33 * but a deliberately far-future `modifiedAt`/`deletedAt` can no longer34 * permanently pin a malicious value against honest local edits.35 */36 const val MAX_CLOCK_SKEW_MS = 5 * 60 * 1000L3738 /**39 * Clamp a peer-supplied timestamp to `now + MAX_CLOCK_SKEW_MS`. Applied to40 * every remote `modifiedAt` and `deletedAt` BEFORE it is compared against41 * any local timestamp.42 *43 * See the HOLE 2 coverage audit in the browser's `sync-limits.ts` for the44 * full list of peer-supplied timestamps and what bounds each one.45 */46 fun clampSyncTimestamp(ts: Long, now: Long = System.currentTimeMillis()): Long =47 minOf(ts, now + MAX_CLOCK_SKEW_MS)48}