package eu.friedcutlet.yokan.services.extensions.recipe import eu.friedcutlet.yokan.services.catchingNonCancellation import kotlinx.coroutines.ensureActive import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlin.coroutines.coroutineContext import kotlin.time.TimeSource enum class RecipeExecutionErrorCode { InvalidBundle, InvalidPolicy, OriginDenied, DocumentBudgetExceeded, BrokerDenied, BrokerHttpFailure, BrokerDeadlineExceeded, BrokerFailure, InvalidJsonDocument, JsonPointerNotFound, } data class RecipeExecutionError(val code: RecipeExecutionErrorCode) sealed interface RecipeEntrypointInput { data class PageIndex(val value: Int) : RecipeEntrypointInput /** Derived by the runtime from [PageIndex] for `pageOffset` entrypoints; hosts never supply it. */ data class PageOffset(val value: Int) : RecipeEntrypointInput data class Query(val value: String) : RecipeEntrypointInput data class ItemId(val value: String) : RecipeEntrypointInput data class EpisodeId(val value: String) : RecipeEntrypointInput } sealed interface RecipeEntrypointResult { data class Listing(val items: List, val pageSize: Int) : RecipeEntrypointResult data class Detail(val id: String, val title: String, val thumbnailUrl: String?, val description: String?) : RecipeEntrypointResult data class Episodes(val items: List) : RecipeEntrypointResult data class Media(val items: List) : RecipeEntrypointResult data class Item(val id: String, val title: String, val thumbnailUrl: String?) data class Episode(val id: String, val season: String?, val number: String?) data class MediaItem(val url: String, val quality: String?) } sealed interface RecipeEntrypointExecutionResult { data class Completed(val result: RecipeEntrypointResult) : RecipeEntrypointExecutionResult data class Rejected(val error: RecipeExecutionError) : RecipeEntrypointExecutionResult } /** Injectable monotonic source used only to form one invocation-wide deadline. */ fun interface RecipeMonotonicClock { fun nowMillis(): Long } private object DefaultRecipeMonotonicClock : RecipeMonotonicClock { private val start = TimeSource.Monotonic.markNow() override fun nowMillis(): Long = start.elapsedNow().inWholeMilliseconds } /** Host-issued, nonserializable limits. Every limit is aggregate for one execution invocation. */ class RecipeExecutionPolicy( grantedOrigins: Map, val maxReceivedDocumentBytes: Int = 256 * 1024, val brokerDeadlineMillis: Long = 15_000, ) { val grantedOrigins: Map = grantedOrigins.toMap() } /** * Host broker contract. The host must enforce destination/public-address policy, redirect/retry/session isolation, * streaming decompressed response limits, JSON-only response content, and cancellation. Recipes provide no headers, cookies, methods, or authority. */ data class RecipeBrokerRequest( val originId: String, val origin: String, val pathAndQuery: String, val maxDocumentBytes: Int, /** Remaining time from the single runtime invocation deadline; never a refreshed per-request allowance. */ val deadlineMillis: Long, ) { val url: String get() = origin + pathAndQuery } sealed interface RecipeBrokerResult { data class Document(val bytes: ByteArray) : RecipeBrokerResult data object OriginDenied : RecipeBrokerResult data object HttpFailure : RecipeBrokerResult data object ResponseTooLarge : RecipeBrokerResult data object Failed : RecipeBrokerResult } interface RecipeCapabilityBroker { suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult } class DeclarativeRecipeRuntime( private val broker: RecipeCapabilityBroker, private val clock: RecipeMonotonicClock = DefaultRecipeMonotonicClock, ) { suspend fun executeEntrypoint(bundle: DeclarativeExtensionBundle, entrypoint: String, hostInputs: Map, policy: RecipeExecutionPolicy): RecipeEntrypointExecutionResult { coroutineContext.ensureActive() val deadline = InvocationDeadline(clock, policy.brokerDeadlineMillis) if (!deadline.isActive()) return entryRejected(RecipeExecutionErrorCode.BrokerDeadlineExceeded) if (bundle.manifest.formatVersion != RecipeFormatVersion.V21 || RecipeBundleValidator.validate(bundle) !is RecipeBundleDecodeResult.Accepted || !validPolicy(policy)) return entryRejected(RecipeExecutionErrorCode.InvalidBundle) val entry = bundle.entrypoints[entrypoint] ?: return entryRejected(RecipeExecutionErrorCode.InvalidBundle) val inputs = pageOffsetInputs(entry, hostInputs) val expected = entry.inputs.associateWith { it.name.replaceFirstChar { c -> c.lowercase() } } if (inputs.keys != expected.values.toSet() || !inputs.all { (key, value) -> expected.entries.any { it.value == key && inputMatches(it.key, value) } }) return entryRejected(RecipeExecutionErrorCode.InvalidPolicy) val origin = bundle.manifest.declaredOrigins.firstOrNull { it.id == entry.url.origin.originId } ?: return entryRejected(RecipeExecutionErrorCode.InvalidBundle) if (policy.grantedOrigins[origin.id] != origin.origin) return entryRejected(RecipeExecutionErrorCode.OriginDenied) val path = entry.url.path.joinToString("") { value -> when (value) { is RecipeV21UrlValue.Literal -> value.text; is RecipeV21UrlValue.HostInput -> percentEncode(inputText(inputs.getValue(expected.getValue(value.input)))) } } val query = entry.url.query.entries.sortedBy { it.key }.joinToString("&", prefix = if (entry.url.query.isEmpty()) "" else "?") { (key, value) -> "$key=${percentEncode(when (value) { is RecipeV21UrlValue.Literal -> value.text; is RecipeV21UrlValue.HostInput -> inputText(inputs.getValue(expected.getValue(value.input))) })}" } val remaining = deadline.remainingMillis() if (remaining <= 0) return entryRejected(RecipeExecutionErrorCode.BrokerDeadlineExceeded) val response = catchingNonCancellation { broker.fetch(RecipeBrokerRequest(origin.id, origin.origin, path + query, policy.maxReceivedDocumentBytes, remaining)) } .getOrElse { return entryRejected(RecipeExecutionErrorCode.BrokerFailure) } val bytes = when (response) { is RecipeBrokerResult.Document -> response.bytes RecipeBrokerResult.OriginDenied -> return entryRejected(RecipeExecutionErrorCode.BrokerDenied) RecipeBrokerResult.HttpFailure -> return entryRejected(RecipeExecutionErrorCode.BrokerHttpFailure) RecipeBrokerResult.ResponseTooLarge -> return entryRejected(RecipeExecutionErrorCode.DocumentBudgetExceeded) RecipeBrokerResult.Failed -> return entryRejected(RecipeExecutionErrorCode.BrokerFailure) } if (bytes.size > policy.maxReceivedDocumentBytes || StrictRecipeBundleDecoder.boundedApiResponseJsonPreflight(bytes, policy.maxReceivedDocumentBytes) != null) return entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument) // The preflight above already proved the bytes are valid UTF-8 JSON within the structural limits. val root = try { strictJson.parseToJsonElement(bytes.decodeToString()) } catch (_: IllegalArgumentException) { return entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument) } val selected = jsonPointerElement(root, entry.projection.pointer) ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound) val rows = when (entry.projection.mode) { RecipeV21ProjectionMode.One -> listOf(selected as? JsonObject ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound)); RecipeV21ProjectionMode.Many -> (selected as? JsonArray)?.takeIf { it.size <= resultLimit(entry.terminal.type) }?.map { it as? JsonObject ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound) } ?: return entryRejected(RecipeExecutionErrorCode.JsonPointerNotFound) } val mapped = rows.map { row -> coroutineContext.ensureActive() if (!deadline.isActive()) return entryRejected(RecipeExecutionErrorCode.BrokerDeadlineExceeded) entry.projection.fields.mapValues { (_, pointers) -> pointers.firstNotNullOfOrNull { jsonPointerScalar(row, it) } } } if (mapped.any { fields -> entry.projection.fields.any { (name, _) -> fields[name] == null && name in requiredFields(entry.terminal.type) } }) return entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument) return mapTerminal(entry.terminal, mapped) ?: entryRejected(RecipeExecutionErrorCode.InvalidJsonDocument) } private fun validPolicy(policy: RecipeExecutionPolicy): Boolean = policy.maxReceivedDocumentBytes >= 0 && policy.brokerDeadlineMillis > 0 && policy.grantedOrigins.all { (id, origin) -> RecipeSyntax.isIdentifier(id) && RecipeSyntax.isNormalizedHttpsOrigin(origin) } private companion object { val strictJson = Json { ignoreUnknownKeys = false; isLenient = false; coerceInputValues = false; explicitNulls = false; useAlternativeNames = false } } } private class InvocationDeadline(clock: RecipeMonotonicClock, durationMillis: Long) { private val clock = clock private val expiresAt = clock.nowMillis().let { start -> if (start > Long.MAX_VALUE - durationMillis) Long.MAX_VALUE else start + durationMillis } suspend fun isActive(): Boolean { coroutineContext.ensureActive() return clock.nowMillis() < expiresAt } suspend fun remainingMillis(): Long { coroutineContext.ensureActive() return (expiresAt - clock.nowMillis()).coerceAtLeast(0) } } private fun jsonPointerScalar(root: JsonElement, pointer: String): String? { val rawTokens = when { pointer.isEmpty() -> emptyList() !pointer.startsWith('/') -> return null else -> pointer.substring(1).split('/') } if (rawTokens.size > RecipeBundleLimits.maxJsonPointerTokens) return null var current = root for (raw in rawTokens) { if (raw.length > RecipeBundleLimits.maxJsonPointerTokenCharacters) return null val token = decodePointerToken(raw) ?: return null current = when (current) { is JsonObject -> current[token] ?: return null is JsonArray -> { if (token.isEmpty() || (token.length > 1 && token[0] == '0') || token.any { it !in '0'..'9' }) return null current.getOrNull(token.toIntOrNull() ?: return null) ?: return null } else -> return null } } val primitive = current as? JsonPrimitive ?: return null return primitive.takeUnless { it is JsonNull }?.content } private fun decodePointerToken(raw: String): String? { val decoded = StringBuilder() var index = 0 while (index < raw.length) { val char = raw[index++] if (char != '~') decoded.append(char) else when (raw.getOrNull(index++)) { '0' -> decoded.append('~') '1' -> decoded.append('/') else -> return null } } return decoded.toString() } private fun inputMatches(expected: RecipeHostInput, value: RecipeEntrypointInput): Boolean = when (expected) { RecipeHostInput.PageIndex -> (value as? RecipeEntrypointInput.PageIndex)?.value in 0..999 RecipeHostInput.PageOffset -> (value as? RecipeEntrypointInput.PageOffset)?.value in 0..999 * 30 RecipeHostInput.Query -> (value as? RecipeEntrypointInput.Query)?.value?.let { it.length <= 256 && it.none { c -> c.code < 0x20 } } == true RecipeHostInput.ItemId -> (value as? RecipeEntrypointInput.ItemId)?.value?.let(::validOpaqueId) == true RecipeHostInput.EpisodeId -> (value as? RecipeEntrypointInput.EpisodeId)?.value?.let(::validOpaqueId) == true } private fun inputText(value: RecipeEntrypointInput): String = when (value) { is RecipeEntrypointInput.PageIndex -> value.value.toString(); is RecipeEntrypointInput.PageOffset -> value.value.toString(); is RecipeEntrypointInput.Query -> value.value; is RecipeEntrypointInput.ItemId -> value.value; is RecipeEntrypointInput.EpisodeId -> value.value } /** A `pageOffset` entrypoint receives the host's zero-based page index as an item offset: `pageIndex × pageSize`. */ private fun pageOffsetInputs(entry: RecipeV21Entrypoint, inputs: Map): Map { if (RecipeHostInput.PageOffset !in entry.inputs) return inputs val page = inputs["pageIndex"] as? RecipeEntrypointInput.PageIndex ?: return inputs val pageSize = entry.terminal.pageSize ?: return inputs return inputs - "pageIndex" + ("pageOffset" to RecipeEntrypointInput.PageOffset(page.value * pageSize)) } private fun validOpaqueId(value: String) = value.length in 1..64 && value.all { it in '0'..'9' || it in 'a'..'z' || it in 'A'..'Z' || it == '-' || it == '_' } private fun percentEncode(value: String): String = value.encodeToByteArray().joinToString("") { byte -> val n = byte.toInt() and 255; if ((n in 48..57) || (n in 65..90) || (n in 97..122) || n in intArrayOf(45, 46, 95, 126)) n.toChar().toString() else "%${"0123456789ABCDEF"[n ushr 4]}${"0123456789ABCDEF"[n and 15]}" } private fun jsonPointerElement(root: JsonElement, pointer: String): JsonElement? { val tokens = if (pointer.isEmpty()) emptyList() else pointer.takeIf { it.startsWith('/') }?.substring(1)?.split('/') ?: return null var current = root for (raw in tokens) { val token = decodePointerToken(raw) ?: return null; current = when (current) { is JsonObject -> current[token] ?: return null; is JsonArray -> current.getOrNull(token.toIntOrNull() ?: return null) ?: return null; else -> return null } } return current } private fun resultLimit(type: RecipeV21TerminalType) = when (type) { RecipeV21TerminalType.Listing -> 30; RecipeV21TerminalType.Detail -> 1; RecipeV21TerminalType.Episodes -> 256; RecipeV21TerminalType.Media -> 16 } private fun requiredFields(type: RecipeV21TerminalType) = when (type) { RecipeV21TerminalType.Media -> setOf("url"); RecipeV21TerminalType.Episodes -> setOf("id"); else -> setOf("id", "title") } private fun mapTerminal(terminal: RecipeV21Terminal, rows: List>): RecipeEntrypointExecutionResult.Completed? = when (terminal.type) { RecipeV21TerminalType.Listing -> RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Listing(rows.map { RecipeEntrypointResult.Item(it["id"] ?: return null, it["title"] ?: return null, it["thumbnailUrl"]) }, terminal.pageSize ?: return null)) RecipeV21TerminalType.Detail -> rows.singleOrNull()?.let { RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Detail(it["id"] ?: return null, it["title"] ?: return null, it["thumbnailUrl"], it["description"])) } RecipeV21TerminalType.Episodes -> RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Episodes(rows.map { RecipeEntrypointResult.Episode(it["id"] ?: return null, it["season"], it["number"]) })) RecipeV21TerminalType.Media -> RecipeEntrypointExecutionResult.Completed(RecipeEntrypointResult.Media(rows.map { val url = it["url"] ?: return null; if (!url.startsWith("https://") || url.length > 2048) return null; RecipeEntrypointResult.MediaItem(url, it["quality"]?.takeIf { q -> q.length <= 128 }) })) } private fun entryRejected(code: RecipeExecutionErrorCode) = RecipeEntrypointExecutionResult.Rejected(RecipeExecutionError(code))