CatalogEnrollmentCode.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CatalogEnrollmentCode.kt
1package eu.friedcutlet.yokan.services.extensions.recipe23import eu.friedcutlet.yokan.util.sha25645private const val loopbackCatalogPrefix = "http://127.0.0.1:"67/**8 * `http://127.0.0.1:<port>` when [url] targets a local test catalog server, else null. Such URLs pass syntax checks9 * everywhere, but only the catalog downloader decides whether to fetch them (developer mode).10 */11internal fun loopbackCatalogOrigin(url: String): String? {12 if (!url.startsWith(loopbackCatalogPrefix)) return null13 val authorityEnd = url.indexOf('/', loopbackCatalogPrefix.length).takeIf { it >= 0 } ?: return null14 val port = url.substring(loopbackCatalogPrefix.length, authorityEnd)15 if (port.isEmpty() || port.length > 5 || port.first() == '0' || port.any { it !in '0'..'9' } || port.toInt() > 65_535) return null16 return url.substring(0, authorityEnd)17}1819/** A portable trust proposal; parsing it never changes a catalog's trust state. */20class CatalogEnrollmentCode private constructor(21 val catalogId: String,22 val catalogEnvelopeUrl: String,23 val keyId: String,24 private val rawEd25519PublicKey: ByteArray,25) {26 /** Stable lowercase SHA-256 fingerprint for explicit user confirmation. */27 val publicKeyFingerprint: String = sha256(rawEd25519PublicKey).toHexString()2829 fun render(): String = listOf(30 prefix, version, catalogId, encodeBase64Url(catalogEnvelopeUrl.encodeToByteArray()), keyId, encodeBase64Url(rawEd25519PublicKey),31 ).joinToString(":")3233 internal fun trustPolicy(): CatalogTrustPolicy = CatalogTrustPolicy(34 catalogId,35 listOf(TrustedCatalogKey(catalogId, keyId, rawEd25519PublicKey.copyOf(), TrustedCatalogKeyState.Active)),36 )3738 override fun equals(other: Any?): Boolean = other is CatalogEnrollmentCode &&39 catalogId == other.catalogId && catalogEnvelopeUrl == other.catalogEnvelopeUrl && keyId == other.keyId && rawEd25519PublicKey.contentEquals(other.rawEd25519PublicKey)4041 override fun hashCode(): Int = (((catalogId.hashCode() * 31 + catalogEnvelopeUrl.hashCode()) * 31 + keyId.hashCode()) * 31 + rawEd25519PublicKey.contentHashCode())42 override fun toString(): String = render()4344 companion object {45 private const val prefix = "yokan-catalog"46 private const val version = "v1"47 private const val maxCodeCharacters = 4_09648 private const val maxUrlCharacters = 2_04849 private const val publicKeyBytes = 325051 /** Returns null unless [value] is a bounded, canonical v1 enrollment code. */52 fun parse(value: String): CatalogEnrollmentCode? {53 if (value.length > maxCodeCharacters || value.any { it.code !in 0x21..0x7e }) return null54 val parts = value.split(':')55 if (parts.size != 6 || parts[0] != prefix || parts[1] != version || !RecipeSyntax.isIdentifier(parts[2]) || !RecipeSyntax.isIdentifier(parts[4], RecipeCatalogLimits.maxKeyIdBytes)) return null56 val urlBytes = decodeCanonicalBase64Url(parts[3]) ?: return null57 val url = try { urlBytes.decodeToString(throwOnInvalidSequence = true) } catch (_: CharacterCodingException) { return null }58 if (!url.encodeToByteArray().contentEquals(urlBytes) || !safeCanonicalHttpsUrl(url)) return null59 val publicKey = decodeCanonicalBase64Url(parts[5]) ?: return null60 if (publicKey.size != publicKeyBytes) return null61 return CatalogEnrollmentCode(parts[2], url, parts[4], publicKey)62 }6364 private fun safeCanonicalHttpsUrl(value: String): Boolean {65 if (value.length !in 9..maxUrlCharacters || value.any { it.code !in 0x21..0x7e || it == '\\' || it == '?' || it == '#' }) return false66 loopbackCatalogOrigin(value)?.let { return RecipeSyntax.isCanonicalPath(value.substring(it.length)) }67 if (!value.startsWith("https://")) return false68 val authorityEnd = value.indexOf('/', startIndex = 8).takeIf { it >= 0 } ?: return false69 val host = value.substring(8, authorityEnd)70 if (host.isEmpty() || '@' in host || ':' in host || !RecipeSyntax.isHost(host)) return false71 return RecipeSyntax.isCanonicalPath(value.substring(authorityEnd))72 }7374 private fun decodeCanonicalBase64Url(value: String): ByteArray? {75 if (value.isEmpty() || value.length % 4 == 1 || value.any { base64UrlValue(it) < 0 }) return null76 val output = ArrayList<Byte>()77 var accumulator = 078 var bits = 079 for (character in value) {80 accumulator = (accumulator shl 6) or base64UrlValue(character)81 bits += 682 while (bits >= 8) {83 bits -= 884 output += ((accumulator ushr bits) and 0xff).toByte()85 }86 }87 val decoded = output.toByteArray()88 return decoded.takeIf { encodeBase64Url(it) == value }89 }9091 private fun encodeBase64Url(bytes: ByteArray): String = buildString((bytes.size * 4 + 2) / 3) {92 var index = 093 while (index < bytes.size) {94 val first = bytes[index++].toInt() and 0xff95 val second = if (index < bytes.size) bytes[index++].toInt() and 0xff else -196 val third = if (index < bytes.size) bytes[index++].toInt() and 0xff else -197 append(base64UrlAlphabet[first ushr 2])98 append(base64UrlAlphabet[((first and 3) shl 4) or if (second >= 0) second ushr 4 else 0])99 if (second >= 0) append(base64UrlAlphabet[((second and 15) shl 2) or if (third >= 0) third ushr 6 else 0])100 if (third >= 0) append(base64UrlAlphabet[third and 63])101 }102 }103104 private fun base64UrlValue(character: Char): Int = when (character) {105 in 'A'..'Z' -> character - 'A'106 in 'a'..'z' -> character - 'a' + 26107 in '0'..'9' -> character - '0' + 52108 '-' -> 62109 '_' -> 63110 else -> -1111 }112113 private const val base64UrlAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"114 }115}116