Yokan / rebuild
Course 1 8624561

StrictRecipeBundleDecoder.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/StrictRecipeBundleDecoder.kt

implementation321 lines
1package eu.friedcutlet.yokan.services.extensions.recipe23import kotlinx.serialization.SerializationException4import kotlinx.serialization.decodeFromString5import kotlinx.serialization.json.Json67object RecipeBundleLimits {8    const val maxBundleBytes = 64 * 10249    /** Maximum nested JSON arrays/objects; the root value is not counted. */10    const val maxJsonDepth = 1611    const val maxStringCharacters = 2_04812    const val maxCollectionEntries = 6413    const val maxOrigins = 814    const val maxQueryParameters = 1615    const val maxJsonPointerTokens = 1616    const val maxJsonPointerTokenCharacters = 12817}1819enum class RecipeBundleErrorCode {20    ByteLimitExceeded,21    NestingLimitExceeded,22    StringLimitExceeded,23    CollectionLimitExceeded,24    DuplicateJsonKey,25    InvalidJson,26    InvalidBundleShape,27    UnsupportedFormatVersion,28    UnknownFieldOrOperation,29    InvalidValue,30    OperationLimitExceeded,31}3233/** All details are fixed diagnostics, never parser text or bundle data. */34data class RecipeBundleError(35    val code: RecipeBundleErrorCode,36    val path: String = "$",37    val detail: String = "",38)3940sealed interface RecipeBundleDecodeResult {41    data class Accepted(val bundle: DeclarativeExtensionBundle) : RecipeBundleDecodeResult42    data class Rejected(val error: RecipeBundleError) : RecipeBundleDecodeResult43}4445object StrictRecipeBundleDecoder {46    private val json = Json {47        ignoreUnknownKeys = false48        isLenient = false49        coerceInputValues = false50        explicitNulls = false51        useAlternativeNames = false52    }5354    fun decode(bytes: ByteArray): RecipeBundleDecodeResult {55        val preflight = boundedJsonPreflight(bytes, RecipeBundleLimits.maxBundleBytes)56        if (preflight != null) return RecipeBundleDecodeResult.Rejected(preflight)57        // Preflight already proved the bytes are valid UTF-8.58        val source = bytes.decodeToString()59        return try {60            RecipeBundleValidator.validate(json.decodeFromString<DeclarativeExtensionBundle>(source))61        } catch (error: SerializationException) {62            rejected(decodingCode(error))63        } catch (_: IllegalArgumentException) {64            rejected(RecipeBundleErrorCode.InvalidBundleShape)65        }66    }6768    /** Shared bounded structural validation for authenticated JSON payloads. */69    internal fun boundedJsonPreflight(bytes: ByteArray, maxBytes: Int): RecipeBundleError? =70        boundedPreflight(bytes, maxBytes, RecipeBundleLimits.maxStringCharacters, RecipeBundleLimits.maxCollectionEntries)7172    /** Strict response-only JSON boundary; it intentionally does not inherit signed-bundle collection ceilings. */73    internal fun boundedApiResponseJsonPreflight(bytes: ByteArray, maxBytes: Int): RecipeBundleError? = boundedPreflight(bytes, maxBytes, maxBytes, 512)7475    private fun boundedPreflight(bytes: ByteArray, maxBytes: Int, maxStringCharacters: Int, maxCollectionEntries: Int): RecipeBundleError? {76        if (bytes.size > maxBytes) return reject(RecipeBundleErrorCode.ByteLimitExceeded)77        val source = try {78            bytes.decodeToString(throwOnInvalidSequence = true)79        } catch (_: CharacterCodingException) {80            return reject(RecipeBundleErrorCode.InvalidJson)81        }82        return JsonStructureScanner.scan(source, RecipeBundleLimits.maxJsonDepth, maxStringCharacters, maxCollectionEntries)83    }8485    private fun decodingCode(error: SerializationException): RecipeBundleErrorCode {86        val message = error.message.orEmpty().lowercase()87        return when {88            "recipeformatversion" in message -> RecipeBundleErrorCode.UnsupportedFormatVersion89            "unknown key" in message || "subclass" in message || "discriminator" in message ->90                RecipeBundleErrorCode.UnknownFieldOrOperation91            else -> RecipeBundleErrorCode.InvalidBundleShape92        }93    }94}9596object RecipeBundleValidator {97    /** Only V2.1 entrypoint bundles run; older step-based versions still parse so they are rejected here explicitly. */98    fun validate(bundle: DeclarativeExtensionBundle): RecipeBundleDecodeResult {99        if (bundle.manifest.formatVersion != RecipeFormatVersion.V21) return rejected(RecipeBundleErrorCode.UnsupportedFormatVersion, "$.manifest.formatVersion")100        val originById = validateManifest(bundle.manifest) ?: return rejected(RecipeBundleErrorCode.InvalidValue, "$.manifest")101        return validateV21(bundle, originById)102    }103104    private fun validateV21(bundle: DeclarativeExtensionBundle, origins: Map<String, DeclaredRecipeOrigin>): RecipeBundleDecodeResult {105        if (bundle.recipe.steps.isNotEmpty() || bundle.entrypoints.isEmpty() || bundle.entrypoints.size > 6) return rejected(RecipeBundleErrorCode.InvalidValue, "$.entrypoints")106        var projected = 0107        for ((name, entry) in bundle.entrypoints) {108            if (name !in setOf("popular", "latest", "search", "detail", "episodes", "media") || !validV21Inputs(name, entry.inputs) ||109                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 ||110                entry.url.path.any { !validV21UrlValue(it) } || entry.url.query.any { !RecipeSyntax.isIdentifier(it.key) || !validV21UrlValue(it.value) } ||111                !validJsonPointer(entry.projection.pointer) || entry.projection.fields.isEmpty() || entry.projection.fields.size > 8 ||112                entry.projection.fields.keys.any { !RecipeSyntax.isIdentifier(it) } || entry.projection.fields.values.any { it.isEmpty() || it.size > 8 || !it.all(::validJsonPointer) } ||113                !validV21Terminal(entry) || !terminalMatchesEntrypoint(name, entry.terminal.type) || DeclaredRecipeCapability.NetworkRead !in bundle.manifest.declaredCapabilities114            ) return rejected(RecipeBundleErrorCode.InvalidValue, "$.entrypoints.$name")115            projected += entry.projection.fields.size * if (entry.projection.mode == RecipeV21ProjectionMode.Many) 256 else 1116            if (projected > 2_048) return rejected(RecipeBundleErrorCode.OperationLimitExceeded, "$.entrypoints")117        }118        return RecipeBundleDecodeResult.Accepted(bundle)119    }120121    private fun validV21Inputs(name: String, inputs: List<RecipeHostInput>): Boolean = inputs.toSet().size == inputs.size && when (name) {122        "popular", "latest" -> inputs == listOf(RecipeHostInput.PageIndex) || inputs == listOf(RecipeHostInput.PageOffset)123        "search" -> inputs == listOf(RecipeHostInput.PageIndex, RecipeHostInput.Query) || inputs == listOf(RecipeHostInput.PageOffset, RecipeHostInput.Query)124        "detail", "episodes" -> inputs == listOf(RecipeHostInput.ItemId)125        else -> inputs == listOf(RecipeHostInput.EpisodeId)126    }127    private fun validV21UrlValue(value: RecipeV21UrlValue): Boolean = when (value) {128        is RecipeV21UrlValue.Literal -> value.text.isNotEmpty() && value.text.length <= RecipeBundleLimits.maxStringCharacters && value.text.none { it.code < 0x20 || it == ':' || it == '#' || it == '\\' }129        is RecipeV21UrlValue.HostInput -> true130    }131    private fun validV21Terminal(entry: RecipeV21Entrypoint): Boolean {132        val allowed = when (entry.terminal.type) {133            RecipeV21TerminalType.Listing -> setOf("id", "title", "thumbnailUrl")134            RecipeV21TerminalType.Detail -> setOf("id", "title", "thumbnailUrl", "description")135            RecipeV21TerminalType.Episodes -> setOf("id", "season", "number")136            RecipeV21TerminalType.Media -> setOf("url", "quality")137        }138        val required = if (entry.terminal.type == RecipeV21TerminalType.Media) setOf("url") else if (entry.terminal.type == RecipeV21TerminalType.Episodes) setOf("id") else setOf("id", "title")139        return entry.projection.fields.keys.all { it in allowed } && required.all { it in entry.projection.fields } &&140            (entry.terminal.type != RecipeV21TerminalType.Listing || entry.terminal.pageSize in 1..30) &&141            (entry.terminal.type == RecipeV21TerminalType.Listing || entry.terminal.pageSize == null)142    }143    private fun terminalMatchesEntrypoint(name: String, type: RecipeV21TerminalType): Boolean = when (name) {144        "popular", "latest", "search" -> type == RecipeV21TerminalType.Listing145        "detail" -> type == RecipeV21TerminalType.Detail146        "episodes" -> type == RecipeV21TerminalType.Episodes147        else -> type == RecipeV21TerminalType.Media148    }149150    private fun validateManifest(manifest: ExtensionRecipeManifest): Map<String, DeclaredRecipeOrigin>? {151        if (!RecipeSyntax.isIdentifier(manifest.id) || !validText(manifest.name) ||152            manifest.declaredCapabilities.size > RecipeBundleLimits.maxCollectionEntries ||153            manifest.declaredOrigins.size > RecipeBundleLimits.maxOrigins154        ) return null155        val origins = mutableMapOf<String, DeclaredRecipeOrigin>()156        for (origin in manifest.declaredOrigins) {157            if (!RecipeSyntax.isIdentifier(origin.id) || !RecipeSyntax.isNormalizedHttpsOrigin(origin.origin) || origins.put(origin.id, origin) != null) return null158        }159        return origins160    }161162    private fun validText(value: String): Boolean = value.isNotEmpty() && value.length <= RecipeBundleLimits.maxStringCharacters163    private fun validJsonPointer(pointer: String): Boolean {164        if (pointer.isEmpty()) return true165        if (!pointer.startsWith('/')) return false166        val tokens = pointer.substring(1).split('/')167        return tokens.size <= RecipeBundleLimits.maxJsonPointerTokens && tokens.all { token ->168            token.length <= RecipeBundleLimits.maxJsonPointerTokenCharacters && token.indices.none { index -> token[index] == '~' && (index + 1 == token.length || token[index + 1] !in "01") }169        }170    }171}172173private fun rejected(code: RecipeBundleErrorCode, path: String = "$", detail: String = "invalid recipe bundle"): RecipeBundleDecodeResult.Rejected =174    RecipeBundleDecodeResult.Rejected(reject(code, path, detail))175176private fun reject(code: RecipeBundleErrorCode, path: String = "$", detail: String = "invalid recipe bundle"): RecipeBundleError =177    RecipeBundleError(code, path.take(256), detail.take(80))178179/** Bounded streaming preflight: it creates no JSON tree and rejects duplicate decoded object names. */180private object JsonStructureScanner {181    private enum class State { RootValue, RootEnd, ObjectKeyOrEnd, ObjectKey, Colon, ObjectValue, ArrayValueOrEnd, ArrayValue, CommaOrEnd }182    private class Frame(val objectFrame: Boolean, var state: State) { val keys = mutableSetOf<String>(); var entries = 0 }183184    fun scan(source: String, maxDepth: Int, maxStringCharacters: Int, maxCollectionEntries: Int): RecipeBundleError? {185        val stack = mutableListOf(Frame(false, State.RootValue))186        var index = 0187        var scannerError: RecipeBundleError? = null188189        fun skipWhitespace() { while (source.getOrNull(index)?.let(::isJsonWhitespace) == true) index++ }190        fun fail() = reject(RecipeBundleErrorCode.InvalidJson)191        fun finishValue(parent: Frame) {192            parent.state = when (parent.state) {193                State.RootValue -> State.RootEnd194                State.ObjectValue, State.ArrayValue, State.ArrayValueOrEnd -> State.CommaOrEnd195                else -> parent.state196            }197        }198        fun readString(): String? {199            if (source.getOrNull(index) != '"') return null200            index++201            val decoded = StringBuilder()202            while (true) {203                val char = source.getOrNull(index++) ?: return null204                if (char == '"') return decoded.toString()205                if (char.code < 0x20) return null206                if (char != '\\') {207                    decoded.append(char)208                } else {209                    when (val escaped = source.getOrNull(index++)) {210                        '"', '\\', '/' -> decoded.append(escaped)211                        'b' -> decoded.append('\b')212                        'f' -> decoded.append('\u000C')213                        'n' -> decoded.append('\n')214                        'r' -> decoded.append('\r')215                        't' -> decoded.append('\t')216                        'u' -> {217                            if (index + 4 > source.length) return null218                            var value = 0219                            repeat(4) { value = value * 16 + hexValue(source[index++]).also { if (it < 0) return null } }220                            decoded.append(value.toChar())221                        }222                        else -> return null223                    }224                }225                if (decoded.length > maxStringCharacters) {226                    scannerError = reject(RecipeBundleErrorCode.StringLimitExceeded)227                    return null228                }229            }230        }231        fun readNumber(): Boolean {232            if (source.getOrNull(index) == '-') index++233            when (val first = source.getOrNull(index)) {234                '0' -> { index++; if (source.getOrNull(index)?.isAsciiDigit() == true) return false }235                in '1'..'9' -> while (source.getOrNull(index)?.isAsciiDigit() == true) index++236                else -> return false237            }238            if (source.getOrNull(index) == '.') {239                index++240                if (source.getOrNull(index)?.isAsciiDigit() != true) return false241                while (source.getOrNull(index)?.isAsciiDigit() == true) index++242            }243            if (source.getOrNull(index) == 'e' || source.getOrNull(index) == 'E') {244                index++245                if (source.getOrNull(index) == '+' || source.getOrNull(index) == '-') index++246                if (source.getOrNull(index)?.isAsciiDigit() != true) return false247                while (source.getOrNull(index)?.isAsciiDigit() == true) index++248            }249            return true250        }251        fun consumeValue(parent: Frame): Boolean {252            when (source.getOrNull(index)) {253                '"' -> if (readString() == null) return false else finishValue(parent)254                '{', '[' -> {255                    if (stack.size - 1 >= maxDepth) {256                        scannerError = reject(RecipeBundleErrorCode.NestingLimitExceeded)257                        return false258                    }259                    val objectFrame = source[index++] == '{'260                    stack += Frame(objectFrame, if (objectFrame) State.ObjectKeyOrEnd else State.ArrayValueOrEnd)261                }262                't' -> { if (!source.startsWith("true", index)) return false; index += 4; finishValue(parent) }263                'f' -> { if (!source.startsWith("false", index)) return false; index += 5; finishValue(parent) }264                'n' -> { if (!source.startsWith("null", index)) return false; index += 4; finishValue(parent) }265                '-', in '0'..'9' -> { if (!readNumber()) return false; finishValue(parent) }266                else -> return false267            }268            return true269        }270271        while (true) {272            skipWhitespace()273            val frame = stack.last()274            if (frame === stack.first() && frame.state == State.RootEnd) return if (index == source.length) null else fail()275            when (frame.state) {276                State.RootValue -> if (!consumeValue(frame)) return scannerError ?: fail()277                State.ObjectKeyOrEnd, State.ObjectKey -> {278                    if (frame.state == State.ObjectKeyOrEnd && source.getOrNull(index) == '}') {279                        index++; stack.removeLast(); finishValue(stack.last())280                    } else {281                        val key = readString() ?: return scannerError ?: fail()282                        if (!frame.keys.add(key)) return reject(RecipeBundleErrorCode.DuplicateJsonKey)283                        if (++frame.entries > maxCollectionEntries) return reject(RecipeBundleErrorCode.CollectionLimitExceeded)284                        frame.state = State.Colon285                    }286                }287                State.Colon -> {288                    if (source.getOrNull(index) != ':') return fail()289                    index++; frame.state = State.ObjectValue290                }291                State.ObjectValue -> if (!consumeValue(frame)) return scannerError ?: fail()292                State.ArrayValueOrEnd, State.ArrayValue -> {293                    if (frame.state == State.ArrayValueOrEnd && source.getOrNull(index) == ']') {294                        index++; stack.removeLast(); finishValue(stack.last())295                    } else {296                        if (++frame.entries > maxCollectionEntries) return reject(RecipeBundleErrorCode.CollectionLimitExceeded)297                        if (!consumeValue(frame)) return scannerError ?: fail()298                    }299                }300                State.CommaOrEnd -> {301                    val close = if (frame.objectFrame) '}' else ']'302                    when (source.getOrNull(index)) {303                        close -> { index++; stack.removeLast(); finishValue(stack.last()) }304                        ',' -> { index++; frame.state = if (frame.objectFrame) State.ObjectKey else State.ArrayValue }305                        else -> return fail()306                    }307                }308                State.RootEnd -> return fail()309            }310        }311    }312313    private fun isJsonWhitespace(char: Char): Boolean = char == ' ' || char == '\t' || char == '\n' || char == '\r'314    private fun Char.isAsciiDigit(): Boolean = this in '0'..'9'315    private fun hexValue(char: Char): Int = when (char) {316        in '0'..'9' -> char - '0'317        in 'a'..'f' -> char - 'a' + 10318        in 'A'..'F' -> char - 'A' + 10319        else -> -1320    }321}322

Search chapters, reference and source filenames.