package eu.friedcutlet.yokan.services.extensions.recipe import kotlinx.serialization.SerializationException import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json object RecipeBundleLimits { const val maxBundleBytes = 64 * 1024 /** Maximum nested JSON arrays/objects; the root value is not counted. */ const val maxJsonDepth = 16 const val maxStringCharacters = 2_048 const val maxCollectionEntries = 64 const val maxOrigins = 8 const val maxQueryParameters = 16 const val maxJsonPointerTokens = 16 const val maxJsonPointerTokenCharacters = 128 } enum class RecipeBundleErrorCode { ByteLimitExceeded, NestingLimitExceeded, StringLimitExceeded, CollectionLimitExceeded, DuplicateJsonKey, InvalidJson, InvalidBundleShape, UnsupportedFormatVersion, UnknownFieldOrOperation, InvalidValue, OperationLimitExceeded, } /** All details are fixed diagnostics, never parser text or bundle data. */ data class RecipeBundleError( val code: RecipeBundleErrorCode, val path: String = "$", val detail: String = "", ) sealed interface RecipeBundleDecodeResult { data class Accepted(val bundle: DeclarativeExtensionBundle) : RecipeBundleDecodeResult data class Rejected(val error: RecipeBundleError) : RecipeBundleDecodeResult } object StrictRecipeBundleDecoder { private val json = Json { ignoreUnknownKeys = false isLenient = false coerceInputValues = false explicitNulls = false useAlternativeNames = false } fun decode(bytes: ByteArray): RecipeBundleDecodeResult { val preflight = boundedJsonPreflight(bytes, RecipeBundleLimits.maxBundleBytes) if (preflight != null) return RecipeBundleDecodeResult.Rejected(preflight) // Preflight already proved the bytes are valid UTF-8. val source = bytes.decodeToString() return try { RecipeBundleValidator.validate(json.decodeFromString(source)) } catch (error: SerializationException) { rejected(decodingCode(error)) } catch (_: IllegalArgumentException) { rejected(RecipeBundleErrorCode.InvalidBundleShape) } } /** Shared bounded structural validation for authenticated JSON payloads. */ internal fun boundedJsonPreflight(bytes: ByteArray, maxBytes: Int): RecipeBundleError? = boundedPreflight(bytes, maxBytes, RecipeBundleLimits.maxStringCharacters, RecipeBundleLimits.maxCollectionEntries) /** Strict response-only JSON boundary; it intentionally does not inherit signed-bundle collection ceilings. */ internal fun boundedApiResponseJsonPreflight(bytes: ByteArray, maxBytes: Int): RecipeBundleError? = boundedPreflight(bytes, maxBytes, maxBytes, 512) private fun boundedPreflight(bytes: ByteArray, maxBytes: Int, maxStringCharacters: Int, maxCollectionEntries: Int): RecipeBundleError? { if (bytes.size > maxBytes) return reject(RecipeBundleErrorCode.ByteLimitExceeded) val source = try { bytes.decodeToString(throwOnInvalidSequence = true) } catch (_: CharacterCodingException) { return reject(RecipeBundleErrorCode.InvalidJson) } return JsonStructureScanner.scan(source, RecipeBundleLimits.maxJsonDepth, maxStringCharacters, maxCollectionEntries) } private fun decodingCode(error: SerializationException): RecipeBundleErrorCode { val message = error.message.orEmpty().lowercase() return when { "recipeformatversion" in message -> RecipeBundleErrorCode.UnsupportedFormatVersion "unknown key" in message || "subclass" in message || "discriminator" in message -> RecipeBundleErrorCode.UnknownFieldOrOperation else -> RecipeBundleErrorCode.InvalidBundleShape } } } object RecipeBundleValidator { /** Only V2.1 entrypoint bundles run; older step-based versions still parse so they are rejected here explicitly. */ fun validate(bundle: DeclarativeExtensionBundle): RecipeBundleDecodeResult { if (bundle.manifest.formatVersion != RecipeFormatVersion.V21) return rejected(RecipeBundleErrorCode.UnsupportedFormatVersion, "$.manifest.formatVersion") val originById = validateManifest(bundle.manifest) ?: return rejected(RecipeBundleErrorCode.InvalidValue, "$.manifest") return validateV21(bundle, originById) } private fun validateV21(bundle: DeclarativeExtensionBundle, origins: Map): RecipeBundleDecodeResult { if (bundle.recipe.steps.isNotEmpty() || bundle.entrypoints.isEmpty() || bundle.entrypoints.size > 6) return rejected(RecipeBundleErrorCode.InvalidValue, "$.entrypoints") var projected = 0 for ((name, entry) in bundle.entrypoints) { if (name !in setOf("popular", "latest", "search", "detail", "episodes", "media") || !validV21Inputs(name, entry.inputs) || entry.url.origin.originId !in origins || entry.url.path.isEmpty() || entry.url.path.size > 4 || entry.url.path.firstOrNull()?.let { it is RecipeV21UrlValue.Literal && (!it.text.startsWith("/") || it.text.startsWith("//")) } != false || entry.url.query.size > RecipeBundleLimits.maxQueryParameters || entry.url.path.any { !validV21UrlValue(it) } || entry.url.query.any { !RecipeSyntax.isIdentifier(it.key) || !validV21UrlValue(it.value) } || !validJsonPointer(entry.projection.pointer) || entry.projection.fields.isEmpty() || entry.projection.fields.size > 8 || entry.projection.fields.keys.any { !RecipeSyntax.isIdentifier(it) } || entry.projection.fields.values.any { it.isEmpty() || it.size > 8 || !it.all(::validJsonPointer) } || !validV21Terminal(entry) || !terminalMatchesEntrypoint(name, entry.terminal.type) || DeclaredRecipeCapability.NetworkRead !in bundle.manifest.declaredCapabilities ) return rejected(RecipeBundleErrorCode.InvalidValue, "$.entrypoints.$name") projected += entry.projection.fields.size * if (entry.projection.mode == RecipeV21ProjectionMode.Many) 256 else 1 if (projected > 2_048) return rejected(RecipeBundleErrorCode.OperationLimitExceeded, "$.entrypoints") } return RecipeBundleDecodeResult.Accepted(bundle) } private fun validV21Inputs(name: String, inputs: List): Boolean = inputs.toSet().size == inputs.size && when (name) { "popular", "latest" -> inputs == listOf(RecipeHostInput.PageIndex) || inputs == listOf(RecipeHostInput.PageOffset) "search" -> inputs == listOf(RecipeHostInput.PageIndex, RecipeHostInput.Query) || inputs == listOf(RecipeHostInput.PageOffset, RecipeHostInput.Query) "detail", "episodes" -> inputs == listOf(RecipeHostInput.ItemId) else -> inputs == listOf(RecipeHostInput.EpisodeId) } private fun validV21UrlValue(value: RecipeV21UrlValue): Boolean = when (value) { is RecipeV21UrlValue.Literal -> value.text.isNotEmpty() && value.text.length <= RecipeBundleLimits.maxStringCharacters && value.text.none { it.code < 0x20 || it == ':' || it == '#' || it == '\\' } is RecipeV21UrlValue.HostInput -> true } private fun validV21Terminal(entry: RecipeV21Entrypoint): Boolean { val allowed = when (entry.terminal.type) { RecipeV21TerminalType.Listing -> setOf("id", "title", "thumbnailUrl") RecipeV21TerminalType.Detail -> setOf("id", "title", "thumbnailUrl", "description") RecipeV21TerminalType.Episodes -> setOf("id", "season", "number") RecipeV21TerminalType.Media -> setOf("url", "quality") } val required = if (entry.terminal.type == RecipeV21TerminalType.Media) setOf("url") else if (entry.terminal.type == RecipeV21TerminalType.Episodes) setOf("id") else setOf("id", "title") return entry.projection.fields.keys.all { it in allowed } && required.all { it in entry.projection.fields } && (entry.terminal.type != RecipeV21TerminalType.Listing || entry.terminal.pageSize in 1..30) && (entry.terminal.type == RecipeV21TerminalType.Listing || entry.terminal.pageSize == null) } private fun terminalMatchesEntrypoint(name: String, type: RecipeV21TerminalType): Boolean = when (name) { "popular", "latest", "search" -> type == RecipeV21TerminalType.Listing "detail" -> type == RecipeV21TerminalType.Detail "episodes" -> type == RecipeV21TerminalType.Episodes else -> type == RecipeV21TerminalType.Media } private fun validateManifest(manifest: ExtensionRecipeManifest): Map? { if (!RecipeSyntax.isIdentifier(manifest.id) || !validText(manifest.name) || manifest.declaredCapabilities.size > RecipeBundleLimits.maxCollectionEntries || manifest.declaredOrigins.size > RecipeBundleLimits.maxOrigins ) return null val origins = mutableMapOf() for (origin in manifest.declaredOrigins) { if (!RecipeSyntax.isIdentifier(origin.id) || !RecipeSyntax.isNormalizedHttpsOrigin(origin.origin) || origins.put(origin.id, origin) != null) return null } return origins } private fun validText(value: String): Boolean = value.isNotEmpty() && value.length <= RecipeBundleLimits.maxStringCharacters private fun validJsonPointer(pointer: String): Boolean { if (pointer.isEmpty()) return true if (!pointer.startsWith('/')) return false val tokens = pointer.substring(1).split('/') return tokens.size <= RecipeBundleLimits.maxJsonPointerTokens && tokens.all { token -> token.length <= RecipeBundleLimits.maxJsonPointerTokenCharacters && token.indices.none { index -> token[index] == '~' && (index + 1 == token.length || token[index + 1] !in "01") } } } } private fun rejected(code: RecipeBundleErrorCode, path: String = "$", detail: String = "invalid recipe bundle"): RecipeBundleDecodeResult.Rejected = RecipeBundleDecodeResult.Rejected(reject(code, path, detail)) private fun reject(code: RecipeBundleErrorCode, path: String = "$", detail: String = "invalid recipe bundle"): RecipeBundleError = RecipeBundleError(code, path.take(256), detail.take(80)) /** Bounded streaming preflight: it creates no JSON tree and rejects duplicate decoded object names. */ private object JsonStructureScanner { private enum class State { RootValue, RootEnd, ObjectKeyOrEnd, ObjectKey, Colon, ObjectValue, ArrayValueOrEnd, ArrayValue, CommaOrEnd } private class Frame(val objectFrame: Boolean, var state: State) { val keys = mutableSetOf(); var entries = 0 } fun scan(source: String, maxDepth: Int, maxStringCharacters: Int, maxCollectionEntries: Int): RecipeBundleError? { val stack = mutableListOf(Frame(false, State.RootValue)) var index = 0 var scannerError: RecipeBundleError? = null fun skipWhitespace() { while (source.getOrNull(index)?.let(::isJsonWhitespace) == true) index++ } fun fail() = reject(RecipeBundleErrorCode.InvalidJson) fun finishValue(parent: Frame) { parent.state = when (parent.state) { State.RootValue -> State.RootEnd State.ObjectValue, State.ArrayValue, State.ArrayValueOrEnd -> State.CommaOrEnd else -> parent.state } } fun readString(): String? { if (source.getOrNull(index) != '"') return null index++ val decoded = StringBuilder() while (true) { val char = source.getOrNull(index++) ?: return null if (char == '"') return decoded.toString() if (char.code < 0x20) return null if (char != '\\') { decoded.append(char) } else { when (val escaped = source.getOrNull(index++)) { '"', '\\', '/' -> decoded.append(escaped) 'b' -> decoded.append('\b') 'f' -> decoded.append('\u000C') 'n' -> decoded.append('\n') 'r' -> decoded.append('\r') 't' -> decoded.append('\t') 'u' -> { if (index + 4 > source.length) return null var value = 0 repeat(4) { value = value * 16 + hexValue(source[index++]).also { if (it < 0) return null } } decoded.append(value.toChar()) } else -> return null } } if (decoded.length > maxStringCharacters) { scannerError = reject(RecipeBundleErrorCode.StringLimitExceeded) return null } } } fun readNumber(): Boolean { if (source.getOrNull(index) == '-') index++ when (val first = source.getOrNull(index)) { '0' -> { index++; if (source.getOrNull(index)?.isAsciiDigit() == true) return false } in '1'..'9' -> while (source.getOrNull(index)?.isAsciiDigit() == true) index++ else -> return false } if (source.getOrNull(index) == '.') { index++ if (source.getOrNull(index)?.isAsciiDigit() != true) return false while (source.getOrNull(index)?.isAsciiDigit() == true) index++ } if (source.getOrNull(index) == 'e' || source.getOrNull(index) == 'E') { index++ if (source.getOrNull(index) == '+' || source.getOrNull(index) == '-') index++ if (source.getOrNull(index)?.isAsciiDigit() != true) return false while (source.getOrNull(index)?.isAsciiDigit() == true) index++ } return true } fun consumeValue(parent: Frame): Boolean { when (source.getOrNull(index)) { '"' -> if (readString() == null) return false else finishValue(parent) '{', '[' -> { if (stack.size - 1 >= maxDepth) { scannerError = reject(RecipeBundleErrorCode.NestingLimitExceeded) return false } val objectFrame = source[index++] == '{' stack += Frame(objectFrame, if (objectFrame) State.ObjectKeyOrEnd else State.ArrayValueOrEnd) } 't' -> { if (!source.startsWith("true", index)) return false; index += 4; finishValue(parent) } 'f' -> { if (!source.startsWith("false", index)) return false; index += 5; finishValue(parent) } 'n' -> { if (!source.startsWith("null", index)) return false; index += 4; finishValue(parent) } '-', in '0'..'9' -> { if (!readNumber()) return false; finishValue(parent) } else -> return false } return true } while (true) { skipWhitespace() val frame = stack.last() if (frame === stack.first() && frame.state == State.RootEnd) return if (index == source.length) null else fail() when (frame.state) { State.RootValue -> if (!consumeValue(frame)) return scannerError ?: fail() State.ObjectKeyOrEnd, State.ObjectKey -> { if (frame.state == State.ObjectKeyOrEnd && source.getOrNull(index) == '}') { index++; stack.removeLast(); finishValue(stack.last()) } else { val key = readString() ?: return scannerError ?: fail() if (!frame.keys.add(key)) return reject(RecipeBundleErrorCode.DuplicateJsonKey) if (++frame.entries > maxCollectionEntries) return reject(RecipeBundleErrorCode.CollectionLimitExceeded) frame.state = State.Colon } } State.Colon -> { if (source.getOrNull(index) != ':') return fail() index++; frame.state = State.ObjectValue } State.ObjectValue -> if (!consumeValue(frame)) return scannerError ?: fail() State.ArrayValueOrEnd, State.ArrayValue -> { if (frame.state == State.ArrayValueOrEnd && source.getOrNull(index) == ']') { index++; stack.removeLast(); finishValue(stack.last()) } else { if (++frame.entries > maxCollectionEntries) return reject(RecipeBundleErrorCode.CollectionLimitExceeded) if (!consumeValue(frame)) return scannerError ?: fail() } } State.CommaOrEnd -> { val close = if (frame.objectFrame) '}' else ']' when (source.getOrNull(index)) { close -> { index++; stack.removeLast(); finishValue(stack.last()) } ',' -> { index++; frame.state = if (frame.objectFrame) State.ObjectKey else State.ArrayValue } else -> return fail() } } State.RootEnd -> return fail() } } } private fun isJsonWhitespace(char: Char): Boolean = char == ' ' || char == '\t' || char == '\n' || char == '\r' private fun Char.isAsciiDigit(): Boolean = this in '0'..'9' private fun hexValue(char: Char): Int = when (char) { in '0'..'9' -> char - '0' in 'a'..'f' -> char - 'a' + 10 in 'A'..'F' -> char - 'A' + 10 else -> -1 } }