RecipeSyntax.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeSyntax.kt
1package eu.friedcutlet.yokan.services.extensions.recipe23/** Shared size ceilings for signed catalog envelopes. */4internal object RecipeCatalogLimits {5 const val maxEnvelopeBytes = 96 * 10246 const val maxPayloadBytes = 64 * 10247 const val maxKeyIdBytes = 648}910/** Trust-boundary syntax shared by recipe bundles, catalogs, enrollment codes and the native transports. */11internal object RecipeSyntax {12 /** Lowercase ASCII DNS name with at least one letter, so IP literals are never accepted as hosts. */13 fun isHost(host: String): Boolean = host.isNotEmpty() && host.length <= 253 && host.any { it in 'a'..'z' } &&14 host.all { it in 'a'..'z' || it in '0'..'9' || it == '.' || it == '-' } &&15 host.split('.').all { it.isNotEmpty() && it.length <= 63 && it.first() != '-' && it.last() != '-' }1617 /** `https://host[:port]` with no path, userinfo or default port. */18 fun isNormalizedHttpsOrigin(value: String): Boolean {19 if (!value.startsWith("https://")) return false20 val authority = value.removePrefix("https://")21 if (authority.isEmpty() || authority.any { it == '/' || it == '?' || it == '#' || it == '@' || it == '\\' }) return false22 val pieces = authority.split(':')23 if (pieces.size !in 1..2 || !isHost(pieces.first())) return false24 if (pieces.size == 2) {25 val port = pieces[1].toIntOrNull() ?: return false26 if (pieces[1] != port.toString() || port !in 1..65535 || port == 443) return false27 }28 return true29 }3031 fun isIdentifier(value: String, maxLength: Int = 80, allowPlus: Boolean = false): Boolean = value.isNotEmpty() && value.length <= maxLength &&32 value.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '-' || it == '_' || it == '.' || (allowPlus && it == '+') }3334 /** Canonical URL path: no dot segments, uppercase percent-escapes only for characters that need them. */35 fun isCanonicalPath(path: String): Boolean {36 if (path.split('/').any { it == "." || it == ".." }) return false37 var index = 038 while (index < path.length) {39 val character = path[index]40 if (character == '%') {41 if (index + 2 >= path.length || !isUpperHex(path[index + 1]) || !isUpperHex(path[index + 2])) return false42 if (isUnreserved(((hexValue(path[index + 1]) shl 4) or hexValue(path[index + 2])).toChar())) return false43 index += 344 } else if (isUnreserved(character) || character in "!$&'()*+,;=:@/") {45 index++46 } else return false47 }48 return true49 }5051 fun isUnreserved(char: Char): Boolean = char in 'a'..'z' || char in 'A'..'Z' || char in '0'..'9' || char == '-' || char == '.' || char == '_' || char == '~'52 fun isUpperHex(char: Char): Boolean = char in '0'..'9' || char in 'A'..'F'53 fun hexValue(char: Char): Int = if (char in '0'..'9') char - '0' else char - 'A' + 1054}55