package eu.friedcutlet.yokan.services.extensions.recipe /** Shared size ceilings for signed catalog envelopes. */ internal object RecipeCatalogLimits { const val maxEnvelopeBytes = 96 * 1024 const val maxPayloadBytes = 64 * 1024 const val maxKeyIdBytes = 64 } /** Trust-boundary syntax shared by recipe bundles, catalogs, enrollment codes and the native transports. */ internal object RecipeSyntax { /** Lowercase ASCII DNS name with at least one letter, so IP literals are never accepted as hosts. */ fun isHost(host: String): Boolean = host.isNotEmpty() && host.length <= 253 && host.any { it in 'a'..'z' } && host.all { it in 'a'..'z' || it in '0'..'9' || it == '.' || it == '-' } && host.split('.').all { it.isNotEmpty() && it.length <= 63 && it.first() != '-' && it.last() != '-' } /** `https://host[:port]` with no path, userinfo or default port. */ fun isNormalizedHttpsOrigin(value: String): Boolean { if (!value.startsWith("https://")) return false val authority = value.removePrefix("https://") if (authority.isEmpty() || authority.any { it == '/' || it == '?' || it == '#' || it == '@' || it == '\\' }) return false val pieces = authority.split(':') if (pieces.size !in 1..2 || !isHost(pieces.first())) return false if (pieces.size == 2) { val port = pieces[1].toIntOrNull() ?: return false if (pieces[1] != port.toString() || port !in 1..65535 || port == 443) return false } return true } fun isIdentifier(value: String, maxLength: Int = 80, allowPlus: Boolean = false): Boolean = value.isNotEmpty() && value.length <= maxLength && value.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '-' || it == '_' || it == '.' || (allowPlus && it == '+') } /** Canonical URL path: no dot segments, uppercase percent-escapes only for characters that need them. */ fun isCanonicalPath(path: String): Boolean { if (path.split('/').any { it == "." || it == ".." }) return false var index = 0 while (index < path.length) { val character = path[index] if (character == '%') { if (index + 2 >= path.length || !isUpperHex(path[index + 1]) || !isUpperHex(path[index + 2])) return false if (isUnreserved(((hexValue(path[index + 1]) shl 4) or hexValue(path[index + 2])).toChar())) return false index += 3 } else if (isUnreserved(character) || character in "!$&'()*+,;=:@/") { index++ } else return false } return true } fun isUnreserved(char: Char): Boolean = char in 'a'..'z' || char in 'A'..'Z' || char in '0'..'9' || char == '-' || char == '.' || char == '_' || char == '~' fun isUpperHex(char: Char): Boolean = char in '0'..'9' || char in 'A'..'F' fun hexValue(char: Char): Int = if (char in '0'..'9') char - '0' else char - 'A' + 10 }