mirror of
https://github.com/kalarina-bit/Matewave.git
synced 2026-11-22 08:06:09 +00:00
Validate what the opponent sends and keep friend images in files
- Images from another device are size-checked before they are decoded, shown or stored: more than 4096 px on a side is refused, decoding is capped and OutOfMemoryError is caught. A crafted avatar or background could otherwise crash the app every time the friend card was drawn. - Profiles with an out-of-range name, user id, rating or time control are refused and the connection is closed; nothing is stored for them. Names and ratings from presence are bounded in the friends list too. - The opponent's clock claim may not exceed what our clock gives them plus increment and slack, so a modified client cannot keep its time. The increment was also added twice on the receiving side; fixed. - Joining a player from the nearby list checks that the profile belongs to the announced player and flags the opponent as unverified otherwise. - Friend avatars and backgrounds move from one large settings value to one file per image; existing entries are migrated on first read. - The in-game chat keeps the last 200 messages.
This commit is contained in:
@@ -333,9 +333,12 @@ private fun AppNavHost() {
|
|||||||
viewModel.startVsPlayerNetwork(transport, PieceColor.WHITE, timeControl, isHost = true)
|
viewModel.startVsPlayerNetwork(transport, PieceColor.WHITE, timeControl, isHost = true)
|
||||||
navController.navigate("game")
|
navController.navigate("game")
|
||||||
},
|
},
|
||||||
onJoin = { type, timeControl, targetId ->
|
onJoin = { type, timeControl, targetId, expectedUserId ->
|
||||||
val transport = if (type == TransportType.BLUETOOTH) bleTransport else lanTransport
|
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")
|
navController.navigate("game")
|
||||||
},
|
},
|
||||||
onBack = { navController.popBackStack() }
|
onBack = { navController.popBackStack() }
|
||||||
|
|||||||
@@ -98,6 +98,12 @@ class GameClock(private val timeControl: TimeControl, private val scope: Corouti
|
|||||||
publish()
|
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) {
|
fun restore(whiteMillis: Long, blackMillis: Long) {
|
||||||
if (unlimited) return
|
if (unlimited) return
|
||||||
account()
|
account()
|
||||||
|
|||||||
@@ -2,8 +2,12 @@ package cc.skysparkle.matewave.data
|
|||||||
|
|
||||||
import cc.skysparkle.matewave.ai.AiDifficulty
|
import cc.skysparkle.matewave.ai.AiDifficulty
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import cc.skysparkle.matewave.network.PeerLimits
|
||||||
|
import cc.skysparkle.matewave.security.toHex
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.security.MessageDigest
|
||||||
import kotlin.math.pow
|
import kotlin.math.pow
|
||||||
import kotlin.math.roundToInt
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
@@ -111,6 +115,7 @@ object FriendsStore {
|
|||||||
private const val PREFS = "chess_friends_prefs"
|
private const val PREFS = "chess_friends_prefs"
|
||||||
private const val KEY_LIST = "friends_json"
|
private const val KEY_LIST = "friends_json"
|
||||||
private const val MAX_FRIENDS = 30
|
private const val MAX_FRIENDS = 30
|
||||||
|
private const val IMAGE_DIR = "friend_images"
|
||||||
|
|
||||||
private var appContext: Context? = null
|
private var appContext: Context? = null
|
||||||
|
|
||||||
@@ -125,6 +130,36 @@ object FriendsStore {
|
|||||||
|
|
||||||
private fun prefs() = appContext?.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
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<FriendEntry> = synchronized(lock) { readAll() }
|
fun list(): List<FriendEntry> = synchronized(lock) { readAll() }
|
||||||
|
|
||||||
private fun readAll(): List<FriendEntry> {
|
private fun readAll(): List<FriendEntry> {
|
||||||
@@ -136,15 +171,21 @@ object FriendsStore {
|
|||||||
return emptyList()
|
return emptyList()
|
||||||
}
|
}
|
||||||
val result = ArrayList<FriendEntry>()
|
val result = ArrayList<FriendEntry>()
|
||||||
|
var hasInlineImages = false
|
||||||
for (i in 0 until arr.length()) {
|
for (i in 0 until arr.length()) {
|
||||||
try {
|
try {
|
||||||
val o = arr.getJSONObject(i)
|
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(
|
result.add(
|
||||||
FriendEntry(
|
FriendEntry(
|
||||||
userId = o.optString("uid", "").ifBlank { o.getString("name") },
|
userId = userId,
|
||||||
name = o.getString("name"),
|
name = o.getString("name"),
|
||||||
avatarBase64 = if (o.has("avatar")) o.getString("avatar") else null,
|
avatarBase64 = inlineAvatar ?: if (o.optBoolean("a")) readImage(userId, "a") else null,
|
||||||
backgroundBase64 = if (o.has("background")) o.getString("background") else null,
|
backgroundBase64 = inlineBackground ?: if (o.optBoolean("b")) readImage(userId, "b") else null,
|
||||||
elo = o.optInt("elo", 1200),
|
elo = o.optInt("elo", 1200),
|
||||||
lastPlayedMs = o.optLong("t", 0),
|
lastPlayedMs = o.optLong("t", 0),
|
||||||
favorite = o.optBoolean("fav", false),
|
favorite = o.optBoolean("fav", false),
|
||||||
@@ -156,24 +197,35 @@ object FriendsStore {
|
|||||||
}
|
}
|
||||||
val sorted = result.sortedByDescending { it.lastPlayedMs }
|
val sorted = result.sortedByDescending { it.lastPlayedMs }
|
||||||
cached = sorted
|
cached = sorted
|
||||||
|
if (hasInlineImages) writeAll(sorted, previous = emptyList())
|
||||||
return sorted
|
return sorted
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun writeAll(entries: List<FriendEntry>) {
|
private fun writeAll(entries: List<FriendEntry>, previous: List<FriendEntry> = readAll()) {
|
||||||
val p = prefs() ?: return
|
val p = prefs() ?: return
|
||||||
|
val before = previous.associateBy { it.userId }
|
||||||
val arr = JSONArray()
|
val arr = JSONArray()
|
||||||
entries.forEach { f ->
|
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()
|
val o = JSONObject()
|
||||||
o.put("uid", f.userId)
|
o.put("uid", f.userId)
|
||||||
o.put("name", f.name)
|
o.put("name", f.name)
|
||||||
if (f.avatarBase64 != null) o.put("avatar", f.avatarBase64)
|
if (f.avatarBase64 != null) o.put("a", true)
|
||||||
if (f.backgroundBase64 != null) o.put("background", f.backgroundBase64)
|
if (f.backgroundBase64 != null) o.put("b", true)
|
||||||
o.put("elo", f.elo)
|
o.put("elo", f.elo)
|
||||||
o.put("t", f.lastPlayedMs)
|
o.put("t", f.lastPlayedMs)
|
||||||
if (f.favorite) o.put("fav", true)
|
if (f.favorite) o.put("fav", true)
|
||||||
if (f.lastSeenMs > 0) o.put("s", f.lastSeenMs)
|
if (f.lastSeenMs > 0) o.put("s", f.lastSeenMs)
|
||||||
arr.put(o)
|
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()
|
p.edit().putString(KEY_LIST, arr.toString()).apply()
|
||||||
cached = entries.sortedByDescending { it.lastPlayedMs }
|
cached = entries.sortedByDescending { it.lastPlayedMs }
|
||||||
}
|
}
|
||||||
@@ -182,6 +234,11 @@ object FriendsStore {
|
|||||||
synchronized(lock) { readAll() }
|
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(
|
fun updateProfile(
|
||||||
userId: String,
|
userId: String,
|
||||||
name: String,
|
name: String,
|
||||||
@@ -192,8 +249,8 @@ object FriendsStore {
|
|||||||
synchronized(lock) {
|
synchronized(lock) {
|
||||||
val existing = readAll().firstOrNull { it.userId == userId } ?: return
|
val existing = readAll().firstOrNull { it.userId == userId } ?: return
|
||||||
val updated = existing.copy(
|
val updated = existing.copy(
|
||||||
name = name.ifBlank { existing.name },
|
name = cleanName(name).ifBlank { existing.name },
|
||||||
elo = if (elo > 0) elo else existing.elo,
|
elo = if (elo > 0) cleanElo(elo) else existing.elo,
|
||||||
avatarBase64 = avatarBase64 ?: existing.avatarBase64,
|
avatarBase64 = avatarBase64 ?: existing.avatarBase64,
|
||||||
backgroundBase64 = backgroundBase64 ?: existing.backgroundBase64
|
backgroundBase64 = backgroundBase64 ?: existing.backgroundBase64
|
||||||
)
|
)
|
||||||
@@ -217,12 +274,13 @@ object FriendsStore {
|
|||||||
backgroundBase64: String? = null
|
backgroundBase64: String? = null
|
||||||
): FriendEntry = synchronized(lock) {
|
): FriendEntry = synchronized(lock) {
|
||||||
val existing = readAll().firstOrNull { it.userId == userId }
|
val existing = readAll().firstOrNull { it.userId == userId }
|
||||||
|
val clean = cleanName(name)
|
||||||
val merged = FriendEntry(
|
val merged = FriendEntry(
|
||||||
userId = userId,
|
userId = userId,
|
||||||
name = name.ifBlank { existing?.name ?: name },
|
name = clean.ifBlank { existing?.name ?: clean },
|
||||||
avatarBase64 = avatarBase64 ?: existing?.avatarBase64,
|
avatarBase64 = avatarBase64 ?: existing?.avatarBase64,
|
||||||
backgroundBase64 = backgroundBase64 ?: existing?.backgroundBase64,
|
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(),
|
lastPlayedMs = System.currentTimeMillis(),
|
||||||
favorite = existing?.favorite ?: false,
|
favorite = existing?.favorite ?: false,
|
||||||
lastSeenMs = existing?.lastSeenMs ?: 0
|
lastSeenMs = existing?.lastSeenMs ?: 0
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -86,21 +86,46 @@ private object DecodedImageCache {
|
|||||||
fun put(key: String, bitmap: Bitmap) { cache.put(key, bitmap) }
|
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<Int, Int>? {
|
||||||
|
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? {
|
fun decodeChatImage(base64: String, maxDimension: Int = 0): Bitmap? {
|
||||||
return try {
|
return try {
|
||||||
val bytes = Base64.decode(base64, Base64.NO_WRAP)
|
val bytes = Base64.decode(base64, Base64.NO_WRAP)
|
||||||
if (maxDimension <= 0) {
|
// The size is always checked first: the image may come from another device.
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
|
val (width, height) = imageBounds(bytes) ?: return null
|
||||||
} else {
|
if (width > MAX_INCOMING_IMAGE_PX || height > MAX_INCOMING_IMAGE_PX) return null
|
||||||
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
|
val target = if (maxDimension > 0) maxDimension else DEFAULT_DECODE_PX
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
|
var sample = 1
|
||||||
var sample = 1
|
while (maxOf(width, height) / (sample * 2) >= target) sample *= 2
|
||||||
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= maxDimension) sample *= 2
|
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
||||||
val options = BitmapFactory.Options().apply { inSampleSize = sample }
|
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
||||||
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
null
|
null
|
||||||
|
} catch (e: OutOfMemoryError) {
|
||||||
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -77,14 +77,16 @@ private data class NearbyEntry(
|
|||||||
val elo: Int?,
|
val elo: Int?,
|
||||||
val type: TransportType,
|
val type: TransportType,
|
||||||
val address: String,
|
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
|
@Composable
|
||||||
fun ConnectionScreen(
|
fun ConnectionScreen(
|
||||||
presence: LocalPresence,
|
presence: LocalPresence,
|
||||||
onStartHost: (TimeControl) -> Unit,
|
onStartHost: (TimeControl) -> Unit,
|
||||||
onJoin: (TransportType, TimeControl, targetId: String) -> Unit,
|
onJoin: (TransportType, TimeControl, targetId: String, expectedUserId: String?) -> Unit,
|
||||||
onBack: () -> Unit
|
onBack: () -> Unit
|
||||||
) {
|
) {
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
@@ -146,7 +148,8 @@ fun ConnectionScreen(
|
|||||||
elo = peer.elo,
|
elo = peer.elo,
|
||||||
type = TransportType.LAN,
|
type = TransportType.LAN,
|
||||||
address = peer.address,
|
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() }
|
val lanFingerprints = peers.values.map { it.fingerprint }.filter { it.isNotEmpty() }
|
||||||
@@ -263,7 +266,7 @@ fun ConnectionScreen(
|
|||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.clip(RoundedCornerShape(50))
|
.clip(RoundedCornerShape(50))
|
||||||
.background(Lime)
|
.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)
|
.padding(horizontal = 14.dp, vertical = 6.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ import cc.skysparkle.matewave.network.ConnectionTransport
|
|||||||
import cc.skysparkle.matewave.network.GameMessage
|
import cc.skysparkle.matewave.network.GameMessage
|
||||||
import cc.skysparkle.matewave.network.NetworkLog
|
import cc.skysparkle.matewave.network.NetworkLog
|
||||||
import cc.skysparkle.matewave.network.NetworkMetrics
|
import cc.skysparkle.matewave.network.NetworkMetrics
|
||||||
|
import cc.skysparkle.matewave.network.PeerLimits
|
||||||
import cc.skysparkle.matewave.network.TransportType
|
import cc.skysparkle.matewave.network.TransportType
|
||||||
import cc.skysparkle.matewave.puzzles.Puzzle
|
import cc.skysparkle.matewave.puzzles.Puzzle
|
||||||
import cc.skysparkle.matewave.security.DeviceKeys
|
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.SpectatorResults
|
||||||
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
import cc.skysparkle.matewave.spectate.SpectatorSnapshot
|
||||||
import cc.skysparkle.matewave.stats.Stats
|
import cc.skysparkle.matewave.stats.Stats
|
||||||
|
import cc.skysparkle.matewave.ui.components.isAcceptableIncomingImage
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.Job
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.delay
|
||||||
@@ -185,8 +187,10 @@ class GameViewModel : ViewModel() {
|
|||||||
private var sessionGeneration = 0
|
private var sessionGeneration = 0
|
||||||
private var networkGameId: String = ""
|
private var networkGameId: String = ""
|
||||||
private var pendingOpponentImages: Pair<String?, String?>? = null
|
private var pendingOpponentImages: Pair<String?, String?>? = 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 currentPly: Int = 0
|
||||||
private var lastOpponentRemaining: Long = Long.MAX_VALUE
|
|
||||||
|
|
||||||
// Spectating: the host serves spectators, both players announce the game's tag.
|
// Spectating: the host serves spectators, both players announce the game's tag.
|
||||||
private var spectators: SpectatorBroadcaster? = null
|
private var spectators: SpectatorBroadcaster? = null
|
||||||
@@ -711,7 +715,8 @@ class GameViewModel : ViewModel() {
|
|||||||
myColor: PieceColor,
|
myColor: PieceColor,
|
||||||
timeControl: TimeControl,
|
timeControl: TimeControl,
|
||||||
isHost: Boolean,
|
isHost: Boolean,
|
||||||
targetId: String? = null
|
targetId: String? = null,
|
||||||
|
expectedUserId: String? = null
|
||||||
) {
|
) {
|
||||||
pendingLeave?.let { (job, oldTransport) ->
|
pendingLeave?.let { (job, oldTransport) ->
|
||||||
job.cancel()
|
job.cancel()
|
||||||
@@ -730,6 +735,7 @@ class GameViewModel : ViewModel() {
|
|||||||
this.transport = transport
|
this.transport = transport
|
||||||
lastNetworkTimeControl = timeControl
|
lastNetworkTimeControl = timeControl
|
||||||
isNetworkHost = isHost
|
isNetworkHost = isHost
|
||||||
|
expectedOpponentUserId = expectedUserId?.takeIf { it.isNotBlank() }
|
||||||
|
|
||||||
ephemeralKeys = DeviceKeys.generateEphemeral()
|
ephemeralKeys = DeviceKeys.generateEphemeral()
|
||||||
|
|
||||||
@@ -739,7 +745,6 @@ class GameViewModel : ViewModel() {
|
|||||||
opponentFlagJob = null
|
opponentFlagJob = null
|
||||||
networkGameId = if (isHost) java.util.UUID.randomUUID().toString() else ""
|
networkGameId = if (isHost) java.util.UUID.randomUUID().toString() else ""
|
||||||
currentPly = 0
|
currentPly = 0
|
||||||
lastOpponentRemaining = Long.MAX_VALUE
|
|
||||||
|
|
||||||
_clockState.value = null
|
_clockState.value = null
|
||||||
_uiState.value = GameUiState(
|
_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 =
|
private fun belongsToCurrentGame(gameId: String): Boolean =
|
||||||
gameId.isEmpty() || networkGameId.isEmpty() || gameId == networkGameId
|
gameId.isEmpty() || networkGameId.isEmpty() || gameId == networkGameId
|
||||||
|
|
||||||
@@ -901,9 +913,14 @@ class GameViewModel : ViewModel() {
|
|||||||
NetworkLog.log("GAME", "Oversized chat message rejected")
|
NetworkLog.log("GAME", "Oversized chat message rejected")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (msg.imageBase64 != null && !isAcceptableIncomingImage(msg.imageBase64)) {
|
||||||
|
NetworkLog.log("GAME", "Unreadable or oversized chat image rejected")
|
||||||
|
return
|
||||||
|
}
|
||||||
val state = _uiState.value
|
val state = _uiState.value
|
||||||
_uiState.value = state.copy(
|
_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
|
unreadChatCount = state.unreadChatCount + 1
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -976,8 +993,8 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
is GameMessage.ProfileImagesMsg -> {
|
is GameMessage.ProfileImagesMsg -> {
|
||||||
if (!belongsToCurrentGame(msg.gameId)) return
|
if (!belongsToCurrentGame(msg.gameId)) return
|
||||||
val avatar = msg.avatarBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
val avatar = msg.avatarBase64?.let(::acceptedIncomingImage)
|
||||||
val background = msg.backgroundBase64?.takeIf { it.length <= MAX_CHAT_IMAGE_CHARS }
|
val background = msg.backgroundBase64?.let(::acceptedIncomingImage)
|
||||||
if (avatar == null && background == null) return
|
if (avatar == null && background == null) return
|
||||||
val current = _uiState.value.opponentProfile
|
val current = _uiState.value.opponentProfile
|
||||||
if (current == null) {
|
if (current == null) {
|
||||||
@@ -1051,17 +1068,17 @@ class GameViewModel : ViewModel() {
|
|||||||
|
|
||||||
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
val limit = lastNetworkTimeControl?.let { it.initialSeconds * 1000L + 60_000L }
|
||||||
val increment = lastNetworkTimeControl?.let { it.incrementSeconds * 1000L } ?: 0L
|
val increment = lastNetworkTimeControl?.let { it.incrementSeconds * 1000L } ?: 0L
|
||||||
val allowedMax = if (lastOpponentRemaining == Long.MAX_VALUE) {
|
// Our own clock has been running the opponent's time while they thought, so their claim
|
||||||
limit ?: Long.MAX_VALUE
|
// may not exceed it by more than the increment and network slack.
|
||||||
} else {
|
val allowedMax = clock?.remainingMillis(opponentColor)
|
||||||
lastOpponentRemaining + increment + CLOCK_TOLERANCE_MS
|
?.let { PeerLimits.maxOpponentClockAfterMove(it, increment, CLOCK_TOLERANCE_MS) }
|
||||||
}
|
?: limit ?: Long.MAX_VALUE
|
||||||
if (msg.remainingMillisSelf >= 0 &&
|
if (msg.remainingMillisSelf >= 0 &&
|
||||||
(limit == null || msg.remainingMillisSelf <= limit) &&
|
(limit == null || msg.remainingMillisSelf <= limit) &&
|
||||||
msg.remainingMillisSelf <= allowedMax
|
msg.remainingMillisSelf <= allowedMax
|
||||||
) {
|
) {
|
||||||
lastOpponentRemaining = msg.remainingMillisSelf
|
// The reported time already includes the increment; makeMove below adds it again.
|
||||||
clock?.applyRemoteTime(opponentColor, msg.remainingMillisSelf)
|
clock?.applyRemoteTime(opponentColor, (msg.remainingMillisSelf - increment).coerceAtLeast(0))
|
||||||
} else if (msg.remainingMillisSelf > 0) {
|
} else if (msg.remainingMillisSelf > 0) {
|
||||||
NetworkLog.log("GAME", "Invalid clock value from opponent rejected: ${msg.remainingMillisSelf}")
|
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")
|
NetworkLog.log("GAME", "Repeated profile in current session ignored")
|
||||||
return
|
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
|
val peers = knownPeers
|
||||||
if (peers == null) {
|
if (peers == null) {
|
||||||
NetworkLog.log("GAME", "Key store not ready, profile rejected")
|
NetworkLog.log("GAME", "Key store not ready, profile rejected")
|
||||||
@@ -1125,7 +1148,11 @@ class GameViewModel : ViewModel() {
|
|||||||
}
|
}
|
||||||
markReadyIfPossible()
|
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
|
val pending = pendingOpponentImages
|
||||||
pendingOpponentImages = null
|
pendingOpponentImages = null
|
||||||
@@ -1133,8 +1160,8 @@ class GameViewModel : ViewModel() {
|
|||||||
userId = msg.userId,
|
userId = msg.userId,
|
||||||
name = msg.name,
|
name = msg.name,
|
||||||
elo = msg.elo,
|
elo = msg.elo,
|
||||||
avatarBase64 = msg.avatarBase64 ?: pending?.first,
|
avatarBase64 = msg.avatarBase64?.let(::acceptedIncomingImage) ?: pending?.first,
|
||||||
backgroundBase64 = msg.backgroundBase64 ?: pending?.second
|
backgroundBase64 = msg.backgroundBase64?.let(::acceptedIncomingImage) ?: pending?.second
|
||||||
)
|
)
|
||||||
_uiState.value = _uiState.value.copy(
|
_uiState.value = _uiState.value.copy(
|
||||||
opponentProfile = Profile(
|
opponentProfile = Profile(
|
||||||
@@ -1240,7 +1267,6 @@ class GameViewModel : ViewModel() {
|
|||||||
opponentFlagJob?.cancel()
|
opponentFlagJob?.cancel()
|
||||||
opponentFlagJob = null
|
opponentFlagJob = null
|
||||||
currentPly = 0
|
currentPly = 0
|
||||||
lastOpponentRemaining = Long.MAX_VALUE
|
|
||||||
val start = Board.startPosition()
|
val start = Board.startPosition()
|
||||||
resetHistory(start)
|
resetHistory(start)
|
||||||
|
|
||||||
@@ -1349,7 +1375,8 @@ class GameViewModel : ViewModel() {
|
|||||||
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
val trimmed = text.trim().take(MAX_CHAT_TEXT_CHARS)
|
||||||
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
if (!sendGameMessage(GameMessage.ChatMsg(text = trimmed, gameId = networkGameId))) return
|
||||||
_uiState.value = _uiState.value.copy(
|
_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
|
if (!sendGameMessage(GameMessage.ChatMsg(imageBase64 = base64, gameId = networkGameId))) return
|
||||||
_uiState.value = _uiState.value.copy(
|
_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 {
|
viewModelScope.launch {
|
||||||
var serving = false
|
var serving = false
|
||||||
try {
|
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")
|
if (port == null) NetworkLog.log("SPECTATE", "Could not open the spectator port")
|
||||||
// The game may have ended while the port was opening.
|
// The game may have ended while the port was opening.
|
||||||
if (port == null || generation != sessionGeneration || !spectatingDecided || spectateTag.isEmpty()) return@launch
|
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_TEXT_CHARS = 8_000
|
||||||
const val MAX_CHAT_IMAGE_CHARS = 400_000
|
const val MAX_CHAT_IMAGE_CHARS = 400_000
|
||||||
const val CLOCK_TOLERANCE_MS = 2_000L
|
const val CLOCK_TOLERANCE_MS = 2_000L
|
||||||
|
const val MAX_CHAT_ENTRIES = 200
|
||||||
const val HANDSHAKE_TIMEOUT_MS = 20_000L
|
const val HANDSHAKE_TIMEOUT_MS = 20_000L
|
||||||
const val OPPONENT_FLAG_GRACE_MS = 4_000L
|
const val OPPONENT_FLAG_GRACE_MS = 4_000L
|
||||||
const val LEAVE_FLUSH_MS = 700L
|
const val LEAVE_FLUSH_MS = 700L
|
||||||
|
|||||||
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user