diff --git a/app/src/main/java/cc/skysparkle/matewave/MainActivity.kt b/app/src/main/java/cc/skysparkle/matewave/MainActivity.kt index 9855318..4ee7b90 100644 --- a/app/src/main/java/cc/skysparkle/matewave/MainActivity.kt +++ b/app/src/main/java/cc/skysparkle/matewave/MainActivity.kt @@ -333,9 +333,12 @@ private fun AppNavHost() { viewModel.startVsPlayerNetwork(transport, PieceColor.WHITE, timeControl, isHost = true) navController.navigate("game") }, - onJoin = { type, timeControl, targetId -> + onJoin = { type, timeControl, targetId, expectedUserId -> val transport = if (type == TransportType.BLUETOOTH) bleTransport else lanTransport - viewModel.startVsPlayerNetwork(transport, PieceColor.BLACK, timeControl, isHost = false, targetId = targetId) + viewModel.startVsPlayerNetwork( + transport, PieceColor.BLACK, timeControl, isHost = false, + targetId = targetId, expectedUserId = expectedUserId + ) navController.navigate("game") }, onBack = { navController.popBackStack() } diff --git a/app/src/main/java/cc/skysparkle/matewave/clock/GameClock.kt b/app/src/main/java/cc/skysparkle/matewave/clock/GameClock.kt index 3588e6a..a8fb6fa 100644 --- a/app/src/main/java/cc/skysparkle/matewave/clock/GameClock.kt +++ b/app/src/main/java/cc/skysparkle/matewave/clock/GameClock.kt @@ -98,6 +98,12 @@ class GameClock(private val timeControl: TimeControl, private val scope: Corouti publish() } + /** Time left for [side] right now, including the part of the current second already used. */ + fun remainingMillis(side: PieceColor): Long { + account() + return if (side == PieceColor.WHITE) whiteLeft else blackLeft + } + fun restore(whiteMillis: Long, blackMillis: Long) { if (unlimited) return account() diff --git a/app/src/main/java/cc/skysparkle/matewave/data/ProfileStore.kt b/app/src/main/java/cc/skysparkle/matewave/data/ProfileStore.kt index fb72cde..6290af6 100644 --- a/app/src/main/java/cc/skysparkle/matewave/data/ProfileStore.kt +++ b/app/src/main/java/cc/skysparkle/matewave/data/ProfileStore.kt @@ -2,8 +2,12 @@ package cc.skysparkle.matewave.data import cc.skysparkle.matewave.ai.AiDifficulty import android.content.Context +import cc.skysparkle.matewave.network.PeerLimits +import cc.skysparkle.matewave.security.toHex import org.json.JSONArray import org.json.JSONObject +import java.io.File +import java.security.MessageDigest import kotlin.math.pow import kotlin.math.roundToInt @@ -111,6 +115,7 @@ object FriendsStore { private const val PREFS = "chess_friends_prefs" private const val KEY_LIST = "friends_json" private const val MAX_FRIENDS = 30 + private const val IMAGE_DIR = "friend_images" private var appContext: Context? = null @@ -125,6 +130,36 @@ object FriendsStore { private fun prefs() = appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE) + // Avatars and backgrounds live in files, one per image: in the settings XML they made a file + // of up to tens of megabytes that was read at start and rewritten on every change. + private fun imageDir(): File? = appContext?.let { File(it.filesDir, IMAGE_DIR) } + + private fun imageFile(userId: String, kind: String): File? { + val dir = imageDir() ?: return null + val digest = MessageDigest.getInstance("SHA-256").digest(userId.toByteArray(Charsets.UTF_8)) + return File(dir, "${digest.toHex(16)}_$kind") + } + + private fun readImage(userId: String, kind: String): String? = + imageFile(userId, kind)?.takeIf { it.isFile }?.let { runCatching { it.readText() }.getOrNull() } + + private fun writeImage(userId: String, kind: String, base64: String?) { + val file = imageFile(userId, kind) ?: return + if (base64 == null) { + file.delete() + return + } + runCatching { + file.parentFile?.mkdirs() + val tmp = File(file.parentFile, file.name + ".tmp") + tmp.writeText(base64) + if (!tmp.renameTo(file)) { + file.delete() + tmp.renameTo(file) + } + } + } + fun list(): List = synchronized(lock) { readAll() } private fun readAll(): List { @@ -136,15 +171,21 @@ object FriendsStore { return emptyList() } val result = ArrayList() + var hasInlineImages = false for (i in 0 until arr.length()) { try { val o = arr.getJSONObject(i) + val userId = o.optString("uid", "").ifBlank { o.getString("name") } + // Older versions kept the images inline; they move to files on the next write. + val inlineAvatar = if (o.has("avatar")) o.getString("avatar") else null + val inlineBackground = if (o.has("background")) o.getString("background") else null + if (inlineAvatar != null || inlineBackground != null) hasInlineImages = true result.add( FriendEntry( - userId = o.optString("uid", "").ifBlank { o.getString("name") }, + userId = userId, name = o.getString("name"), - avatarBase64 = if (o.has("avatar")) o.getString("avatar") else null, - backgroundBase64 = if (o.has("background")) o.getString("background") else null, + avatarBase64 = inlineAvatar ?: if (o.optBoolean("a")) readImage(userId, "a") else null, + backgroundBase64 = inlineBackground ?: if (o.optBoolean("b")) readImage(userId, "b") else null, elo = o.optInt("elo", 1200), lastPlayedMs = o.optLong("t", 0), favorite = o.optBoolean("fav", false), @@ -156,24 +197,35 @@ object FriendsStore { } val sorted = result.sortedByDescending { it.lastPlayedMs } cached = sorted + if (hasInlineImages) writeAll(sorted, previous = emptyList()) return sorted } - private fun writeAll(entries: List) { + private fun writeAll(entries: List, previous: List = readAll()) { val p = prefs() ?: return + val before = previous.associateBy { it.userId } val arr = JSONArray() entries.forEach { f -> + val old = before[f.userId] + // Image files are touched only when the image itself changed. + if (old == null || old.avatarBase64 != f.avatarBase64) writeImage(f.userId, "a", f.avatarBase64) + if (old == null || old.backgroundBase64 != f.backgroundBase64) writeImage(f.userId, "b", f.backgroundBase64) val o = JSONObject() o.put("uid", f.userId) o.put("name", f.name) - if (f.avatarBase64 != null) o.put("avatar", f.avatarBase64) - if (f.backgroundBase64 != null) o.put("background", f.backgroundBase64) + if (f.avatarBase64 != null) o.put("a", true) + if (f.backgroundBase64 != null) o.put("b", true) o.put("elo", f.elo) o.put("t", f.lastPlayedMs) if (f.favorite) o.put("fav", true) if (f.lastSeenMs > 0) o.put("s", f.lastSeenMs) arr.put(o) } + val kept = entries.mapTo(HashSet()) { it.userId } + previous.filter { it.userId !in kept }.forEach { gone -> + writeImage(gone.userId, "a", null) + writeImage(gone.userId, "b", null) + } p.edit().putString(KEY_LIST, arr.toString()).apply() cached = entries.sortedByDescending { it.lastPlayedMs } } @@ -182,6 +234,11 @@ object FriendsStore { synchronized(lock) { readAll() } } + // Names and ratings also arrive from presence announcements, so they are bounded here too. + private fun cleanName(name: String): String = name.filterNot { it.isISOControl() }.take(PeerLimits.MAX_NAME_CHARS) + + private fun cleanElo(elo: Int): Int = elo.coerceIn(PeerLimits.MIN_ELO, PeerLimits.MAX_ELO) + fun updateProfile( userId: String, name: String, @@ -192,8 +249,8 @@ object FriendsStore { synchronized(lock) { val existing = readAll().firstOrNull { it.userId == userId } ?: return val updated = existing.copy( - name = name.ifBlank { existing.name }, - elo = if (elo > 0) elo else existing.elo, + name = cleanName(name).ifBlank { existing.name }, + elo = if (elo > 0) cleanElo(elo) else existing.elo, avatarBase64 = avatarBase64 ?: existing.avatarBase64, backgroundBase64 = backgroundBase64 ?: existing.backgroundBase64 ) @@ -217,12 +274,13 @@ object FriendsStore { backgroundBase64: String? = null ): FriendEntry = synchronized(lock) { val existing = readAll().firstOrNull { it.userId == userId } + val clean = cleanName(name) val merged = FriendEntry( userId = userId, - name = name.ifBlank { existing?.name ?: name }, + name = clean.ifBlank { existing?.name ?: clean }, avatarBase64 = avatarBase64 ?: existing?.avatarBase64, backgroundBase64 = backgroundBase64 ?: existing?.backgroundBase64, - elo = if (elo > 0) elo else (existing?.elo ?: 1200), + elo = if (elo > 0) cleanElo(elo) else (existing?.elo ?: 1200), lastPlayedMs = System.currentTimeMillis(), favorite = existing?.favorite ?: false, lastSeenMs = existing?.lastSeenMs ?: 0 diff --git a/app/src/main/java/cc/skysparkle/matewave/network/PeerLimits.kt b/app/src/main/java/cc/skysparkle/matewave/network/PeerLimits.kt new file mode 100644 index 0000000..f59d8a1 --- /dev/null +++ b/app/src/main/java/cc/skysparkle/matewave/network/PeerLimits.kt @@ -0,0 +1,39 @@ +package cc.skysparkle.matewave.network + +/** Bounds for what another device may send us; anything outside them is not stored or used. */ +object PeerLimits { + const val MAX_NAME_CHARS = 40 + const val MAX_USER_ID_CHARS = 64 + const val MIN_ELO = 100 + const val MAX_ELO = 3000 + const val MAX_INITIAL_SECONDS = 3 * 60 * 60 + const val MAX_INCREMENT_SECONDS = 180 + + /** "No time limit" is sent as Int.MAX_VALUE; 0 means the peer sent no time control. */ + private fun isTimeControl(initialSeconds: Int, incrementSeconds: Int): Boolean = + (initialSeconds == 0 || initialSeconds == Int.MAX_VALUE || initialSeconds in 1..MAX_INITIAL_SECONDS) && + incrementSeconds in 0..MAX_INCREMENT_SECONDS + + fun isPlausibleName(name: String): Boolean = + name.isNotBlank() && name.length <= MAX_NAME_CHARS && name.none { it.isISOControl() } + + fun isPlausibleUserId(userId: String): Boolean = + userId.isNotBlank() && userId.length <= MAX_USER_ID_CHARS && userId.none { it.isISOControl() } + + /** + * Checked before the profile is trusted or stored. The fields are signed as they are, so an + * out-of-range profile is refused rather than trimmed. + */ + fun isPlausibleProfile(msg: GameMessage.ProfileMsg): Boolean = + isPlausibleUserId(msg.userId) && + isPlausibleName(msg.name) && + msg.elo in MIN_ELO..MAX_ELO && + isTimeControl(msg.initialSeconds, msg.incrementSeconds) + + /** + * The most the opponent's clock may show after their move: what our clock gives them, plus + * the increment and some slack for network delay. A higher claim would mean time not spent. + */ + fun maxOpponentClockAfterMove(localRemainingMs: Long, incrementMs: Long, toleranceMs: Long): Long = + localRemainingMs.coerceAtLeast(0) + incrementMs + toleranceMs +} diff --git a/app/src/main/java/cc/skysparkle/matewave/ui/components/ChatImage.kt b/app/src/main/java/cc/skysparkle/matewave/ui/components/ChatImage.kt index 569d88f..63b7e98 100644 --- a/app/src/main/java/cc/skysparkle/matewave/ui/components/ChatImage.kt +++ b/app/src/main/java/cc/skysparkle/matewave/ui/components/ChatImage.kt @@ -86,21 +86,46 @@ private object DecodedImageCache { fun put(key: String, bitmap: Bitmap) { cache.put(key, bitmap) } } +/** Larger images (from the opponent) are refused; ours never exceed [MAX_DIMENSION_PX]. */ +const val MAX_INCOMING_IMAGE_PX = 4096 + +/** Upper bound for the decoded size when the caller does not ask for a smaller one. */ +private const val DEFAULT_DECODE_PX = 1280 + +/** Width and height of an encoded image, or null if it is not a readable image. */ +private fun imageBounds(bytes: ByteArray): Pair? { + val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) + return if (bounds.outWidth > 0 && bounds.outHeight > 0) bounds.outWidth to bounds.outHeight else null +} + +/** + * Checks an image received from another device before it is shown or stored: it must be a + * readable image no larger than [MAX_INCOMING_IMAGE_PX] on either side. A small file can + * declare a huge resolution, and decoding it at full size would run out of memory. + */ +fun isAcceptableIncomingImage(base64: String): Boolean = try { + val size = imageBounds(Base64.decode(base64, Base64.NO_WRAP)) + size != null && size.first <= MAX_INCOMING_IMAGE_PX && size.second <= MAX_INCOMING_IMAGE_PX +} catch (e: Exception) { + false +} + fun decodeChatImage(base64: String, maxDimension: Int = 0): Bitmap? { return try { val bytes = Base64.decode(base64, Base64.NO_WRAP) - if (maxDimension <= 0) { - BitmapFactory.decodeByteArray(bytes, 0, bytes.size) - } else { - val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds) - var sample = 1 - while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxDimension) sample *= 2 - val options = BitmapFactory.Options().apply { inSampleSize = sample } - BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) - } + // The size is always checked first: the image may come from another device. + val (width, height) = imageBounds(bytes) ?: return null + if (width > MAX_INCOMING_IMAGE_PX || height > MAX_INCOMING_IMAGE_PX) return null + val target = if (maxDimension > 0) maxDimension else DEFAULT_DECODE_PX + var sample = 1 + while (maxOf(width, height) / (sample * 2) >= target) sample *= 2 + val options = BitmapFactory.Options().apply { inSampleSize = sample } + BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) } catch (e: Exception) { null + } catch (e: OutOfMemoryError) { + null } } diff --git a/app/src/main/java/cc/skysparkle/matewave/ui/screens/ConnectionScreen.kt b/app/src/main/java/cc/skysparkle/matewave/ui/screens/ConnectionScreen.kt index 107daaf..44c92b9 100644 --- a/app/src/main/java/cc/skysparkle/matewave/ui/screens/ConnectionScreen.kt +++ b/app/src/main/java/cc/skysparkle/matewave/ui/screens/ConnectionScreen.kt @@ -77,14 +77,16 @@ private data class NearbyEntry( val elo: Int?, val type: TransportType, val address: String, - val avatar: String? + val avatar: String?, + /** Player id from the signed Wi-Fi announcement; checked against the profile after connecting. */ + val playerId: String? = null ) @Composable fun ConnectionScreen( presence: LocalPresence, onStartHost: (TimeControl) -> Unit, - onJoin: (TransportType, TimeControl, targetId: String) -> Unit, + onJoin: (TransportType, TimeControl, targetId: String, expectedUserId: String?) -> Unit, onBack: () -> Unit ) { val context = LocalContext.current @@ -146,7 +148,8 @@ fun ConnectionScreen( elo = peer.elo, type = TransportType.LAN, address = peer.address, - avatar = friends.firstOrNull { it.userId == peer.playerId }?.avatarBase64 + avatar = friends.firstOrNull { it.userId == peer.playerId }?.avatarBase64, + playerId = peer.playerId ) } val lanFingerprints = peers.values.map { it.fingerprint }.filter { it.isNotEmpty() } @@ -263,7 +266,7 @@ fun ConnectionScreen( modifier = Modifier .clip(RoundedCornerShape(50)) .background(Lime) - .clickable { onJoin(entry.type, timeControl, entry.address) } + .clickable { onJoin(entry.type, timeControl, entry.address, entry.playerId) } .padding(horizontal = 14.dp, vertical = 6.dp) ) } diff --git a/app/src/main/java/cc/skysparkle/matewave/viewmodel/GameViewModel.kt b/app/src/main/java/cc/skysparkle/matewave/viewmodel/GameViewModel.kt index 7c69202..a6bc399 100644 --- a/app/src/main/java/cc/skysparkle/matewave/viewmodel/GameViewModel.kt +++ b/app/src/main/java/cc/skysparkle/matewave/viewmodel/GameViewModel.kt @@ -26,6 +26,7 @@ import cc.skysparkle.matewave.network.ConnectionTransport import cc.skysparkle.matewave.network.GameMessage import cc.skysparkle.matewave.network.NetworkLog import cc.skysparkle.matewave.network.NetworkMetrics +import cc.skysparkle.matewave.network.PeerLimits import cc.skysparkle.matewave.network.TransportType import cc.skysparkle.matewave.puzzles.Puzzle import cc.skysparkle.matewave.security.DeviceKeys @@ -43,6 +44,7 @@ import cc.skysparkle.matewave.spectate.SpectatorResult import cc.skysparkle.matewave.spectate.SpectatorResults import cc.skysparkle.matewave.spectate.SpectatorSnapshot import cc.skysparkle.matewave.stats.Stats +import cc.skysparkle.matewave.ui.components.isAcceptableIncomingImage import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay @@ -185,8 +187,10 @@ class GameViewModel : ViewModel() { private var sessionGeneration = 0 private var networkGameId: String = "" private var pendingOpponentImages: Pair? = null + + // The player picked in the nearby list; whoever answers must be that player. + private var expectedOpponentUserId: String? = null private var currentPly: Int = 0 - private var lastOpponentRemaining: Long = Long.MAX_VALUE // Spectating: the host serves spectators, both players announce the game's tag. private var spectators: SpectatorBroadcaster? = null @@ -711,7 +715,8 @@ class GameViewModel : ViewModel() { myColor: PieceColor, timeControl: TimeControl, isHost: Boolean, - targetId: String? = null + targetId: String? = null, + expectedUserId: String? = null ) { pendingLeave?.let { (job, oldTransport) -> job.cancel() @@ -730,6 +735,7 @@ class GameViewModel : ViewModel() { this.transport = transport lastNetworkTimeControl = timeControl isNetworkHost = isHost + expectedOpponentUserId = expectedUserId?.takeIf { it.isNotBlank() } ephemeralKeys = DeviceKeys.generateEphemeral() @@ -739,7 +745,6 @@ class GameViewModel : ViewModel() { opponentFlagJob = null networkGameId = if (isHost) java.util.UUID.randomUUID().toString() else "" currentPly = 0 - lastOpponentRemaining = Long.MAX_VALUE _clockState.value = null _uiState.value = GameUiState( @@ -848,6 +853,13 @@ class GameViewModel : ViewModel() { ) } + /** The image if it may be shown and stored, otherwise null (and a log line). */ + private fun acceptedIncomingImage(base64: String): String? { + if (base64.length <= MAX_CHAT_IMAGE_CHARS && isAcceptableIncomingImage(base64)) return base64 + NetworkLog.log("GAME", "Unreadable or oversized profile image rejected") + return null + } + private fun belongsToCurrentGame(gameId: String): Boolean = gameId.isEmpty() || networkGameId.isEmpty() || gameId == networkGameId @@ -901,9 +913,14 @@ class GameViewModel : ViewModel() { NetworkLog.log("GAME", "Oversized chat message rejected") return } + if (msg.imageBase64 != null && !isAcceptableIncomingImage(msg.imageBase64)) { + NetworkLog.log("GAME", "Unreadable or oversized chat image rejected") + return + } val state = _uiState.value _uiState.value = state.copy( - chatMessages = state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false), + chatMessages = (state.chatMessages + ChatEntry(msg.text, msg.imageBase64, fromMe = false)) + .takeLast(MAX_CHAT_ENTRIES), unreadChatCount = state.unreadChatCount + 1 ) } @@ -976,8 +993,8 @@ class GameViewModel : ViewModel() { } is GameMessage.ProfileImagesMsg -> { if (!belongsToCurrentGame(msg.gameId)) return - val avatar = msg.avatarBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS } - val background = msg.backgroundBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS } + val avatar = msg.avatarBase64?.let(::acceptedIncomingImage) + val background = msg.backgroundBase64?.let(::acceptedIncomingImage) if (avatar == null && background == null) return val current = _uiState.value.opponentProfile if (current == null) { @@ -1051,17 +1068,17 @@ class GameViewModel : ViewModel() { val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L } val increment = lastNetworkTimeControl?.let { it.incrementSeconds * 1000L } ?: 0L - val allowedMax = if (lastOpponentRemaining == Long.MAX_VALUE) { - limit ?: Long.MAX_VALUE - } else { - lastOpponentRemaining + increment + CLOCK_TOLERANCE_MS - } + // Our own clock has been running the opponent's time while they thought, so their claim + // may not exceed it by more than the increment and network slack. + val allowedMax = clock?.remainingMillis(opponentColor) + ?.let { PeerLimits.maxOpponentClockAfterMove(it, increment, CLOCK_TOLERANCE_MS) } + ?: limit ?: Long.MAX_VALUE if (msg.remainingMillisSelf >= 0 && (limit == null || msg.remainingMillisSelf <= limit) && msg.remainingMillisSelf <= allowedMax ) { - lastOpponentRemaining = msg.remainingMillisSelf - clock?.applyRemoteTime(opponentColor, msg.remainingMillisSelf) + // The reported time already includes the increment; makeMove below adds it again. + clock?.applyRemoteTime(opponentColor, (msg.remainingMillisSelf - increment).coerceAtLeast(0)) } else if (msg.remainingMillisSelf > 0) { NetworkLog.log("GAME", "Invalid clock value from opponent rejected: ${msg.remainingMillisSelf}") } @@ -1077,6 +1094,12 @@ class GameViewModel : ViewModel() { NetworkLog.log("GAME", "Repeated profile in current session ignored") return } + if (!PeerLimits.isPlausibleProfile(msg)) { + // Nothing of it is stored: no key, no friend entry. The connection is closed. + NetworkLog.log("GAME", "Profile with out-of-range fields rejected, disconnecting") + transport?.disconnect() + return + } val peers = knownPeers if (peers == null) { NetworkLog.log("GAME", "Key store not ready, profile rejected") @@ -1125,7 +1148,11 @@ class GameViewModel : ViewModel() { } markReadyIfPossible() - _uiState.value = _uiState.value.copy(opponentUnverified = trust == TrustResult.UNSIGNED) + val unexpected = expectedOpponentUserId?.let { it != msg.userId } == true + if (unexpected) { + NetworkLog.log("GAME", "Opponent is not the player picked in the nearby list") + } + _uiState.value = _uiState.value.copy(opponentUnverified = trust == TrustResult.UNSIGNED || unexpected) val pending = pendingOpponentImages pendingOpponentImages = null @@ -1133,8 +1160,8 @@ class GameViewModel : ViewModel() { userId = msg.userId, name = msg.name, elo = msg.elo, - avatarBase64 = msg.avatarBase64 ?: pending?.first, - backgroundBase64 = msg.backgroundBase64 ?: pending?.second + avatarBase64 = msg.avatarBase64?.let(::acceptedIncomingImage) ?: pending?.first, + backgroundBase64 = msg.backgroundBase64?.let(::acceptedIncomingImage) ?: pending?.second ) _uiState.value = _uiState.value.copy( opponentProfile = Profile( @@ -1240,7 +1267,6 @@ class GameViewModel : ViewModel() { opponentFlagJob?.cancel() opponentFlagJob = null currentPly = 0 - lastOpponentRemaining = Long.MAX_VALUE val start = Board.startPosition() resetHistory(start) @@ -1349,7 +1375,8 @@ class GameViewModel : ViewModel() { val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS) if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return _uiState.value = _uiState.value.copy( - chatMessages = _uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true) + chatMessages = (_uiState.value.chatMessages + ChatEntry(trimmed, null, fromMe = true)) + .takeLast(MAX_CHAT_ENTRIES) ) } @@ -1362,7 +1389,8 @@ class GameViewModel : ViewModel() { } if (!sendGameMessage(GameMessage.ChatMsg(imageBase64 = base64, gameId = networkGameId))) return _uiState.value = _uiState.value.copy( - chatMessages = _uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true) + chatMessages = (_uiState.value.chatMessages + ChatEntry(null, base64, fromMe = true)) + .takeLast(MAX_CHAT_ENTRIES) ) } @@ -1400,7 +1428,10 @@ class GameViewModel : ViewModel() { viewModelScope.launch { var serving = false try { - val port = withContext(Dispatchers.IO) { runCatching { hub.start() }.getOrNull() } + // Spectators come over Wi-Fi; other interfaces (mobile data) are not listened on. + val port = withContext(Dispatchers.IO) { + runCatching { hub.start(cc.skysparkle.matewave.share.LocalNetwork.wifiInet4()) }.getOrNull() + } if (port == null) NetworkLog.log("SPECTATE", "Could not open the spectator port") // The game may have ended while the port was opening. if (port == null || generation != sessionGeneration || !spectatingDecided || spectateTag.isEmpty()) return@launch @@ -1589,6 +1620,7 @@ class GameViewModel : ViewModel() { const val MAX_CHAT_TEXT_CHARS = 8_000 const val MAX_CHAT_IMAGE_CHARS = 400_000 const val CLOCK_TOLERANCE_MS = 2_000L + const val MAX_CHAT_ENTRIES = 200 const val HANDSHAKE_TIMEOUT_MS = 20_000L const val OPPONENT_FLAG_GRACE_MS = 4_000L const val LEAVE_FLUSH_MS = 700L diff --git a/app/src/test/java/cc/skysparkle/matewave/PeerLimitsTest.kt b/app/src/test/java/cc/skysparkle/matewave/PeerLimitsTest.kt new file mode 100644 index 0000000..2d370b6 --- /dev/null +++ b/app/src/test/java/cc/skysparkle/matewave/PeerLimitsTest.kt @@ -0,0 +1,55 @@ +package cc.skysparkle.matewave + +import cc.skysparkle.matewave.network.GameMessage +import cc.skysparkle.matewave.network.PeerLimits +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class PeerLimitsTest { + private fun profile( + userId: String = "6f1c2a9e-0b3d-4c5e-8f70-1a2b3c4d5e6f", + name: String = "Vladimir", + elo: Int = 1350, + initialSeconds: Int = 300, + incrementSeconds: Int = 3 + ) = GameMessage.ProfileMsg( + userId = userId, name = name, avatarBase64 = null, backgroundBase64 = null, elo = elo, + initialSeconds = initialSeconds, incrementSeconds = incrementSeconds + ) + + @Test fun ordinaryProfileIsAccepted() = assertTrue(PeerLimits.isPlausibleProfile(profile())) + + @Test fun joiningPlayerWithoutTimeControlIsAccepted() = + assertTrue(PeerLimits.isPlausibleProfile(profile(initialSeconds = 0, incrementSeconds = 0))) + + @Test fun unlimitedGameIsAccepted() = + assertTrue(PeerLimits.isPlausibleProfile(profile(initialSeconds = Int.MAX_VALUE, incrementSeconds = 0))) + + @Test + fun oversizedOrEmptyFieldsAreRefused() { + assertFalse(PeerLimits.isPlausibleProfile(profile(name = "x".repeat(PeerLimits.MAX_NAME_CHARS + 1)))) + assertFalse(PeerLimits.isPlausibleProfile(profile(name = " "))) + assertFalse(PeerLimits.isPlausibleProfile(profile(name = "a\u0000b"))) + assertFalse(PeerLimits.isPlausibleProfile(profile(userId = "u".repeat(PeerLimits.MAX_USER_ID_CHARS + 1)))) + assertFalse(PeerLimits.isPlausibleProfile(profile(userId = ""))) + } + + @Test + fun ratingAndTimeControlMustBeInRange() { + assertFalse(PeerLimits.isPlausibleProfile(profile(elo = 99))) + assertFalse(PeerLimits.isPlausibleProfile(profile(elo = 3001))) + assertFalse(PeerLimits.isPlausibleProfile(profile(initialSeconds = -1))) + assertFalse(PeerLimits.isPlausibleProfile(profile(initialSeconds = PeerLimits.MAX_INITIAL_SECONDS + 1))) + assertFalse(PeerLimits.isPlausibleProfile(profile(incrementSeconds = PeerLimits.MAX_INCREMENT_SECONDS + 1))) + } + + @Test + fun opponentClockMayNotGrowBeyondIncrementAndSlack() { + assertEquals(47_000L, PeerLimits.maxOpponentClockAfterMove(42_000, 3_000, 2_000)) + // A flagged opponent (0 ms locally) may still have had a little time on their side. + assertEquals(5_000L, PeerLimits.maxOpponentClockAfterMove(0, 3_000, 2_000)) + assertEquals(2_000L, PeerLimits.maxOpponentClockAfterMove(-50, 0, 2_000)) + } +}