package com.qft.optical import org.json.JSONObject import java.net.URI data class WifiCredentials( val ssid: String, val passphrase: String, val security: String, ) data class PairingPayload( val version: Int, val session: String, val pcName: String, val transport: String, val port: Int, val endpoints: List, val wifi: WifiCredentials?, val direction: TransferDirection = TransferDirection.UPLOAD_TO_PC, val fileName: String? = null, val fileSize: Long? = null, val sha256: String? = null, /** Internal per-file route used by Android → Android manifests. QR input * never controls this value; parsed pairing codes always use the default. */ val downloadPath: String = "/qft/download", ) enum class TransferDirection { UPLOAD_TO_PC, DOWNLOAD_TO_PHONE, PHONE_TO_PHONE } object PairingProtocol { const val PREFIX_V2 = "QFTPAIR2:" const val PREFIX_SEND_V2 = "QFTSEND2:" const val PREFIX_PHONE_V2 = "QFTPHONE2:" const val PREFIX_V1 = "QFTPAIR1:" fun isPairingText(text: String): Boolean = text.startsWith(PREFIX_V2) || text.startsWith(PREFIX_SEND_V2) || text.startsWith(PREFIX_PHONE_V2) || text.startsWith(PREFIX_V1) fun parse(text: String): PairingPayload? { if (text.length > 4096) return null return when { text.startsWith(PREFIX_V2) -> parseV2(text.substring(PREFIX_V2.length), TransferDirection.UPLOAD_TO_PC) text.startsWith(PREFIX_SEND_V2) -> parseV2(text.substring(PREFIX_SEND_V2.length), TransferDirection.DOWNLOAD_TO_PHONE) text.startsWith(PREFIX_PHONE_V2) -> parseV2(text.substring(PREFIX_PHONE_V2.length), TransferDirection.PHONE_TO_PHONE) text.startsWith(PREFIX_V1) -> parseV1(text.substring(PREFIX_V1.length)) else -> null } } private fun parseV2(encoded: String, expectedDirection: TransferDirection): PairingPayload? { return try { val jsonBytes = decodeUrlBase64(encoded) ?: return null if (jsonBytes.size > 2048) return null val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8)) if (obj.optInt("v", 0) != 2) return null val encodedDirection = obj.optString("d", "u") val direction = when (encodedDirection) { "u" -> TransferDirection.UPLOAD_TO_PC "d" -> TransferDirection.DOWNLOAD_TO_PHONE "m" -> TransferDirection.PHONE_TO_PHONE else -> return null } if (direction != expectedDirection) return null val session = obj.getString("s") if (!validSession(session)) return null val port = obj.getInt("p") if (port !in 1..65535) return null val wifiArray = obj.optJSONArray("w") val wifi = if (wifiArray != null && wifiArray.length() >= 2) { val ssid = wifiArray.optString(0) val passphrase = wifiArray.optString(1) if (!validWifi(ssid, passphrase)) return null val security = wifiArray.optString(2, "WPA2") if (security !in setOf("WPA2", "WPA3")) return null WifiCredentials(ssid, passphrase, security) } else null val endpoints = mutableListOf() obj.optJSONArray("e")?.let { arr -> for (i in 0 until arr.length()) { val value = arr.optString(i).trim().removeSuffix("/") if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value } } // QFT Direct v2 can work with no QR-carried endpoint because UDP discovery // and the actual Wi-Fi gateway are probed after Android obtains an IP. if (wifi == null && endpoints.isEmpty()) return null val fileName = if (direction == TransferDirection.DOWNLOAD_TO_PHONE) { obj.optString("f").trim().takeIf { validFileName(it) } ?: return null } else null val fileSize = if (direction == TransferDirection.DOWNLOAD_TO_PHONE) { obj.optLong("z", -1L).takeIf { it >= 0L } ?: return null } else null val sha = if (direction == TransferDirection.DOWNLOAD_TO_PHONE) { obj.optString("h").lowercase().takeIf { it.matches(Regex("^[0-9a-f]{64}$")) } ?: return null } else null PairingPayload( version = 2, session = session, pcName = obj.optString("n", "Windows-PC").take(80), transport = "http-parallel-v2", port = port, endpoints = endpoints, wifi = wifi, direction = direction, fileName = fileName, fileSize = fileSize, sha256 = sha, ) } catch (_: Exception) { null } } private fun parseV1(encoded: String): PairingPayload? { return try { val jsonBytes = decodeUrlBase64(encoded) ?: return null if (jsonBytes.size > 3072) return null val obj = JSONObject(jsonBytes.toString(Charsets.UTF_8)) if (obj.optInt("v", 0) != 1) return null val session = obj.getString("session") if (!validSession(session)) return null val transport = obj.optString("transport", "") if (transport != "http-stream-v1") return null val port = obj.getInt("port") if (port !in 1..65535) return null val endpoints = mutableListOf() val endpointsJson = obj.getJSONArray("endpoints") for (i in 0 until endpointsJson.length()) { val value = endpointsJson.optString(i).trim().removeSuffix("/") if (isAllowedLocalHttpEndpoint(value, port) && value !in endpoints) endpoints += value } if (endpoints.isEmpty()) return null val wifiObj = obj.optJSONObject("wifi") val wifi = wifiObj?.let { val ssid = it.getString("ssid") val passphrase = it.getString("passphrase") val security = it.optString("security", "WPA2") if (!validWifi(ssid, passphrase) || security != "WPA2") return null WifiCredentials(ssid, passphrase, security) } PairingPayload( version = 1, session = session, pcName = obj.optString("pc_name", "Windows-PC").take(80), transport = transport, port = port, endpoints = endpoints, wifi = wifi, direction = TransferDirection.UPLOAD_TO_PC, ) } catch (_: Exception) { null } } private fun decodeUrlBase64(encoded: String): ByteArray? = Base64Url.decode(encoded) /** Build a compact Android-sender QR. File names and hashes stay in the * authenticated local manifest so a large queue does not make the QR dense. */ fun encodePhoneShare( session: String, senderName: String, port: Int, endpoints: List, wifi: WifiCredentials?, ): String { require(validSession(session)) require(port in 1..65535) val safeEndpoints = endpoints .map { it.trim().removeSuffix("/") } .filter { isAllowedLocalHttpEndpoint(it, port) } .distinct() require(wifi != null || safeEndpoints.isNotEmpty()) val obj = JSONObject().apply { put("v", 2) put("s", session) put("n", senderName.take(80)) put("p", port) put("d", "m") if (safeEndpoints.isNotEmpty()) put("e", org.json.JSONArray(safeEndpoints)) wifi?.let { put("w", org.json.JSONArray(listOf(it.ssid, it.passphrase, it.security))) } } return PREFIX_PHONE_V2 + Base64Url.encode(obj.toString().toByteArray(Charsets.UTF_8)) } private fun validSession(session: String): Boolean = session.matches(Regex("^[A-Za-z0-9_-]{20,64}$")) private fun validWifi(ssid: String, passphrase: String): Boolean { return ssid.isNotBlank() && ssid.toByteArray(Charsets.UTF_8).size <= 32 && passphrase.length in 8..63 } private fun validFileName(value: String): Boolean = value.isNotBlank() && value.length <= 180 && value.none { it.code <= 31 || it.code == 127 || it in "\\/:*?\"<>|" } /** * Pairing QR is treated as untrusted input. QFT only probes literal local * IPv4 addresses on the exact advertised port; public hosts and DNS names * are rejected even though the app permits cleartext HTTP for local QFT. */ fun isAllowedLocalHttpEndpoint(value: String, expectedPort: Int): Boolean { val uri = try { URI(value) } catch (_: Exception) { return false } if (uri.scheme != "http" || uri.userInfo != null || uri.query != null || uri.fragment != null) return false if (uri.port != expectedPort) return false val host = uri.host ?: return false val octets = host.split('.').map { it.toIntOrNull() ?: return false } if (octets.size != 4 || octets.any { it !in 0..255 }) return false val a = octets[0] val b = octets[1] return when { a == 10 -> true a == 127 -> true a == 169 && b == 254 -> true a == 172 && b in 16..31 -> true a == 192 && b == 168 -> true else -> false } } }