# 07 — signed-recipe-catalogs: file workbook

[Implementation chapter](../chapters/07-signed-recipe-catalogs.md) · [Coverage index](README.md)

Each text entry includes the complete pinned file to write at the displayed path, plus an exact-byte download. Read the chapter for implementation order and behavior, then connect callers and reproduce the tests. Platform variants preserve their platform capabilities. Binary assets are retained with applicable licenses or independently recreated, not transcribed as code.

**Pinned baseline for comparison.** Use the reviewed listings in the [implementation chapters](../README.md#reading-order) and the [reviewed source archive](reviewed-source.zip) when reconstructing the app. See the [architecture review](architecture-review.md) for changes.

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CatalogEnrollmentCode.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CatalogEnrollmentCode.kt) · implementation · 115 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
11: internal fun loopbackCatalogOrigin(url: String): String? {
20: class CatalogEnrollmentCode private constructor(
29: fun render(): String = listOf(
33: internal fun trustPolicy(): CatalogTrustPolicy = CatalogTrustPolicy(
38: override fun equals(other: Any?): Boolean = other is CatalogEnrollmentCode &&
41: override fun hashCode(): Int = (((catalogId.hashCode() * 31 + catalogEnvelopeUrl.hashCode()) * 31 + keyId.hashCode()) * 31 + rawEd25519PublicKey.contentHashCode())
42: override fun toString(): String = render()
52: fun parse(value: String): CatalogEnrollmentCode? {
64: private fun safeCanonicalHttpsUrl(value: String): Boolean {
74: private fun decodeCanonicalBase64Url(value: String): ByteArray? {
91: private fun encodeBase64Url(bytes: ByteArray): String = buildString((bytes.size * 4 + 2) / 3) {
104: private fun base64UrlValue(character: Char): Int = when (character) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CatalogEnrollmentCode.kt) · SHA-256 `06f60e2b20b68c9691dc9cf6fa14b45e58ab59a5fece6268123d1a96520f5e1d`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.util.sha256

private const val loopbackCatalogPrefix = "http://127.0.0.1:"

/**
 * `http://127.0.0.1:<port>` when [url] targets a local test catalog server, else null. Such URLs pass syntax checks
 * everywhere, but only the catalog downloader decides whether to fetch them (developer mode).
 */
internal fun loopbackCatalogOrigin(url: String): String? {
    if (!url.startsWith(loopbackCatalogPrefix)) return null
    val authorityEnd = url.indexOf('/', loopbackCatalogPrefix.length).takeIf { it >= 0 } ?: return null
    val port = url.substring(loopbackCatalogPrefix.length, authorityEnd)
    if (port.isEmpty() || port.length > 5 || port.first() == '0' || port.any { it !in '0'..'9' } || port.toInt() > 65_535) return null
    return url.substring(0, authorityEnd)
}

/** A portable trust proposal; parsing it never changes a catalog's trust state. */
class CatalogEnrollmentCode private constructor(
    val catalogId: String,
    val catalogEnvelopeUrl: String,
    val keyId: String,
    private val rawEd25519PublicKey: ByteArray,
) {
    /** Stable lowercase SHA-256 fingerprint for explicit user confirmation. */
    val publicKeyFingerprint: String = sha256(rawEd25519PublicKey).toHexString()

    fun render(): String = listOf(
        prefix, version, catalogId, encodeBase64Url(catalogEnvelopeUrl.encodeToByteArray()), keyId, encodeBase64Url(rawEd25519PublicKey),
    ).joinToString(":")

    internal fun trustPolicy(): CatalogTrustPolicy = CatalogTrustPolicy(
        catalogId,
        listOf(TrustedCatalogKey(catalogId, keyId, rawEd25519PublicKey.copyOf(), TrustedCatalogKeyState.Active)),
    )

    override fun equals(other: Any?): Boolean = other is CatalogEnrollmentCode &&
        catalogId == other.catalogId && catalogEnvelopeUrl == other.catalogEnvelopeUrl && keyId == other.keyId && rawEd25519PublicKey.contentEquals(other.rawEd25519PublicKey)

    override fun hashCode(): Int = (((catalogId.hashCode() * 31 + catalogEnvelopeUrl.hashCode()) * 31 + keyId.hashCode()) * 31 + rawEd25519PublicKey.contentHashCode())
    override fun toString(): String = render()

    companion object {
        private const val prefix = "yokan-catalog"
        private const val version = "v1"
        private const val maxCodeCharacters = 4_096
        private const val maxUrlCharacters = 2_048
        private const val publicKeyBytes = 32

        /** Returns null unless [value] is a bounded, canonical v1 enrollment code. */
        fun parse(value: String): CatalogEnrollmentCode? {
            if (value.length > maxCodeCharacters || value.any { it.code !in 0x21..0x7e }) return null
            val parts = value.split(':')
            if (parts.size != 6 || parts[0] != prefix || parts[1] != version || !RecipeSyntax.isIdentifier(parts[2]) || !RecipeSyntax.isIdentifier(parts[4], RecipeCatalogLimits.maxKeyIdBytes)) return null
            val urlBytes = decodeCanonicalBase64Url(parts[3]) ?: return null
            val url = try { urlBytes.decodeToString(throwOnInvalidSequence = true) } catch (_: CharacterCodingException) { return null }
            if (!url.encodeToByteArray().contentEquals(urlBytes) || !safeCanonicalHttpsUrl(url)) return null
            val publicKey = decodeCanonicalBase64Url(parts[5]) ?: return null
            if (publicKey.size != publicKeyBytes) return null
            return CatalogEnrollmentCode(parts[2], url, parts[4], publicKey)
        }

        private fun safeCanonicalHttpsUrl(value: String): Boolean {
            if (value.length !in 9..maxUrlCharacters || value.any { it.code !in 0x21..0x7e || it == '\\' || it == '?' || it == '#' }) return false
            loopbackCatalogOrigin(value)?.let { return RecipeSyntax.isCanonicalPath(value.substring(it.length)) }
            if (!value.startsWith("https://")) return false
            val authorityEnd = value.indexOf('/', startIndex = 8).takeIf { it >= 0 } ?: return false
            val host = value.substring(8, authorityEnd)
            if (host.isEmpty() || '@' in host || ':' in host || !RecipeSyntax.isHost(host)) return false
            return RecipeSyntax.isCanonicalPath(value.substring(authorityEnd))
        }

        private fun decodeCanonicalBase64Url(value: String): ByteArray? {
            if (value.isEmpty() || value.length % 4 == 1 || value.any { base64UrlValue(it) < 0 }) return null
            val output = ArrayList<Byte>()
            var accumulator = 0
            var bits = 0
            for (character in value) {
                accumulator = (accumulator shl 6) or base64UrlValue(character)
                bits += 6
                while (bits >= 8) {
                    bits -= 8
                    output += ((accumulator ushr bits) and 0xff).toByte()
                }
            }
            val decoded = output.toByteArray()
            return decoded.takeIf { encodeBase64Url(it) == value }
        }

        private fun encodeBase64Url(bytes: ByteArray): String = buildString((bytes.size * 4 + 2) / 3) {
            var index = 0
            while (index < bytes.size) {
                val first = bytes[index++].toInt() and 0xff
                val second = if (index < bytes.size) bytes[index++].toInt() and 0xff else -1
                val third = if (index < bytes.size) bytes[index++].toInt() and 0xff else -1
                append(base64UrlAlphabet[first ushr 2])
                append(base64UrlAlphabet[((first and 3) shl 4) or if (second >= 0) second ushr 4 else 0])
                if (second >= 0) append(base64UrlAlphabet[((second and 15) shl 2) or if (third >= 0) third ushr 6 else 0])
                if (third >= 0) append(base64UrlAlphabet[third and 63])
            }
        }

        private fun base64UrlValue(character: Char): Int = when (character) {
            in 'A'..'Z' -> character - 'A'
            in 'a'..'z' -> character - 'a' + 26
            in '0'..'9' -> character - '0' + 52
            '-' -> 62
            '_' -> 63
            else -> -1
        }

        private const val base64UrlAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipe.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipe.kt) · implementation · 109 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
16: data class DeclarativeExtensionBundle(
23: data class ExtensionRecipeManifest(
33: data class DeclaredRecipeOrigin(
39: enum class RecipeFormatVersion {
52: enum class DeclaredRecipeCapability {
62: data class ExtensionRecipe(
67: data class RecipeV21Entrypoint(
75: enum class RecipeHostInput { @SerialName("pageIndex") PageIndex, @SerialName("pageOffset") PageOffset, @SerialName("query") Query, @SerialName("itemId") ItemId, @SerialName("episodeId") EpisodeId }
78: data class RecipeV21Url(val origin: DeclaredOriginReference, val path: List<RecipeV21UrlValue>, val query: Map<String, RecipeV21UrlValue> = emptyMap())
83: sealed interface RecipeV21UrlValue {
89: data class RecipeV21Projection(
97: internal object RecipeV21FieldPointersSerializer : JsonTransformingSerializer<List<String>>(ListSerializer(String.serializer())) {
98: override fun transformDeserialize(element: JsonElement): JsonElement = if (element is JsonPrimitive) JsonArray(listOf(element)) else element
99: override fun transformSerialize(element: JsonElement): JsonElement = (element as? JsonArray)?.singleOrNull() ?: element
103: data class RecipeV21Terminal(val type: RecipeV21TerminalType, val pageSize: Int? = null)
107: data class DeclaredOriginReference(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipe.kt) · SHA-256 `c01e91d20ba56eaf785f706d4bdaf1976e1748251eba2a89b147e89c2294a288`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.builtins.ListSerializer
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonClassDiscriminator
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import kotlinx.serialization.json.JsonTransformingSerializer

/** Downloaded recipe data only. It deliberately contains no host-issued authority. */
@Serializable
data class DeclarativeExtensionBundle(
    val manifest: ExtensionRecipeManifest,
    val recipe: ExtensionRecipe = ExtensionRecipe(emptyList()),
    val entrypoints: Map<String, RecipeV21Entrypoint> = emptyMap(),
)

@Serializable
data class ExtensionRecipeManifest(
    val formatVersion: RecipeFormatVersion,
    val id: String,
    val name: String,
    val declaredCapabilities: List<DeclaredRecipeCapability>,
    val declaredOrigins: List<DeclaredRecipeOrigin>,
)

/** A normalized HTTPS origin declaration, not a network grant. */
@Serializable
data class DeclaredRecipeOrigin(
    val id: String,
    val origin: String,
)

@Serializable
enum class RecipeFormatVersion {
    @SerialName("1")
    V1,

    @SerialName("2")
    V2,

    @SerialName("2.1")
    V21,
}

/** Declarations are requests; they are not host grants or network authority. */
@Serializable
enum class DeclaredRecipeCapability {
    @SerialName("networkRead")
    NetworkRead,

    @SerialName("documentExtraction")
    DocumentExtraction,
}

/** Legacy V1/V2 step list; catalog bundles still carry `"recipe": {"steps": []}` and validation rejects any steps. */
@Serializable
data class ExtensionRecipe(
    val steps: List<JsonElement>,
)

@Serializable
data class RecipeV21Entrypoint(
    val inputs: List<RecipeHostInput>,
    val url: RecipeV21Url,
    val projection: RecipeV21Projection,
    val terminal: RecipeV21Terminal,
)

@Serializable
enum class RecipeHostInput { @SerialName("pageIndex") PageIndex, @SerialName("pageOffset") PageOffset, @SerialName("query") Query, @SerialName("itemId") ItemId, @SerialName("episodeId") EpisodeId }

@Serializable
data class RecipeV21Url(val origin: DeclaredOriginReference, val path: List<RecipeV21UrlValue>, val query: Map<String, RecipeV21UrlValue> = emptyMap())

@Serializable
@OptIn(ExperimentalSerializationApi::class)
@JsonClassDiscriminator("value")
sealed interface RecipeV21UrlValue {
    @Serializable @SerialName("literal") data class Literal(val text: String) : RecipeV21UrlValue
    @Serializable @SerialName("hostInput") data class HostInput(val input: RecipeHostInput) : RecipeV21UrlValue
}

@Serializable
data class RecipeV21Projection(
    val pointer: String = "",
    val mode: RecipeV21ProjectionMode,
    /** Each field is one JSON Pointer or an ordered fallback list; the first pointer that yields a scalar wins. */
    val fields: Map<String, @Serializable(with = RecipeV21FieldPointersSerializer::class) List<String>>,
)

/** Accepts `"/a"` or `["/a", "/b"]`; always encodes the canonical form (a bare string for one pointer). */
internal object RecipeV21FieldPointersSerializer : JsonTransformingSerializer<List<String>>(ListSerializer(String.serializer())) {
    override fun transformDeserialize(element: JsonElement): JsonElement = if (element is JsonPrimitive) JsonArray(listOf(element)) else element
    override fun transformSerialize(element: JsonElement): JsonElement = (element as? JsonArray)?.singleOrNull() ?: element
}
@Serializable enum class RecipeV21ProjectionMode { @SerialName("one") One, @SerialName("many") Many }
@Serializable
data class RecipeV21Terminal(val type: RecipeV21TerminalType, val pageSize: Int? = null)
@Serializable enum class RecipeV21TerminalType { @SerialName("listing") Listing, @SerialName("detail") Detail, @SerialName("episodes") Episodes, @SerialName("media") Media }

@Serializable
data class DeclaredOriginReference(
    val originId: String,
)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeRecipeRuntime.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeRecipeRuntime.kt) · implementation · 224 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
14: enum class RecipeExecutionErrorCode {
19: data class RecipeExecutionError(val code: RecipeExecutionErrorCode)
21: sealed interface RecipeEntrypointInput {
22: data class PageIndex(val value: Int) : RecipeEntrypointInput
24: data class PageOffset(val value: Int) : RecipeEntrypointInput
25: data class Query(val value: String) : RecipeEntrypointInput
26: data class ItemId(val value: String) : RecipeEntrypointInput
27: data class EpisodeId(val value: String) : RecipeEntrypointInput
30: sealed interface RecipeEntrypointResult {
31: data class Listing(val items: List<Item>, val pageSize: Int) : RecipeEntrypointResult
32: data class Detail(val id: String, val title: String, val thumbnailUrl: String?, val description: String?) : RecipeEntrypointResult
33: data class Episodes(val items: List<Episode>) : RecipeEntrypointResult
34: data class Media(val items: List<MediaItem>) : RecipeEntrypointResult
35: data class Item(val id: String, val title: String, val thumbnailUrl: String?)
36: data class Episode(val id: String, val season: String?, val number: String?)
37: data class MediaItem(val url: String, val quality: String?)
40: sealed interface RecipeEntrypointExecutionResult {
41: data class Completed(val result: RecipeEntrypointResult) : RecipeEntrypointExecutionResult
42: data class Rejected(val error: RecipeExecutionError) : RecipeEntrypointExecutionResult
46: fun interface RecipeMonotonicClock {
47: fun nowMillis(): Long
50: private object DefaultRecipeMonotonicClock : RecipeMonotonicClock {
52: override fun nowMillis(): Long = start.elapsedNow().inWholeMilliseconds
56: class RecipeExecutionPolicy(
68: data class RecipeBrokerRequest(
79: sealed interface RecipeBrokerResult {
80: data class Document(val bytes: ByteArray) : RecipeBrokerResult
81: data object OriginDenied : RecipeBrokerResult
82: data object HttpFailure : RecipeBrokerResult
83: data object ResponseTooLarge : RecipeBrokerResult
84: data object Failed : RecipeBrokerResult
87: interface RecipeCapabilityBroker {
88: suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult
91: class DeclarativeRecipeRuntime(
95: suspend fun executeEntrypoint(bundle: DeclarativeExtensionBundle, entrypoint: String, hostInputs: Map<String, RecipeEntrypointInput>, policy: RecipeExecutionPolicy): RecipeEntrypointExecutionResult {
132: private fun validPolicy(policy: RecipeExecutionPolicy): Boolean =
141: private class InvocationDeadline(clock: RecipeMonotonicClock, durationMillis: Long) {
144: suspend fun isActive(): Boolean {
148: suspend fun remainingMillis(): Long {
154: private fun jsonPointerScalar(root: JsonElement, pointer: String): String? {
178: private fun decodePointerToken(raw: String): String? {
192: private fun inputMatches(expected: RecipeHostInput, value: RecipeEntrypointInput): Boolean = when (expected) {
199: 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 }
202: private fun pageOffsetInputs(entry: RecipeV21Entrypoint, inputs: Map<String, RecipeEntrypointInput>): Map<String, RecipeEntrypointInput> {
208: 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 == '_' }
209: 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]}" }
210: private fun jsonPointerElement(root: JsonElement, pointer: String): JsonElement? {
216: private fun resultLimit(type: RecipeV21TerminalType) = when (type) { RecipeV21TerminalType.Listing -> 30; RecipeV21TerminalType.Detail -> 1; RecipeV21TerminalType.Episodes -> 256; RecipeV21TerminalType.Media -> 16 }
217: private fun requiredFields(type: RecipeV21TerminalType) = when (type) { RecipeV21TerminalType.Media -> setOf("url"); RecipeV21TerminalType.Episodes -> setOf("id"); else -> setOf("id", "title") }
218: private fun mapTerminal(terminal: RecipeV21Terminal, rows: List<Map<String, String?>>): RecipeEntrypointExecutionResult.Completed? = when (terminal.type) {
224: private fun entryRejected(code: RecipeExecutionErrorCode) = RecipeEntrypointExecutionResult.Rejected(RecipeExecutionError(code))
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeRecipeRuntime.kt) · SHA-256 `0e8d217b2839bcdc47ffa1fc003fe0bb96cb9e4506a2ae2b0a50cf92aad6f091`.

### Complete file

```kotlin
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<Item>, 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<Episode>) : RecipeEntrypointResult
    data class Media(val items: List<MediaItem>) : 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<String, String>,
    val maxReceivedDocumentBytes: Int = 256 * 1024,
    val brokerDeadlineMillis: Long = 15_000,
) {
    val grantedOrigins: Map<String, String> = 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<String, RecipeEntrypointInput>, 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<String, RecipeEntrypointInput>): Map<String, RecipeEntrypointInput> {
    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<Map<String, String?>>): 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))
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.kt) · implementation · 28 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
5: class PlatformRecipeServices(
10: expect fun createPlatformRecipeServices(
16: internal fun unavailablePlatformRecipeServices(clock: RecipeInstallationClock): PlatformRecipeServices =
22: private object ClosedRecipeInstallationStore : RecipeInstallationStore {
23: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: eu.friedcutlet.yokan.services.extensions.recipe.CatalogTrustPolicy) = RecipeCatalogEnrollmentResult.Rejected
24: override suspend fun readCatalog(catalogId: String) = null
25: override suspend fun commitInstall(expectedGeneration: eu.friedcutlet.yokan.services.extensions.recipe.CatalogSnapshotGeneration, candidate: RecipeInstallCandidate) = RecipeInstallCommitResult.Rejected
28: private class RecipeTransportUnavailableException : IllegalStateException()
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.kt) · SHA-256 `89c9c3795ac1538123548e5f8136fe1ee78941efdb3ce4bd75d94a3f4c1c159b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.database.YokanDatabase
/** Platform-owned signed-recipe capabilities; a null runtime binding disables recipe execution. */
class PlatformRecipeServices(
    val installation: RecipeCatalogInstallationService,
    val runtimeBindings: RecipeRuntimeBindings?,
)

expect fun createPlatformRecipeServices(
    database: YokanDatabase,
    clock: RecipeInstallationClock,
): PlatformRecipeServices

/** Platforms without the isolated JVM transport reject all signed-recipe operations. */
internal fun unavailablePlatformRecipeServices(clock: RecipeInstallationClock): PlatformRecipeServices =
    PlatformRecipeServices(
        installation = RecipeCatalogInstallationService(ClosedRecipeInstallationStore, RecipeCatalogDownloader { _, _, _ -> throw RecipeTransportUnavailableException() }, clock),
        runtimeBindings = null,
    )

private object ClosedRecipeInstallationStore : RecipeInstallationStore {
    override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: eu.friedcutlet.yokan.services.extensions.recipe.CatalogTrustPolicy) = RecipeCatalogEnrollmentResult.Rejected
    override suspend fun readCatalog(catalogId: String) = null
    override suspend fun commitInstall(expectedGeneration: eu.friedcutlet.yokan.services.extensions.recipe.CatalogSnapshotGeneration, candidate: RecipeInstallCandidate) = RecipeInstallCommitResult.Rejected
}

private class RecipeTransportUnavailableException : IllegalStateException()
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeCatalogInstallationService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeCatalogInstallationService.kt) · implementation · 241 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: fun interface RecipeCatalogDownloader {
9: suspend fun download(url: String, maxBytes: Int, deadlineMillis: Long): ByteArray
12: fun interface RecipeCatalogMonotonicClock {
13: fun nowMillis(): Long
16: private object DefaultRecipeCatalogMonotonicClock : RecipeCatalogMonotonicClock {
18: override fun nowMillis(): Long = origin.elapsedNow().inWholeMilliseconds
21: data class RecipeCatalogInstallationPolicy(val invocationDeadlineMillis: Long = 15_000) {
27: enum class RecipeCatalogEnrollmentError { MismatchedTrust, StoreRejected, StoreFailure }
29: sealed interface RecipeCatalogEnrollmentServiceResult {
30: data object Created : RecipeCatalogEnrollmentServiceResult
31: data object AlreadyEnrolled : RecipeCatalogEnrollmentServiceResult
32: data class Rejected(val error: RecipeCatalogEnrollmentError) : RecipeCatalogEnrollmentServiceResult
35: enum class RecipeCatalogRefreshError { NotEnrolled, MismatchedTrust, StoreFailure, DeadlineExceeded, DownloadFailed, CatalogRejected, ArtifactPolicyRejected }
37: data class RecipeCatalogPreviewArtifact(
44: data class RecipeCatalogPreview(
51: sealed interface RecipeCatalogRefreshResult {
52: data class Available(val preview: RecipeCatalogPreview) : RecipeCatalogRefreshResult
53: data class Rejected(val error: RecipeCatalogRefreshError) : RecipeCatalogRefreshResult
56: enum class RecipeCatalogInstallError { NotEnrolled, MismatchedTrust, StoreFailure, DeadlineExceeded, DownloadFailed, CatalogRejected, ArtifactPolicyRejected, ArtifactUnavailable, ArtifactRejected, StoreRejected }
58: sealed interface RecipeCatalogInstallServiceResult {
59: data class Applied(val record: InstalledRecipeRecord) : RecipeCatalogInstallServiceResult
60: data class Unchanged(val record: InstalledRecipeRecord) : RecipeCatalogInstallServiceResult
61: data object Conflict : RecipeCatalogInstallServiceResult
62: data class Rejected(val error: RecipeCatalogInstallError) : RecipeCatalogInstallServiceResult
66: class RecipeCatalogInstallationService(
74: suspend fun enroll(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult =
77: suspend fun refresh(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult = refreshChecked(proposal).also { result ->
84: suspend fun install(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult = installChecked(proposal, stableId).also { result ->
93: private suspend fun enrollChecked(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult {
111: private suspend fun refreshChecked(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult = when (val prepared = prepare(proposal, InvocationDeadline(monotonicClock, policy.invocationDeadlineMillis))) {
123: private suspend fun installChecked(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult {
158: private suspend fun existingEnrollmentResult(proposal: CatalogEnrollmentCode, trust: CatalogTrustPolicy): RecipeCatalogEnrollmentServiceResult {
167: private suspend fun prepare(proposal: CatalogEnrollmentCode, deadline: InvocationDeadline): PreparedCatalog {
186: private suspend fun fetch(url: String, maxBytes: Int, deadline: InvocationDeadline): FetchResult {
194: private fun portableArtifact(metadata: RecipeArtifactMetadata, catalogUrl: String): Boolean = metadata.sizeBytes in 1..maxPortableArtifactBytes &&
197: private fun canonicalHttpsOrigin(url: String): String? {
209: private sealed interface PreparedCatalog {
210: data class Available(val envelope: ByteArray, val accepted: RecipeCatalogVerificationResult.Accepted, val expiresAtEpochSeconds: Long, val deadline: InvocationDeadline) : PreparedCatalog
211: data class Rejected(val error: RecipeCatalogRefreshError) : PreparedCatalog
214: private sealed interface FetchResult {
215: data class Available(val bytes: ByteArray) : FetchResult
216: data class Rejected(val error: RecipeCatalogRefreshError) : FetchResult
219: private class InvocationDeadline(private val clock: RecipeCatalogMonotonicClock, private val durationMillis: Long) {
221: fun remainingMillis(): Long = (durationMillis - (clock.nowMillis() - startedAtMillis)).coerceIn(0, durationMillis)
230: private fun RecipeCatalogRefreshError.toInstallError(): RecipeCatalogInstallError = when (this) {
240: private fun enrollmentRejected(error: RecipeCatalogEnrollmentError): RecipeCatalogEnrollmentServiceResult.Rejected = RecipeCatalogEnrollmentServiceResult.Rejected(error)
241: private fun installRejected(error: RecipeCatalogInstallError): RecipeCatalogInstallServiceResult.Rejected = RecipeCatalogInstallServiceResult.Rejected(error)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeCatalogInstallationService.kt) · SHA-256 `53e8c3deaf3eb2e3c5f6b9e055579f0487348201591b3521f3954c9b8f27fa10`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.services.logging.AppLogger
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlin.time.TimeSource

/** Narrow transport boundary. Native implementations own DNS, peers, redirects, and content encodings. */
fun interface RecipeCatalogDownloader {
    suspend fun download(url: String, maxBytes: Int, deadlineMillis: Long): ByteArray
}

fun interface RecipeCatalogMonotonicClock {
    fun nowMillis(): Long
}

private object DefaultRecipeCatalogMonotonicClock : RecipeCatalogMonotonicClock {
    private val origin = TimeSource.Monotonic.markNow()
    override fun nowMillis(): Long = origin.elapsedNow().inWholeMilliseconds
}

data class RecipeCatalogInstallationPolicy(val invocationDeadlineMillis: Long = 15_000) {
    init {
        require(invocationDeadlineMillis > 0)
    }
}

enum class RecipeCatalogEnrollmentError { MismatchedTrust, StoreRejected, StoreFailure }

sealed interface RecipeCatalogEnrollmentServiceResult {
    data object Created : RecipeCatalogEnrollmentServiceResult
    data object AlreadyEnrolled : RecipeCatalogEnrollmentServiceResult
    data class Rejected(val error: RecipeCatalogEnrollmentError) : RecipeCatalogEnrollmentServiceResult
}

enum class RecipeCatalogRefreshError { NotEnrolled, MismatchedTrust, StoreFailure, DeadlineExceeded, DownloadFailed, CatalogRejected, ArtifactPolicyRejected }

data class RecipeCatalogPreviewArtifact(
    val stableId: String,
    val releaseVersion: String,
    val sizeBytes: Long,
)

/** Bounded signed metadata only; URLs, envelope bytes, and payload bytes never escape. */
data class RecipeCatalogPreview(
    val catalogId: String,
    val revision: Long,
    val expiresAtEpochSeconds: Long,
    val artifacts: List<RecipeCatalogPreviewArtifact>,
)

sealed interface RecipeCatalogRefreshResult {
    data class Available(val preview: RecipeCatalogPreview) : RecipeCatalogRefreshResult
    data class Rejected(val error: RecipeCatalogRefreshError) : RecipeCatalogRefreshResult
}

enum class RecipeCatalogInstallError { NotEnrolled, MismatchedTrust, StoreFailure, DeadlineExceeded, DownloadFailed, CatalogRejected, ArtifactPolicyRejected, ArtifactUnavailable, ArtifactRejected, StoreRejected }

sealed interface RecipeCatalogInstallServiceResult {
    data class Applied(val record: InstalledRecipeRecord) : RecipeCatalogInstallServiceResult
    data class Unchanged(val record: InstalledRecipeRecord) : RecipeCatalogInstallServiceResult
    data object Conflict : RecipeCatalogInstallServiceResult
    data class Rejected(val error: RecipeCatalogInstallError) : RecipeCatalogInstallServiceResult
}

/** Explicit enrollment, preview, and install orchestration. It never auto-parses or auto-enrolls. */
class RecipeCatalogInstallationService(
    private val store: RecipeInstallationStore,
    private val downloader: RecipeCatalogDownloader,
    private val clock: RecipeInstallationClock,
    private val monotonicClock: RecipeCatalogMonotonicClock = DefaultRecipeCatalogMonotonicClock,
    private val policy: RecipeCatalogInstallationPolicy = RecipeCatalogInstallationPolicy(),
    private val coordinator: RecipeInstallationCoordinator = RecipeInstallationCoordinator(store),
) {
    suspend fun enroll(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult =
        enrollChecked(proposal).also { AppLogger.info("[recipe] catalog ${proposal.catalogId} enroll: $it") }

    suspend fun refresh(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult = refreshChecked(proposal).also { result ->
        when (result) {
            is RecipeCatalogRefreshResult.Available -> AppLogger.info("[recipe] catalog ${proposal.catalogId} refresh: revision ${result.preview.revision}, ${result.preview.artifacts.size} recipes")
            is RecipeCatalogRefreshResult.Rejected -> AppLogger.warn("[recipe] catalog ${proposal.catalogId} refresh rejected: ${result.error}")
        }
    }

    suspend fun install(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult = installChecked(proposal, stableId).also { result ->
        when (result) {
            is RecipeCatalogInstallServiceResult.Applied -> AppLogger.info("[recipe] ${proposal.catalogId}/$stableId installed ${result.record.releaseVersion}")
            is RecipeCatalogInstallServiceResult.Unchanged -> AppLogger.info("[recipe] ${proposal.catalogId}/$stableId already installed ${result.record.releaseVersion}")
            RecipeCatalogInstallServiceResult.Conflict -> AppLogger.warn("[recipe] ${proposal.catalogId}/$stableId install conflicted with a concurrent change")
            is RecipeCatalogInstallServiceResult.Rejected -> AppLogger.warn("[recipe] ${proposal.catalogId}/$stableId install rejected: ${result.error}")
        }
    }

    private suspend fun enrollChecked(proposal: CatalogEnrollmentCode): RecipeCatalogEnrollmentServiceResult {
        val trust = proposal.trustPolicy()
        val existing = catchingNonCancellation { store.readCatalog(proposal.catalogId) }.getOrElse { return enrollmentRejected(RecipeCatalogEnrollmentError.StoreFailure) }
        if (existing != null) return if (existing.catalogId == proposal.catalogId && sameTrustPolicy(existing.trustPolicy, trust)) {
            RecipeCatalogEnrollmentServiceResult.AlreadyEnrolled
        } else {
            enrollmentRejected(RecipeCatalogEnrollmentError.MismatchedTrust)
        }
        return catchingNonCancellation {
            when (store.enrollIfAbsent(proposal.catalogId, trust)) {
                RecipeCatalogEnrollmentResult.Created -> RecipeCatalogEnrollmentServiceResult.Created
                RecipeCatalogEnrollmentResult.Rejected -> enrollmentRejected(RecipeCatalogEnrollmentError.StoreRejected)
                RecipeCatalogEnrollmentResult.StoreFailure -> enrollmentRejected(RecipeCatalogEnrollmentError.StoreFailure)
                RecipeCatalogEnrollmentResult.AlreadyExists -> existingEnrollmentResult(proposal, trust)
            }
        }.getOrElse { enrollmentRejected(RecipeCatalogEnrollmentError.StoreFailure) }
    }

    private suspend fun refreshChecked(proposal: CatalogEnrollmentCode): RecipeCatalogRefreshResult = when (val prepared = prepare(proposal, InvocationDeadline(monotonicClock, policy.invocationDeadlineMillis))) {
        is PreparedCatalog.Available -> RecipeCatalogRefreshResult.Available(
            RecipeCatalogPreview(
                proposal.catalogId,
                prepared.accepted.acceptanceState.highestRevision,
                prepared.expiresAtEpochSeconds,
                prepared.accepted.catalog.artifacts.map { RecipeCatalogPreviewArtifact(it.stableId, it.releaseVersion, it.sizeBytes) },
            ),
        )
        is PreparedCatalog.Rejected -> RecipeCatalogRefreshResult.Rejected(prepared.error)
    }

    private suspend fun installChecked(proposal: CatalogEnrollmentCode, stableId: String): RecipeCatalogInstallServiceResult {
        val prepared = prepare(proposal, InvocationDeadline(monotonicClock, policy.invocationDeadlineMillis))
        if (prepared is PreparedCatalog.Rejected) return installRejected(prepared.error.toInstallError())
        prepared as PreparedCatalog.Available
        val metadata = prepared.accepted.catalog.artifacts.firstOrNull { it.stableId == stableId }
            ?: return installRejected(RecipeCatalogInstallError.ArtifactUnavailable)
        val artifact = when (val fetched = fetch(metadata.url, metadata.sizeBytes.toInt(), prepared.deadline)) {
            is FetchResult.Available -> fetched.bytes
            is FetchResult.Rejected -> return installRejected(fetched.error.toInstallError())
        }
        val result = catchingNonCancellation {
            coordinator.install(
                proposal.catalogId,
                prepared.envelope,
                artifact,
                stableId,
                clock.nowEpochSeconds(),
                proposal.trustPolicy(),
            )
        }.getOrElse { return installRejected(RecipeCatalogInstallError.StoreFailure) }
        return when (result) {
            is RecipeInstallationResult.Applied -> RecipeCatalogInstallServiceResult.Applied(result.record)
            is RecipeInstallationResult.Unchanged -> RecipeCatalogInstallServiceResult.Unchanged(result.record)
            RecipeInstallationResult.Conflict -> RecipeCatalogInstallServiceResult.Conflict
            is RecipeInstallationResult.Rejected -> installRejected(
                when (result.code) {
                    RecipeInstallationErrorCode.StoreFailure -> RecipeCatalogInstallError.StoreFailure
                    RecipeInstallationErrorCode.StoreRejected -> RecipeCatalogInstallError.StoreRejected
                    RecipeInstallationErrorCode.UnknownCatalog, RecipeInstallationErrorCode.CatalogVerificationFailed -> RecipeCatalogInstallError.CatalogRejected
                    RecipeInstallationErrorCode.ArtifactVerificationFailed, RecipeInstallationErrorCode.RecipeDecodeFailed, RecipeInstallationErrorCode.ArtifactIdentityMismatch -> RecipeCatalogInstallError.ArtifactRejected
                },
            )
        }
    }

    private suspend fun existingEnrollmentResult(proposal: CatalogEnrollmentCode, trust: CatalogTrustPolicy): RecipeCatalogEnrollmentServiceResult {
        val existing = catchingNonCancellation { store.readCatalog(proposal.catalogId) }.getOrElse { return enrollmentRejected(RecipeCatalogEnrollmentError.StoreFailure) }
        return if (existing != null && existing.catalogId == proposal.catalogId && sameTrustPolicy(existing.trustPolicy, trust)) {
            RecipeCatalogEnrollmentServiceResult.AlreadyEnrolled
        } else {
            enrollmentRejected(RecipeCatalogEnrollmentError.MismatchedTrust)
        }
    }

    private suspend fun prepare(proposal: CatalogEnrollmentCode, deadline: InvocationDeadline): PreparedCatalog {
        val snapshot = catchingNonCancellation { store.readCatalog(proposal.catalogId) }.getOrElse { return PreparedCatalog.Rejected(RecipeCatalogRefreshError.StoreFailure) } ?: return PreparedCatalog.Rejected(RecipeCatalogRefreshError.NotEnrolled)
        if (snapshot.catalogId != proposal.catalogId || !sameTrustPolicy(snapshot.trustPolicy, proposal.trustPolicy())) {
            return PreparedCatalog.Rejected(RecipeCatalogRefreshError.MismatchedTrust)
        }
        val envelope = when (val fetched = fetch(proposal.catalogEnvelopeUrl, RecipeCatalogLimits.maxEnvelopeBytes, deadline)) {
            is FetchResult.Available -> fetched.bytes
            is FetchResult.Rejected -> return PreparedCatalog.Rejected(fetched.error)
        }
        val accepted = VerifiedRecipeCatalogVerifier.verify(envelope, snapshot.trustPolicy, snapshot.acceptanceState, clock.nowEpochSeconds())
            as? RecipeCatalogVerificationResult.Accepted ?: return PreparedCatalog.Rejected(RecipeCatalogRefreshError.CatalogRejected)
        val parsed = RecipeCatalogEnvelopeWire.parse(envelope, RecipeCatalogLimits.maxEnvelopeBytes, RecipeCatalogLimits.maxPayloadBytes, RecipeCatalogLimits.maxKeyIdBytes) as? RecipeCatalogEnvelopeParseResult.Parsed
            ?: return PreparedCatalog.Rejected(RecipeCatalogRefreshError.CatalogRejected)
        if (accepted.catalog.artifacts.any { !portableArtifact(it, proposal.catalogEnvelopeUrl) }) {
            return PreparedCatalog.Rejected(RecipeCatalogRefreshError.ArtifactPolicyRejected)
        }
        return PreparedCatalog.Available(envelope, accepted, parsed.envelope.expiresAtEpochSeconds, deadline)
    }

    private suspend fun fetch(url: String, maxBytes: Int, deadline: InvocationDeadline): FetchResult {
        val remaining = deadline.remainingMillis()
        if (remaining <= 0) return FetchResult.Rejected(RecipeCatalogRefreshError.DeadlineExceeded)
        val bytes = catchingNonCancellation { downloader.download(url, maxBytes, remaining) }.getOrElse { return FetchResult.Rejected(RecipeCatalogRefreshError.DownloadFailed) }
        if (deadline.remainingMillis() <= 0) return FetchResult.Rejected(RecipeCatalogRefreshError.DeadlineExceeded)
        return if (bytes.size <= maxBytes) FetchResult.Available(bytes.copyOf()) else FetchResult.Rejected(RecipeCatalogRefreshError.DownloadFailed)
    }

    private fun portableArtifact(metadata: RecipeArtifactMetadata, catalogUrl: String): Boolean = metadata.sizeBytes in 1..maxPortableArtifactBytes &&
        canonicalHttpsOrigin(metadata.url) == canonicalHttpsOrigin(catalogUrl)

    private fun canonicalHttpsOrigin(url: String): String? {
        if (url.length !in 9..maxUrlCharacters || url.any { it.code !in 0x21..0x7e || it == '\\' || it == '?' || it == '#' }) return null
        val origin = loopbackCatalogOrigin(url) ?: run {
            if (!url.startsWith("https://")) return null
            val authorityEnd = url.indexOf('/', 8).takeIf { it >= 0 } ?: return null
            val host = url.substring(8, authorityEnd)
            if (!RecipeSyntax.isHost(host)) return null
            "https://$host"
        }
        return origin.takeIf { RecipeSyntax.isCanonicalPath(url.substring(it.length)) }
    }

    private sealed interface PreparedCatalog {
        data class Available(val envelope: ByteArray, val accepted: RecipeCatalogVerificationResult.Accepted, val expiresAtEpochSeconds: Long, val deadline: InvocationDeadline) : PreparedCatalog
        data class Rejected(val error: RecipeCatalogRefreshError) : PreparedCatalog
    }

    private sealed interface FetchResult {
        data class Available(val bytes: ByteArray) : FetchResult
        data class Rejected(val error: RecipeCatalogRefreshError) : FetchResult
    }

    private class InvocationDeadline(private val clock: RecipeCatalogMonotonicClock, private val durationMillis: Long) {
        private val startedAtMillis = clock.nowMillis()
        fun remainingMillis(): Long = (durationMillis - (clock.nowMillis() - startedAtMillis)).coerceIn(0, durationMillis)
    }

    private companion object {
        const val maxPortableArtifactBytes = 64L * 1024
        const val maxUrlCharacters = 2_048
    }
}

private fun RecipeCatalogRefreshError.toInstallError(): RecipeCatalogInstallError = when (this) {
    RecipeCatalogRefreshError.NotEnrolled -> RecipeCatalogInstallError.NotEnrolled
    RecipeCatalogRefreshError.MismatchedTrust -> RecipeCatalogInstallError.MismatchedTrust
    RecipeCatalogRefreshError.StoreFailure -> RecipeCatalogInstallError.StoreFailure
    RecipeCatalogRefreshError.DeadlineExceeded -> RecipeCatalogInstallError.DeadlineExceeded
    RecipeCatalogRefreshError.DownloadFailed -> RecipeCatalogInstallError.DownloadFailed
    RecipeCatalogRefreshError.CatalogRejected -> RecipeCatalogInstallError.CatalogRejected
    RecipeCatalogRefreshError.ArtifactPolicyRejected -> RecipeCatalogInstallError.ArtifactPolicyRejected
}

private fun enrollmentRejected(error: RecipeCatalogEnrollmentError): RecipeCatalogEnrollmentServiceResult.Rejected = RecipeCatalogEnrollmentServiceResult.Rejected(error)
private fun installRejected(error: RecipeCatalogInstallError): RecipeCatalogInstallServiceResult.Rejected = RecipeCatalogInstallServiceResult.Rejected(error)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeExtensionRuntimeService.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeExtensionRuntimeService.kt) · implementation · 80 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
15: class RecipeRuntimeBindings(
22: fun interface VerifiedRecipeBundleResolver {
23: suspend fun resolve(catalogId: String, stableId: String): DeclarativeExtensionBundle?
27: class RecipeExtensionRuntimeService(
36: override suspend fun supportsLatest(): Boolean = bundle()?.entrypoints?.containsKey("latest") == true
38: override suspend fun popular(page: Int): SourceListing = listing("popular", page, null)
39: override suspend fun latest(page: Int): SourceListing = listing("latest", page, null)
40: override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
43: override suspend fun detail(url: String): RemoteDetail {
56: private suspend fun listing(entrypoint: String, page: Int, query: String?): SourceListing {
66: private suspend fun execute(
77: private suspend fun bundle(): DeclarativeExtensionBundle? = resolver.resolve(catalogId, stableId)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeExtensionRuntimeService.kt) · SHA-256 `68619d236f97ffd39bdcf4e1da141d3e4b7e810eab6a328c4944bd60ae78e2ea`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.services.extensions.ExtensionRuntimeService
import eu.friedcutlet.yokan.services.extensions.RemoteChapter
import eu.friedcutlet.yokan.services.extensions.RemoteDetail
import eu.friedcutlet.yokan.services.extensions.RemoteManga
import eu.friedcutlet.yokan.services.extensions.SourceFilter
import eu.friedcutlet.yokan.services.extensions.SourceListing
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import eu.friedcutlet.yokan.services.logging.AppLogger

/** Explicit host capabilities for signed recipes; omitted bindings deliberately disable recipe sources. */
class RecipeRuntimeBindings(
    val resolver: VerifiedRecipeBundleResolver,
    val broker: RecipeCapabilityBroker,
    val policy: RecipeExecutionPolicy,
)

/** Host-owned resolver; it returns only an identity-bound, already verified recipe bundle. */
fun interface VerifiedRecipeBundleResolver {
    suspend fun resolve(catalogId: String, stableId: String): DeclarativeExtensionBundle?
}

/** Runtime for installed signed recipes, registered by `ExtensionRuntimeFactory`. It never reads [DbSource.sourceCode]. */
class RecipeExtensionRuntimeService(
    override val source: DbSource,
    private val catalogId: String,
    private val stableId: String,
    private val resolver: VerifiedRecipeBundleResolver,
    broker: RecipeCapabilityBroker,
    private val policy: RecipeExecutionPolicy,
) : ExtensionRuntimeService {
    private val runtime = DeclarativeRecipeRuntime(broker)
    override suspend fun supportsLatest(): Boolean = bundle()?.entrypoints?.containsKey("latest") == true

    override suspend fun popular(page: Int): SourceListing = listing("popular", page, null)
    override suspend fun latest(page: Int): SourceListing = listing("latest", page, null)
    override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing =
        if (filters.isNotEmpty()) SourceListing(emptyList(), false) else listing("search", page, query)

    override suspend fun detail(url: String): RemoteDetail {
        val bundle = bundle() ?: return RemoteDetail("", url)
        val detail = execute(bundle, "detail", mapOf("itemId" to RecipeEntrypointInput.ItemId(url))) as? RecipeEntrypointExecutionResult.Completed
            ?: return RemoteDetail("", url)
        val details = detail.result as? RecipeEntrypointResult.Detail ?: return RemoteDetail("", url)
        val episodes = execute(bundle, "episodes", mapOf("itemId" to RecipeEntrypointInput.ItemId(url))) as? RecipeEntrypointExecutionResult.Completed
            ?: return RemoteDetail("", url)
        val episodeResult = episodes.result as? RecipeEntrypointResult.Episodes ?: return RemoteDetail("", url)
        val chapters = episodeResult.items.map { RemoteChapter(it.number ?: it.id, it.id, scanlator = it.season.orEmpty()) }
            .ifEmpty { listOf(RemoteChapter(details.title, url)) }
        return RemoteDetail(details.title, details.id, details.description.orEmpty(), thumbnailUrl = details.thumbnailUrl, chapters = chapters)
    }

    private suspend fun listing(entrypoint: String, page: Int, query: String?): SourceListing {
        if (page !in 1..1000 || (query != null && (query.length > 256 || query.any { it.code < 0x20 }))) return SourceListing(emptyList(), false)
        val inputs = buildMap<String, RecipeEntrypointInput> { put("pageIndex", RecipeEntrypointInput.PageIndex(page - 1)); if (query != null) put("query", RecipeEntrypointInput.Query(query)) }
        val bundle = bundle() ?: return SourceListing(emptyList(), false)
        val completed = execute(bundle, entrypoint, inputs) as? RecipeEntrypointExecutionResult.Completed ?: return SourceListing(emptyList(), false)
        val listing = completed.result as? RecipeEntrypointResult.Listing ?: return SourceListing(emptyList(), false)
        return SourceListing(listing.items.map { RemoteManga(it.title, it.id, it.thumbnailUrl) }, listing.items.size == listing.pageSize)
    }

    // Bundle validation and JSON projection are CPU work; keep them off the caller's (often Main) thread.
    private suspend fun execute(
        bundle: DeclarativeExtensionBundle,
        entrypoint: String,
        inputs: Map<String, RecipeEntrypointInput>,
    ): RecipeEntrypointExecutionResult = withContext(Dispatchers.Default) {
        runtime.executeEntrypoint(bundle, entrypoint, inputs, policy)
    }.also { result ->
        // Closed error codes only: recipe runtimes never surface URLs or response bodies.
        if (result is RecipeEntrypointExecutionResult.Rejected) AppLogger.warn("[recipe] $catalogId/$stableId $entrypoint rejected: ${result.error.code}")
    }

    private suspend fun bundle(): DeclarativeExtensionBundle? = resolver.resolve(catalogId, stableId)
        ?.takeIf { it.manifest.formatVersion == RecipeFormatVersion.V21 && it.manifest.id == stableId }
        .also { if (it == null) AppLogger.warn("[recipe] $catalogId/$stableId has no valid installed bundle") }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeInstallationCoordinator.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeInstallationCoordinator.kt) · implementation · 419 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
8: class CatalogSnapshotGeneration internal constructor(internal val value: Long)
11: fun interface RecipeInstallationClock {
12: fun nowEpochSeconds(): Long
16: class InstalledRecipeRecord(
30: internal fun copyOwned(): InstalledRecipeRecord = InstalledRecipeRecord(
36: data class RecipeSourceReference(val catalogId: String, val stableId: String)
40: internal fun recipeSourceId(catalogId: String, stableId: String): Long {
48: internal fun recipeSourceReference(catalogId: String, stableId: String): String =
51: internal fun parseRecipeSourceReference(value: String): RecipeSourceReference? {
61: class CatalogInstallationSnapshot(
76: internal fun copyOwned(): CatalogInstallationSnapshot = CatalogInstallationSnapshot(
81: sealed interface RecipeInstallCommitResult {
82: data object Applied : RecipeInstallCommitResult
83: data object Unchanged : RecipeInstallCommitResult
84: data object Conflict : RecipeInstallCommitResult
85: data object Rejected : RecipeInstallCommitResult
88: sealed interface RecipeCatalogEnrollmentResult {
89: data object Created : RecipeCatalogEnrollmentResult
90: data object AlreadyExists : RecipeCatalogEnrollmentResult
91: data object Rejected : RecipeCatalogEnrollmentResult
92: data object StoreFailure : RecipeCatalogEnrollmentResult
96: data class RecipeInstallationStoreLimits(
107: interface RecipeInstallationStore {
109: suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult
111: suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot?
116: suspend fun commitInstall(
123: class RecipeInstallCandidate internal constructor(
140: enum class RecipeInstallationErrorCode {
150: sealed interface RecipeInstallationResult {
151: data class Applied(val record: InstalledRecipeRecord) : RecipeInstallationResult
152: data class Unchanged(val record: InstalledRecipeRecord) : RecipeInstallationResult
153: data object Conflict : RecipeInstallationResult
154: data class Rejected(val code: RecipeInstallationErrorCode) : RecipeInstallationResult
157: class RecipeInstallationCoordinator(private val store: RecipeInstallationStore) {
158: suspend fun install(
225: class InstalledRecipeBundleResolver(
228: override suspend fun resolve(catalogId: String, stableId: String): DeclarativeExtensionBundle? {
241: class InMemoryRecipeInstallationStore(
252: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult {
264: override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = mutex.withLock {
268: override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = mutex.withLock {
285: suspend fun uninstall(catalogId: String, stableId: String): Boolean = mutex.withLock {
292: suspend fun replaceTrustPolicy(catalogId: String, trustPolicy: CatalogTrustPolicy): Boolean {
303: suspend fun failNextCommit() = mutex.withLock { failNextCommit = true }
305: private fun validEnrollment(catalogId: String, trustPolicy: CatalogTrustPolicy): Boolean {
309: private class StoredCatalog(
318: fun advanceGeneration(): Boolean {
323: fun snapshot(catalogId: String): CatalogInstallationSnapshot = CatalogInstallationSnapshot(
329: private fun CatalogTrustPolicy.copyOwned(): CatalogTrustPolicy = CatalogTrustPolicy(
336: private fun CatalogAcceptanceState.copyOwned(): CatalogAcceptanceState = CatalogAcceptanceState(catalogId, highestRevision, payloadHash)
338: internal fun decideRecipeInstallationCommit(
367: internal fun fitsRecipeInstallationArtifactQuota(
381: internal fun sameTrustPolicy(left: CatalogTrustPolicy, right: CatalogTrustPolicy): Boolean =
387: internal fun sameAcceptance(left: CatalogAcceptanceState?, right: CatalogAcceptanceState?): Boolean =
390: internal fun sameRecord(left: InstalledRecipeRecord, right: InstalledRecipeRecord): Boolean =
394: private fun rejected(code: RecipeInstallationErrorCode): RecipeInstallationResult.Rejected = RecipeInstallationResult.Rejected(code)
396: internal fun validRecipeInstallationTrustPolicy(
411: internal fun validRecipeInstallationCatalogId(value: String): Boolean = validRecipeInstallationIdentifier(value, 64)
412: internal fun validRecipeInstallationKeyId(value: String): Boolean = validRecipeInstallationIdentifier(value, 64)
413: internal fun validRecipeInstallationArtifactRecord(record: InstalledRecipeRecord): Boolean =
418: internal fun validRecipeInstallationReleaseVersion(value: String): Boolean = validRecipeInstallationIdentifier(value, 80, allowPlus = true)
419: private fun validRecipeInstallationIdentifier(value: String, maxLength: Int, allowPlus: Boolean = false): Boolean = RecipeSyntax.isIdentifier(value, maxLength, allowPlus)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeInstallationCoordinator.kt) · SHA-256 `f06c3557156b40c8649ab3e0391134268117231f839b80d869bfd357716bea81`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

/** Opaque, host-owned compare-and-set generation. */
class CatalogSnapshotGeneration internal constructor(internal val value: Long)

/** Host-owned time source, sampled by the store only after its catalog serialization boundary. */
fun interface RecipeInstallationClock {
    fun nowEpochSeconds(): Long
}

/** Immutable installation payload; it deliberately contains no execution authority or legacy metadata. */
class InstalledRecipeRecord(
    val catalogId: String,
    val stableId: String,
    val catalogRevision: Long,
    val releaseVersion: String,
    val sha256: String,
    val sizeBytes: Long,
    artifactBytes: ByteArray,
    /** Stable host source identity for this catalog/stable-id pair. */
    val sourceId: Long = recipeSourceId(catalogId, stableId),
) {
    private val ownedArtifactBytes = artifactBytes.copyOf()
    val artifactBytes: ByteArray get() = ownedArtifactBytes.copyOf()

    internal fun copyOwned(): InstalledRecipeRecord = InstalledRecipeRecord(
        catalogId, stableId, catalogRevision, releaseVersion, sha256, sizeBytes, ownedArtifactBytes, sourceId,
    )
}

/** Compact persisted payload in [eu.friedcutlet.yokan.database.DbSource.additionalParams]. */
data class RecipeSourceReference(val catalogId: String, val stableId: String)

internal const val RecipeSourceDiscriminator = "Recipe"

internal fun recipeSourceId(catalogId: String, stableId: String): Long {
    var hash = -0x340d631b8c46753bL // FNV-1a offset basis; source IDs remain negative and host-owned.
    for (byte in "$catalogId\u0000$stableId".encodeToByteArray()) {
        hash = (hash xor (byte.toLong() and 0xffL)) * 0x100000001b3L
    }
    return -(hash and Long.MAX_VALUE).coerceAtLeast(1L)
}

internal fun recipeSourceReference(catalogId: String, stableId: String): String =
    "recipe:v1:$catalogId:$stableId"

internal fun parseRecipeSourceReference(value: String): RecipeSourceReference? {
    val parts = value.split(':')
    if (parts.size != 4 || parts[0] != "recipe" || parts[1] != "v1") return null
    val (catalogId, stableId) = parts[2] to parts[3]
    return RecipeSourceReference(catalogId, stableId).takeIf {
        validRecipeInstallationCatalogId(catalogId) && validRecipeInstallationIdentifier(stableId, 80)
    }
}

/** A catalog-scoped host snapshot. Trust, replay state, and all artifact bytes are copied on every boundary. */
class CatalogInstallationSnapshot(
    val catalogId: String,
    val generation: CatalogSnapshotGeneration,
    trustPolicy: CatalogTrustPolicy,
    acceptanceState: CatalogAcceptanceState?,
    installedRecords: Map<String, InstalledRecipeRecord>,
) {
    private val ownedTrustPolicy = trustPolicy.copyOwned()
    private val ownedAcceptanceState = acceptanceState?.copyOwned()
    private val ownedInstalledRecords = installedRecords.mapValues { (_, record) -> record.copyOwned() }

    val trustPolicy: CatalogTrustPolicy get() = ownedTrustPolicy.copyOwned()
    val acceptanceState: CatalogAcceptanceState? get() = ownedAcceptanceState?.copyOwned()
    val installedRecords: Map<String, InstalledRecipeRecord> get() = ownedInstalledRecords.mapValues { (_, record) -> record.copyOwned() }

    internal fun copyOwned(): CatalogInstallationSnapshot = CatalogInstallationSnapshot(
        catalogId, CatalogSnapshotGeneration(generation.value), ownedTrustPolicy, ownedAcceptanceState, ownedInstalledRecords,
    )
}

sealed interface RecipeInstallCommitResult {
    data object Applied : RecipeInstallCommitResult
    data object Unchanged : RecipeInstallCommitResult
    data object Conflict : RecipeInstallCommitResult
    data object Rejected : RecipeInstallCommitResult
}

sealed interface RecipeCatalogEnrollmentResult {
    data object Created : RecipeCatalogEnrollmentResult
    data object AlreadyExists : RecipeCatalogEnrollmentResult
    data object Rejected : RecipeCatalogEnrollmentResult
    data object StoreFailure : RecipeCatalogEnrollmentResult
}

/** Host-owned capacity limits for a store instance. */
data class RecipeInstallationStoreLimits(
    val maxEnrolledCatalogs: Int = 64,
    val maxKeysPerCatalog: Int = 8,
    val maxInstalledRecipesPerCatalog: Int = 64,
    val maxArtifactBytesPerCatalog: Long = 32L * 1024 * 1024,
) {
    init {
        require(maxEnrolledCatalogs > 0 && maxKeysPerCatalog > 0 && maxInstalledRecipesPerCatalog > 0 && maxArtifactBytesPerCatalog > 0)
    }
}

interface RecipeInstallationStore {
    /** Creates host-supplied trust once. Downloaded catalog data must never call this API. */
    suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult
    /** Returns null only when the catalog is definitely absent; malformed/unreadable persistence must fail. */
    suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot?
    /**
     * The successful commit linearizes at the store's atomic decision. Cancellation before a result is returned
     * must not cause the coordinator to publish a result; implementations must expose only that linearized state.
     */
    suspend fun commitInstall(
        expectedGeneration: CatalogSnapshotGeneration,
        candidate: RecipeInstallCandidate,
    ): RecipeInstallCommitResult
}

/** Internal verified write intent. Callers cannot manufacture one from downloaded data. */
class RecipeInstallCandidate internal constructor(
    val catalogId: String,
    expectedTrustPolicy: CatalogTrustPolicy,
    expectedAcceptanceState: CatalogAcceptanceState?,
    acceptedAcceptanceState: CatalogAcceptanceState,
    val expiresAtEpochSeconds: Long,
    internal val signingKeyId: String,
    internal val signingKeyValidFromEpochSeconds: Long?,
    internal val signingKeyValidUntilEpochSeconds: Long?,
    record: InstalledRecipeRecord,
) {
    internal val expectedTrustPolicy = expectedTrustPolicy.copyOwned()
    internal val expectedAcceptanceState = expectedAcceptanceState?.copyOwned()
    internal val acceptedAcceptanceState = acceptedAcceptanceState.copyOwned()
    internal val record = record.copyOwned()
}

enum class RecipeInstallationErrorCode {
    UnknownCatalog,
    CatalogVerificationFailed,
    ArtifactVerificationFailed,
    RecipeDecodeFailed,
    ArtifactIdentityMismatch,
    StoreRejected,
    StoreFailure,
}

sealed interface RecipeInstallationResult {
    data class Applied(val record: InstalledRecipeRecord) : RecipeInstallationResult
    data class Unchanged(val record: InstalledRecipeRecord) : RecipeInstallationResult
    data object Conflict : RecipeInstallationResult
    data class Rejected(val code: RecipeInstallationErrorCode) : RecipeInstallationResult
}

class RecipeInstallationCoordinator(private val store: RecipeInstallationStore) {
    suspend fun install(
        catalogId: String,
        envelopeBytes: ByteArray,
        artifactBytes: ByteArray,
        stableArtifactId: String,
        nowEpochSeconds: Long,
        requiredTrustPolicy: CatalogTrustPolicy? = null,
    ): RecipeInstallationResult {
        val ownedEnvelope = envelopeBytes.copyOf()
        val ownedArtifact = artifactBytes.copyOf()
        val snapshot = catchingNonCancellation { store.readCatalog(catalogId) }.getOrElse { return rejected(RecipeInstallationErrorCode.StoreFailure) } ?: return rejected(RecipeInstallationErrorCode.UnknownCatalog)
        if (snapshot.catalogId != catalogId) return rejected(RecipeInstallationErrorCode.StoreFailure)
        if (requiredTrustPolicy != null && !sameTrustPolicy(snapshot.trustPolicy, requiredTrustPolicy)) {
            return rejected(RecipeInstallationErrorCode.CatalogVerificationFailed)
        }

        val verified = VerifiedRecipeCatalogVerifier.verify(
            ownedEnvelope,
            snapshot.trustPolicy,
            snapshot.acceptanceState,
            nowEpochSeconds,
        ) as? RecipeCatalogVerificationResult.Accepted ?: return rejected(RecipeInstallationErrorCode.CatalogVerificationFailed)
        val metadata = verified.catalog.artifacts.firstOrNull { it.stableId == stableArtifactId }
            ?: return rejected(RecipeInstallationErrorCode.ArtifactVerificationFailed)
        if (VerifiedRecipeCatalogVerifier.artifactEligibility(metadata, ownedArtifact) !is RecipeArtifactEligibility.Eligible) {
            return rejected(RecipeInstallationErrorCode.ArtifactVerificationFailed)
        }
        val bundle = (StrictRecipeBundleDecoder.decode(ownedArtifact) as? RecipeBundleDecodeResult.Accepted)?.bundle
            ?: return rejected(RecipeInstallationErrorCode.RecipeDecodeFailed)
        if (bundle.manifest.id != stableArtifactId) return rejected(RecipeInstallationErrorCode.ArtifactIdentityMismatch)
        val parsedEnvelope = (RecipeCatalogEnvelopeWire.parse(ownedEnvelope, RecipeCatalogLimits.maxEnvelopeBytes, RecipeCatalogLimits.maxPayloadBytes, RecipeCatalogLimits.maxKeyIdBytes) as? RecipeCatalogEnvelopeParseResult.Parsed)
            ?.envelope ?: return rejected(RecipeInstallationErrorCode.CatalogVerificationFailed)
        val signingKey = snapshot.trustPolicy.trustedKeys.singleOrNull { it.keyId == parsedEnvelope.keyId }
            ?: return rejected(RecipeInstallationErrorCode.CatalogVerificationFailed)

        val record = InstalledRecipeRecord(
            catalogId = catalogId,
            stableId = stableArtifactId,
            catalogRevision = verified.acceptanceState.highestRevision,
            releaseVersion = metadata.releaseVersion,
            sha256 = metadata.sha256,
            sizeBytes = metadata.sizeBytes,
            artifactBytes = ownedArtifact,
            sourceId = recipeSourceId(catalogId, stableArtifactId),
        )
        val candidate = RecipeInstallCandidate(
            catalogId = catalogId,
            expectedTrustPolicy = snapshot.trustPolicy,
            expectedAcceptanceState = snapshot.acceptanceState,
            acceptedAcceptanceState = verified.acceptanceState,
            expiresAtEpochSeconds = parsedEnvelope.expiresAtEpochSeconds,
            signingKeyId = signingKey.keyId,
            signingKeyValidFromEpochSeconds = signingKey.validFromEpochSeconds,
            signingKeyValidUntilEpochSeconds = signingKey.validUntilEpochSeconds,
            record = record,
        )
        val committed = catchingNonCancellation { store.commitInstall(snapshot.generation, candidate) }.getOrElse { return rejected(RecipeInstallationErrorCode.StoreFailure) }
        return when (committed) {
            RecipeInstallCommitResult.Applied -> RecipeInstallationResult.Applied(record.copyOwned())
            RecipeInstallCommitResult.Unchanged -> RecipeInstallationResult.Unchanged(record.copyOwned())
            RecipeInstallCommitResult.Conflict -> RecipeInstallationResult.Conflict
            RecipeInstallCommitResult.Rejected -> rejected(RecipeInstallationErrorCode.StoreRejected)
        }
    }
}

/** Resolves only the artifact retained by the host-owned installation store. */
class InstalledRecipeBundleResolver(
    private val store: RecipeInstallationStore,
) : VerifiedRecipeBundleResolver {
    override suspend fun resolve(catalogId: String, stableId: String): DeclarativeExtensionBundle? {
        if (!validRecipeInstallationCatalogId(catalogId) || !validRecipeInstallationIdentifier(stableId, 80)) return null
        val record = store.readCatalog(catalogId)?.installedRecords?.get(stableId) ?: return null
        if (record.catalogId != catalogId || record.stableId != stableId || record.sourceId != recipeSourceId(catalogId, stableId)) return null
        val metadata = RecipeArtifactMetadata(stableId, record.releaseVersion, record.sha256, record.sizeBytes, "https://recipe.invalid/$stableId")
        if (VerifiedRecipeCatalogVerifier.artifactEligibility(metadata, record.artifactBytes) !is RecipeArtifactEligibility.Eligible) return null
        return (StrictRecipeBundleDecoder.decode(record.artifactBytes) as? RecipeBundleDecodeResult.Accepted)
            ?.bundle
            ?.takeIf { it.manifest.id == stableId }
    }
}

/** In-memory contract store for deterministic common tests; replay state intentionally survives uninstall. */
class InMemoryRecipeInstallationStore(
    snapshots: List<CatalogInstallationSnapshot>,
    private val clock: RecipeInstallationClock,
    private val limits: RecipeInstallationStoreLimits = RecipeInstallationStoreLimits(),
) : RecipeInstallationStore {
    private val mutex = Mutex()
    private val catalogs = snapshots.associate { snapshot ->
        snapshot.catalogId to StoredCatalog(snapshot.generation.value, snapshot.trustPolicy, snapshot.acceptanceState, snapshot.installedRecords)
    }.toMutableMap()
    private var failNextCommit = false

    override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult {
        val ownedTrustPolicy = trustPolicy.copyOwned()
        return mutex.withLock {
        if (catalogs.containsKey(catalogId)) return@withLock RecipeCatalogEnrollmentResult.AlreadyExists
        if (catalogs.size >= limits.maxEnrolledCatalogs || !validEnrollment(catalogId, ownedTrustPolicy)) {
            return@withLock RecipeCatalogEnrollmentResult.Rejected
        }
        catalogs[catalogId] = StoredCatalog(0, ownedTrustPolicy, null, emptyMap())
        RecipeCatalogEnrollmentResult.Created
        }
    }

    override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = mutex.withLock {
        catalogs[catalogId]?.snapshot(catalogId)
    }

    override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = mutex.withLock {
        if (failNextCommit) {
            failNextCommit = false
            return@withLock RecipeInstallCommitResult.Rejected
        }
        val current = catalogs[candidate.catalogId] ?: return@withLock RecipeInstallCommitResult.Rejected
        val decision = decideRecipeInstallationCommit(
            current.snapshot(candidate.catalogId), expectedGeneration, candidate, clock.nowEpochSeconds(), limits,
        )
        if (decision != RecipeInstallCommitResult.Applied) return@withLock decision

        current.records[candidate.record.stableId] = candidate.record.copyOwned()
        current.acceptanceState = candidate.acceptedAcceptanceState.copyOwned()
        current.advanceGeneration()
        RecipeInstallCommitResult.Applied
    }

    suspend fun uninstall(catalogId: String, stableId: String): Boolean = mutex.withLock {
        val current = catalogs[catalogId] ?: return@withLock false
        if (current.generation == Long.MAX_VALUE) return@withLock false
        current.records.remove(stableId)
        current.advanceGeneration()
    }

    suspend fun replaceTrustPolicy(catalogId: String, trustPolicy: CatalogTrustPolicy): Boolean {
        val ownedTrustPolicy = trustPolicy.copyOwned()
        return mutex.withLock {
        val current = catalogs[catalogId] ?: return@withLock false
        if (!validRecipeInstallationTrustPolicy(catalogId, ownedTrustPolicy, limits, requireActiveKey = false)) return@withLock false
        if (current.generation == Long.MAX_VALUE) return@withLock false
        current.trustPolicy = ownedTrustPolicy
        current.advanceGeneration()
        }
    }

    suspend fun failNextCommit() = mutex.withLock { failNextCommit = true }

    private fun validEnrollment(catalogId: String, trustPolicy: CatalogTrustPolicy): Boolean {
        return validRecipeInstallationTrustPolicy(catalogId, trustPolicy, limits, requireActiveKey = true)
    }

    private class StoredCatalog(
        var generation: Long,
        trustPolicy: CatalogTrustPolicy,
        acceptanceState: CatalogAcceptanceState?,
        records: Map<String, InstalledRecipeRecord>,
    ) {
        var trustPolicy = trustPolicy.copyOwned()
        var acceptanceState = acceptanceState?.copyOwned()
        val records = records.mapValues { (_, record) -> record.copyOwned() }.toMutableMap()
        fun advanceGeneration(): Boolean {
            if (generation == Long.MAX_VALUE) return false
            generation++
            return true
        }
        fun snapshot(catalogId: String): CatalogInstallationSnapshot = CatalogInstallationSnapshot(
            catalogId, CatalogSnapshotGeneration(generation), trustPolicy, acceptanceState, records,
        )
    }
}

private fun CatalogTrustPolicy.copyOwned(): CatalogTrustPolicy = CatalogTrustPolicy(
    catalogId,
    trustedKeys.map { key ->
        TrustedCatalogKey(key.catalogId, key.keyId, key.rawEd25519PublicKey.copyOf(), key.state, key.validFromEpochSeconds, key.validUntilEpochSeconds)
    },
)

private fun CatalogAcceptanceState.copyOwned(): CatalogAcceptanceState = CatalogAcceptanceState(catalogId, highestRevision, payloadHash)

internal fun decideRecipeInstallationCommit(
    current: CatalogInstallationSnapshot,
    expectedGeneration: CatalogSnapshotGeneration,
    candidate: RecipeInstallCandidate,
    commitNowEpochSeconds: Long,
    limits: RecipeInstallationStoreLimits,
): RecipeInstallCommitResult {
    if (current.generation.value != expectedGeneration.value || !sameTrustPolicy(current.trustPolicy, candidate.expectedTrustPolicy) || !sameAcceptance(current.acceptanceState, candidate.expectedAcceptanceState)) {
        return RecipeInstallCommitResult.Conflict
    }
    val signingKey = current.trustPolicy.trustedKeys.singleOrNull { it.keyId == candidate.signingKeyId }
    if (commitNowEpochSeconds >= candidate.expiresAtEpochSeconds || signingKey == null || signingKey.state != TrustedCatalogKeyState.Active ||
        signingKey.validFromEpochSeconds != candidate.signingKeyValidFromEpochSeconds || signingKey.validUntilEpochSeconds != candidate.signingKeyValidUntilEpochSeconds ||
        (signingKey.validFromEpochSeconds != null && commitNowEpochSeconds < signingKey.validFromEpochSeconds) ||
        (signingKey.validUntilEpochSeconds != null && commitNowEpochSeconds > signingKey.validUntilEpochSeconds) ||
        candidate.acceptedAcceptanceState.catalogId != candidate.catalogId || candidate.record.catalogId != candidate.catalogId || candidate.record.catalogRevision != candidate.acceptedAcceptanceState.highestRevision
    ) return RecipeInstallCommitResult.Rejected
    val replay = current.acceptanceState
    if (replay != null && (candidate.acceptedAcceptanceState.highestRevision < replay.highestRevision ||
            (candidate.acceptedAcceptanceState.highestRevision == replay.highestRevision && !candidate.acceptedAcceptanceState.payloadHash.contentEquals(replay.payloadHash)))) return RecipeInstallCommitResult.Rejected
    val installed = current.installedRecords[candidate.record.stableId]
    if (installed != null && sameRecord(installed, candidate.record) && sameAcceptance(current.acceptanceState, candidate.acceptedAcceptanceState)) return RecipeInstallCommitResult.Unchanged
    if (current.generation.value == Long.MAX_VALUE || !validRecipeInstallationArtifactRecord(candidate.record) ||
        (installed == null && current.installedRecords.size >= limits.maxInstalledRecipesPerCatalog) ||
        !fitsRecipeInstallationArtifactQuota(current.installedRecords, candidate.record, limits)
    ) return RecipeInstallCommitResult.Rejected
    return RecipeInstallCommitResult.Applied
}

internal fun fitsRecipeInstallationArtifactQuota(
    records: Map<String, InstalledRecipeRecord>,
    replacement: InstalledRecipeRecord,
    limits: RecipeInstallationStoreLimits,
): Boolean {
    var total = 0L
    for ((stableId, record) in records) {
        if (stableId == replacement.stableId) continue
        if (record.sizeBytes < 0 || total > limits.maxArtifactBytesPerCatalog - record.sizeBytes) return false
        total += record.sizeBytes
    }
    return replacement.sizeBytes <= limits.maxArtifactBytesPerCatalog - total
}

internal fun sameTrustPolicy(left: CatalogTrustPolicy, right: CatalogTrustPolicy): Boolean =
    left.catalogId == right.catalogId && left.trustedKeys.size == right.trustedKeys.size && left.trustedKeys.zip(right.trustedKeys).all { (a, b) ->
        a.catalogId == b.catalogId && a.keyId == b.keyId && a.state == b.state && a.validFromEpochSeconds == b.validFromEpochSeconds &&
            a.validUntilEpochSeconds == b.validUntilEpochSeconds && a.rawEd25519PublicKey.contentEquals(b.rawEd25519PublicKey)
    }

internal fun sameAcceptance(left: CatalogAcceptanceState?, right: CatalogAcceptanceState?): Boolean =
    left === right || (left != null && right != null && left.catalogId == right.catalogId && left.highestRevision == right.highestRevision && left.payloadHash.contentEquals(right.payloadHash))

internal fun sameRecord(left: InstalledRecipeRecord, right: InstalledRecipeRecord): Boolean =
    left.catalogId == right.catalogId && left.stableId == right.stableId && left.catalogRevision == right.catalogRevision &&
        left.releaseVersion == right.releaseVersion && left.sha256 == right.sha256 && left.sizeBytes == right.sizeBytes && left.artifactBytes.contentEquals(right.artifactBytes)

private fun rejected(code: RecipeInstallationErrorCode): RecipeInstallationResult.Rejected = RecipeInstallationResult.Rejected(code)

internal fun validRecipeInstallationTrustPolicy(
    catalogId: String,
    trustPolicy: CatalogTrustPolicy,
    limits: RecipeInstallationStoreLimits,
    requireActiveKey: Boolean,
): Boolean {
    if (!validRecipeInstallationCatalogId(catalogId) || trustPolicy.catalogId != catalogId || trustPolicy.trustedKeys.isEmpty() || trustPolicy.trustedKeys.size > limits.maxKeysPerCatalog) return false
    val keyIds = mutableSetOf<String>()
    return trustPolicy.trustedKeys.all { key ->
        key.catalogId == catalogId && validRecipeInstallationKeyId(key.keyId) && keyIds.add(key.keyId) &&
            key.rawEd25519PublicKey.size == 32 &&
            (key.validFromEpochSeconds == null || key.validUntilEpochSeconds == null || key.validFromEpochSeconds <= key.validUntilEpochSeconds)
    } && (!requireActiveKey || trustPolicy.trustedKeys.any { it.state == TrustedCatalogKeyState.Active })
}

internal fun validRecipeInstallationCatalogId(value: String): Boolean = validRecipeInstallationIdentifier(value, 64)
internal fun validRecipeInstallationKeyId(value: String): Boolean = validRecipeInstallationIdentifier(value, 64)
internal fun validRecipeInstallationArtifactRecord(record: InstalledRecipeRecord): Boolean =
    validRecipeInstallationIdentifier(record.stableId, 80) && validRecipeInstallationReleaseVersion(record.releaseVersion) &&
        record.sizeBytes in 1..(32L * 1024 * 1024) && record.sizeBytes == record.artifactBytes.size.toLong() &&
        record.sourceId == recipeSourceId(record.catalogId, record.stableId) &&
        record.sha256.length == 64 && record.sha256.all { it in '0'..'9' || it in 'a'..'f' }
internal fun validRecipeInstallationReleaseVersion(value: String): Boolean = validRecipeInstallationIdentifier(value, 80, allowPlus = true)
private fun validRecipeInstallationIdentifier(value: String, maxLength: Int, allowPlus: Boolean = false): Boolean = RecipeSyntax.isIdentifier(value, maxLength, allowPlus)
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeSyntax.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeSyntax.kt) · implementation · 54 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
4: internal object RecipeCatalogLimits {
11: internal object RecipeSyntax {
13: fun isHost(host: String): Boolean = host.isNotEmpty() && host.length <= 253 && host.any { it in 'a'..'z' } &&
18: fun isNormalizedHttpsOrigin(value: String): Boolean {
31: fun isIdentifier(value: String, maxLength: Int = 80, allowPlus: Boolean = false): Boolean = value.isNotEmpty() && value.length <= maxLength &&
35: fun isCanonicalPath(path: String): Boolean {
51: 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' + 10
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeSyntax.kt) · SHA-256 `2b27a1562fe952214c667610e45db0cc6690a773c64fbb7c6054902b30ae4381`.

### Complete file

```kotlin
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
}
```
[complete-source-end]: #

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

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/StrictRecipeBundleDecoder.kt) · implementation · 321 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
7: object RecipeBundleLimits {
19: enum class RecipeBundleErrorCode {
34: data class RecipeBundleError(
40: sealed interface RecipeBundleDecodeResult {
41: data class Accepted(val bundle: DeclarativeExtensionBundle) : RecipeBundleDecodeResult
42: data class Rejected(val error: RecipeBundleError) : RecipeBundleDecodeResult
45: object StrictRecipeBundleDecoder {
54: fun decode(bytes: ByteArray): RecipeBundleDecodeResult {
69: internal fun boundedJsonPreflight(bytes: ByteArray, maxBytes: Int): RecipeBundleError? =
73: internal fun boundedApiResponseJsonPreflight(bytes: ByteArray, maxBytes: Int): RecipeBundleError? = boundedPreflight(bytes, maxBytes, maxBytes, 512)
75: private fun boundedPreflight(bytes: ByteArray, maxBytes: Int, maxStringCharacters: Int, maxCollectionEntries: Int): RecipeBundleError? {
85: private fun decodingCode(error: SerializationException): RecipeBundleErrorCode {
96: object RecipeBundleValidator {
98: fun validate(bundle: DeclarativeExtensionBundle): RecipeBundleDecodeResult {
104: private fun validateV21(bundle: DeclarativeExtensionBundle, origins: Map<String, DeclaredRecipeOrigin>): RecipeBundleDecodeResult {
121: private fun validV21Inputs(name: String, inputs: List<RecipeHostInput>): Boolean = inputs.toSet().size == inputs.size && when (name) {
127: private fun validV21UrlValue(value: RecipeV21UrlValue): Boolean = when (value) {
131: private fun validV21Terminal(entry: RecipeV21Entrypoint): Boolean {
143: private fun terminalMatchesEntrypoint(name: String, type: RecipeV21TerminalType): Boolean = when (name) {
150: private fun validateManifest(manifest: ExtensionRecipeManifest): Map<String, DeclaredRecipeOrigin>? {
162: private fun validText(value: String): Boolean = value.isNotEmpty() && value.length <= RecipeBundleLimits.maxStringCharacters
163: private fun validJsonPointer(pointer: String): Boolean {
173: private fun rejected(code: RecipeBundleErrorCode, path: String = "$", detail: String = "invalid recipe bundle"): RecipeBundleDecodeResult.Rejected =
176: private fun reject(code: RecipeBundleErrorCode, path: String = "$", detail: String = "invalid recipe bundle"): RecipeBundleError =
180: private 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 }
184: fun scan(source: String, maxDepth: Int, maxStringCharacters: Int, maxCollectionEntries: Int): RecipeBundleError? {
189: fun skipWhitespace() { while (source.getOrNull(index)?.let(::isJsonWhitespace) == true) index++ }
190: fun fail() = reject(RecipeBundleErrorCode.InvalidJson)
191: fun finishValue(parent: Frame) {
198: fun readString(): String? {
231: fun readNumber(): Boolean {
251: fun consumeValue(parent: Frame): Boolean {
313: 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) {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/StrictRecipeBundleDecoder.kt) · SHA-256 `ccb3190f5639670b261af783dd642a4f605586af1b83b111c0294521b3909897`.

### Complete file

```kotlin
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<DeclarativeExtensionBundle>(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<String, DeclaredRecipeOrigin>): 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<RecipeHostInput>): 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<String, DeclaredRecipeOrigin>? {
        if (!RecipeSyntax.isIdentifier(manifest.id) || !validText(manifest.name) ||
            manifest.declaredCapabilities.size > RecipeBundleLimits.maxCollectionEntries ||
            manifest.declaredOrigins.size > RecipeBundleLimits.maxOrigins
        ) return null
        val origins = mutableMapOf<String, DeclaredRecipeOrigin>()
        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<String>(); 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
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalog.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalog.kt) · implementation · 371 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
13: data class TrustedCatalogKey(
23: data class CatalogTrustPolicy(
28: enum class TrustedCatalogKeyState { Active, Revoked }
31: class CatalogAcceptanceState(
40: data class VerifiedRecipeCatalog(
46: enum class RecipeCatalogFormatVersion {
53: data class RecipeArtifactMetadata(
61: enum class RecipeCatalogVerificationErrorCode {
83: data class RecipeCatalogVerificationError(
88: sealed interface RecipeCatalogVerificationResult {
89: data class Accepted(
95: data class Rejected(val error: RecipeCatalogVerificationError) : RecipeCatalogVerificationResult
98: sealed interface RecipeArtifactEligibility {
99: data object Eligible : RecipeArtifactEligibility
100: data class Rejected(val error: RecipeArtifactEligibilityError) : RecipeArtifactEligibility
103: enum class RecipeArtifactEligibilityError { InvalidMetadata, SizeMismatch, DigestMismatch }
105: object VerifiedRecipeCatalogVerifier {
122: suspend fun verify(
200: suspend fun artifactEligibility(metadata: RecipeArtifactMetadata, bytes: ByteArray): RecipeArtifactEligibility {
212: private fun decodeCatalog(payload: ByteArray): VerifiedRecipeCatalog? {
226: private fun validCatalog(catalog: VerifiedRecipeCatalog): Boolean = catalog.artifacts.size in 1..maxCatalogArtifacts &&
229: private fun validArtifact(artifact: RecipeArtifactMetadata): Boolean =
233: private fun safeHttpsUrl(value: String): Boolean {
251: private fun validIdentifier(value: String): Boolean = RecipeSyntax.isIdentifier(value)
252: private fun validCatalogId(value: String): Boolean = RecipeSyntax.isIdentifier(value)
253: private fun validReleaseVersion(value: String): Boolean = RecipeSyntax.isIdentifier(value, allowPlus = true)
254: private fun validKeyId(value: String): Boolean = RecipeSyntax.isIdentifier(value, RecipeCatalogLimits.maxKeyIdBytes)
255: private fun hexToBytes(value: String): ByteArray? {
259: private fun Char.isHex(): Boolean = this in '0'..'9' || this in 'a'..'f'
260: private fun Char.hexValue(): Int = if (this in '0'..'9') this - '0' else this - 'a' + 10
261: private fun constantTimeEquals(left: ByteArray, right: ByteArray): Boolean {
269: private fun rejected(code: RecipeCatalogVerificationErrorCode): RecipeCatalogVerificationResult.Rejected =
272: internal data class RecipeCatalogEnvelope(
283: internal sealed interface RecipeCatalogEnvelopeParseResult {
284: data class Parsed(val envelope: RecipeCatalogEnvelope) : RecipeCatalogEnvelopeParseResult
285: data object UnsupportedVersion : RecipeCatalogEnvelopeParseResult
286: data object Malformed : RecipeCatalogEnvelopeParseResult
290: internal object RecipeCatalogEnvelopeWire {
297: internal fun parse(bytes: ByteArray, maxEnvelopeBytes: Int, maxPayloadBytes: Int, maxKeyIdBytes: Int): RecipeCatalogEnvelopeParseResult {
302: fun read(count: Int): ByteArray? = if (count > bytes.size - offset) null else bytes.copyOfRange(offset, offset + count).also { offset += count }
332: internal fun signingFrame(envelope: RecipeCatalogEnvelope): ByteArray = signingFrame(
336: internal fun signingFrame(
346: internal fun encodeForTesting(
362: private fun readU16(bytes: ByteArray): Int = ((bytes[0].toInt() and 0xff) shl 8) or (bytes[1].toInt() and 0xff)
363: private fun readU32(bytes: ByteArray): Int? {
367: private fun readI64(bytes: ByteArray): Long = bytes.fold(0L) { value, byte -> (value shl 8) or (byte.toLong() and 0xff) }
368: private fun writeU16(value: Int): ByteArray = byteArrayOf((value ushr 8).toByte(), value.toByte())
369: private fun writeU32(value: Int): ByteArray = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
370: private fun writeI64(value: Long): ByteArray = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalog.kt) · SHA-256 `7a71d44947579f73cde778067d4c6616ed46079cf27e4f61bfaf501cf3da1b2b`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import dev.whyoleg.cryptography.CryptographyProviderApi
import dev.whyoleg.cryptography.algorithms.EdDSA
import dev.whyoleg.cryptography.algorithms.SHA256
import eu.friedcutlet.yokan.services.catchingNonCancellation
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.json.Json

/** Host-owned trust material. It is intentionally not serializable recipe/catalog data. */
data class TrustedCatalogKey(
    val catalogId: String,
    val keyId: String,
    val rawEd25519PublicKey: ByteArray,
    val state: TrustedCatalogKeyState,
    val validFromEpochSeconds: Long? = null,
    val validUntilEpochSeconds: Long? = null,
)

/** Host-owned key scope; keys enrolled for another catalog are never valid here. */
data class CatalogTrustPolicy(
    val catalogId: String,
    val trustedKeys: List<TrustedCatalogKey>,
)

enum class TrustedCatalogKeyState { Active, Revoked }

/** Host-owned replay state. Persisting it belongs to a later integration phase. */
class CatalogAcceptanceState(
    val catalogId: String,
    val highestRevision: Long,
    payloadHash: ByteArray,
) {
    val payloadHash: ByteArray = payloadHash.copyOf()
}

@Serializable
data class VerifiedRecipeCatalog(
    val formatVersion: RecipeCatalogFormatVersion,
    val artifacts: List<RecipeArtifactMetadata>,
)

@Serializable
enum class RecipeCatalogFormatVersion {
    @SerialName("1")
    V1,
}

/** Signed transport metadata only; recipe parsing and execution deliberately remain out of scope. */
@Serializable
data class RecipeArtifactMetadata(
    val stableId: String,
    val releaseVersion: String,
    val sha256: String,
    val sizeBytes: Long,
    val url: String,
)

enum class RecipeCatalogVerificationErrorCode {
    EnvelopeTooLarge,
    MalformedEnvelope,
    UnsupportedEnvelopeVersion,
    UnknownKey,
    RevokedKey,
    InvalidKey,
    KeyOutsideValidity,
    InvalidSignature,
    InvalidPayloadDigest,
    Expired,
    IssuedInFuture,
    InvalidLifetime,
    CatalogIdentityMismatch,
    InvalidTrustPolicy,
    Rollback,
    RevisionConflict,
    InvalidAcceptanceState,
    InvalidCatalogPayload,
    InvalidArtifactMetadata,
}

data class RecipeCatalogVerificationError(
    val code: RecipeCatalogVerificationErrorCode,
    val detail: String = "catalog verification failed",
)

sealed interface RecipeCatalogVerificationResult {
    data class Accepted(
        val catalog: VerifiedRecipeCatalog,
        val acceptanceState: CatalogAcceptanceState,
        val idempotent: Boolean,
    ) : RecipeCatalogVerificationResult

    data class Rejected(val error: RecipeCatalogVerificationError) : RecipeCatalogVerificationResult
}

sealed interface RecipeArtifactEligibility {
    data object Eligible : RecipeArtifactEligibility
    data class Rejected(val error: RecipeArtifactEligibilityError) : RecipeArtifactEligibility
}

enum class RecipeArtifactEligibilityError { InvalidMetadata, SizeMismatch, DigestMismatch }

object VerifiedRecipeCatalogVerifier {
    private const val maxCatalogArtifacts = 64
    private const val maxArtifactBytes = 32 * 1024 * 1024
    private const val maxCatalogLifetimeSeconds = 14L * 24 * 60 * 60
    private const val maxFutureIssueSkewSeconds = 5L * 60
    private const val publicKeyBytes = 32
    private const val sha256Bytes = 32
    private val provider = dev.whyoleg.cryptography.CryptographyProvider.Default
    private val catalogJson = Json {
        ignoreUnknownKeys = false
        isLenient = false
        coerceInputValues = false
        explicitNulls = false
        useAlternativeNames = false
    }

    @OptIn(CryptographyProviderApi::class)
    suspend fun verify(
        envelopeBytes: ByteArray,
        trustPolicy: CatalogTrustPolicy,
        previousAcceptance: CatalogAcceptanceState?,
        nowEpochSeconds: Long,
    ): RecipeCatalogVerificationResult {
        val envelope = when (val parsed = RecipeCatalogEnvelopeWire.parse(envelopeBytes, RecipeCatalogLimits.maxEnvelopeBytes, RecipeCatalogLimits.maxPayloadBytes, RecipeCatalogLimits.maxKeyIdBytes)) {
            is RecipeCatalogEnvelopeParseResult.Parsed -> parsed.envelope
            RecipeCatalogEnvelopeParseResult.UnsupportedVersion -> return rejected(RecipeCatalogVerificationErrorCode.UnsupportedEnvelopeVersion)
            RecipeCatalogEnvelopeParseResult.Malformed -> return rejected(RecipeCatalogVerificationErrorCode.MalformedEnvelope)
        }
        if (!validCatalogId(trustPolicy.catalogId) || trustPolicy.trustedKeys.any { it.catalogId != trustPolicy.catalogId }) {
            return rejected(RecipeCatalogVerificationErrorCode.InvalidTrustPolicy)
        }
        if (envelope.catalogId != trustPolicy.catalogId) return rejected(RecipeCatalogVerificationErrorCode.CatalogIdentityMismatch)
        val matchingKeys = trustPolicy.trustedKeys.filter { it.keyId == envelope.keyId }
        if (matchingKeys.isEmpty()) return rejected(RecipeCatalogVerificationErrorCode.UnknownKey)
        if (matchingKeys.size != 1) return rejected(RecipeCatalogVerificationErrorCode.InvalidKey)
        val key = matchingKeys.single()
        if (key.state == TrustedCatalogKeyState.Revoked) return rejected(RecipeCatalogVerificationErrorCode.RevokedKey)
        if (key.rawEd25519PublicKey.size != publicKeyBytes || !validKeyId(key.keyId) || !validCatalogId(key.catalogId)) {
            return rejected(RecipeCatalogVerificationErrorCode.InvalidKey)
        }
        if ((key.validFromEpochSeconds != null && nowEpochSeconds < key.validFromEpochSeconds) ||
            (key.validUntilEpochSeconds != null && nowEpochSeconds > key.validUntilEpochSeconds)
        ) return rejected(RecipeCatalogVerificationErrorCode.KeyOutsideValidity)
        if (envelope.expiresAtEpochSeconds <= envelope.issuedAtEpochSeconds ||
            envelope.issuedAtEpochSeconds > Long.MAX_VALUE - maxCatalogLifetimeSeconds ||
            envelope.expiresAtEpochSeconds > envelope.issuedAtEpochSeconds + maxCatalogLifetimeSeconds
        ) return rejected(RecipeCatalogVerificationErrorCode.InvalidLifetime)
        val latestAllowedIssue = if (nowEpochSeconds > Long.MAX_VALUE - maxFutureIssueSkewSeconds) {
            Long.MAX_VALUE
        } else {
            nowEpochSeconds + maxFutureIssueSkewSeconds
        }
        if (envelope.issuedAtEpochSeconds > latestAllowedIssue) {
            return rejected(RecipeCatalogVerificationErrorCode.IssuedInFuture)
        }
        if (envelope.expiresAtEpochSeconds <= nowEpochSeconds) return rejected(RecipeCatalogVerificationErrorCode.Expired)

        val payloadHash = catchingNonCancellation { provider.get(SHA256).hasher().hash(envelope.payload) }
            .getOrElse { return rejected(RecipeCatalogVerificationErrorCode.InvalidPayloadDigest) }
        if (!constantTimeEquals(payloadHash, envelope.payloadHash)) return rejected(RecipeCatalogVerificationErrorCode.InvalidPayloadDigest)

        val publicKey = catchingNonCancellation {
            provider.get(EdDSA).publicKeyDecoder(EdDSA.Curve.Ed25519)
                .decodeFromByteArray(EdDSA.PublicKey.Format.RAW, key.rawEd25519PublicKey)
        }.getOrElse { return rejected(RecipeCatalogVerificationErrorCode.InvalidKey) }
        val signatureValid = catchingNonCancellation {
            publicKey.signatureVerifier().tryVerifySignature(RecipeCatalogEnvelopeWire.signingFrame(envelope), envelope.signature)
        }.getOrDefault(false)
        if (!signatureValid) return rejected(RecipeCatalogVerificationErrorCode.InvalidSignature)

        val idempotent = when (previousAcceptance) {
            null -> false
            else -> when {
                previousAcceptance.catalogId != envelope.catalogId || previousAcceptance.highestRevision < 0 || previousAcceptance.payloadHash.size != sha256Bytes ->
                    return rejected(RecipeCatalogVerificationErrorCode.InvalidAcceptanceState)
                envelope.revision < previousAcceptance.highestRevision -> return rejected(RecipeCatalogVerificationErrorCode.Rollback)
                envelope.revision == previousAcceptance.highestRevision && !constantTimeEquals(envelope.payloadHash, previousAcceptance.payloadHash) ->
                    return rejected(RecipeCatalogVerificationErrorCode.RevisionConflict)
                else -> envelope.revision == previousAcceptance.highestRevision
            }
        }
        if (StrictRecipeBundleDecoder.boundedJsonPreflight(envelope.payload, RecipeCatalogLimits.maxPayloadBytes) != null) {
            return rejected(RecipeCatalogVerificationErrorCode.InvalidCatalogPayload)
        }
        val catalog = decodeCatalog(envelope.payload) ?: return rejected(RecipeCatalogVerificationErrorCode.InvalidCatalogPayload)
        if (!validCatalog(catalog)) return rejected(RecipeCatalogVerificationErrorCode.InvalidArtifactMetadata)
        return RecipeCatalogVerificationResult.Accepted(
            catalog = catalog,
            acceptanceState = CatalogAcceptanceState(envelope.catalogId, envelope.revision, envelope.payloadHash),
            idempotent = idempotent,
        )
    }

    @OptIn(CryptographyProviderApi::class)
    /** Integrity matching only; download and installation authorization remain host policy decisions. */
    suspend fun artifactEligibility(metadata: RecipeArtifactMetadata, bytes: ByteArray): RecipeArtifactEligibility {
        if (!validArtifact(metadata)) return RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.InvalidMetadata)
        if (bytes.size.toLong() != metadata.sizeBytes) return RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.SizeMismatch)
        val digest = catchingNonCancellation { provider.get(SHA256).hasher().hash(bytes) }
            .getOrElse { return RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.DigestMismatch) }
        return if (constantTimeEquals(digest, hexToBytes(metadata.sha256) ?: ByteArray(0))) {
            RecipeArtifactEligibility.Eligible
        } else {
            RecipeArtifactEligibility.Rejected(RecipeArtifactEligibilityError.DigestMismatch)
        }
    }

    private fun decodeCatalog(payload: ByteArray): VerifiedRecipeCatalog? {
        val text = try {
            payload.decodeToString(throwOnInvalidSequence = true)
        } catch (_: CharacterCodingException) {
            return null
        }
        // SerializationException is an IllegalArgumentException.
        return try {
            catalogJson.decodeFromString<VerifiedRecipeCatalog>(text)
        } catch (_: IllegalArgumentException) {
            null
        }
    }

    private fun validCatalog(catalog: VerifiedRecipeCatalog): Boolean = catalog.artifacts.size in 1..maxCatalogArtifacts &&
        catalog.artifacts.all(::validArtifact) && catalog.artifacts.map(RecipeArtifactMetadata::stableId).toSet().size == catalog.artifacts.size

    private fun validArtifact(artifact: RecipeArtifactMetadata): Boolean =
        validIdentifier(artifact.stableId) && validReleaseVersion(artifact.releaseVersion) &&
            artifact.sizeBytes in 1..maxArtifactBytes.toLong() && hexToBytes(artifact.sha256)?.size == sha256Bytes && safeHttpsUrl(artifact.url)

    private fun safeHttpsUrl(value: String): Boolean {
        if (value.length !in 9..2_048 || value.any { it.code <= 0x20 || it == '\\' || it == '#' }) return false
        if (loopbackCatalogOrigin(value) != null) return true
        if (!value.startsWith("https://")) return false
        val pathStart = value.indexOf('/', startIndex = 8)
        val queryStart = value.indexOf('?', startIndex = 8)
        val authorityEnd = listOf(pathStart, queryStart).filter { it >= 0 }.minOrNull() ?: value.length
        val authority = value.substring(8, authorityEnd)
        if (authority.isEmpty() || '@' in authority) return false
        val pieces = authority.split(':')
        if (pieces.size !in 1..2 || !RecipeSyntax.isHost(pieces.first())) return false
        if (pieces.size == 2) {
            val port = pieces[1].toIntOrNull() ?: return false
            if (port !in 1..65535 || pieces[1] != port.toString()) return false
        }
        return true
    }

    private fun validIdentifier(value: String): Boolean = RecipeSyntax.isIdentifier(value)
    private fun validCatalogId(value: String): Boolean = RecipeSyntax.isIdentifier(value)
    private fun validReleaseVersion(value: String): Boolean = RecipeSyntax.isIdentifier(value, allowPlus = true)
    private fun validKeyId(value: String): Boolean = RecipeSyntax.isIdentifier(value, RecipeCatalogLimits.maxKeyIdBytes)
    private fun hexToBytes(value: String): ByteArray? {
        if (value.length != 64 || value.any { !it.isHex() }) return null
        return ByteArray(32) { index -> ((value[index * 2].hexValue() shl 4) or value[index * 2 + 1].hexValue()).toByte() }
    }
    private fun Char.isHex(): Boolean = this in '0'..'9' || this in 'a'..'f'
    private fun Char.hexValue(): Int = if (this in '0'..'9') this - '0' else this - 'a' + 10
    private fun constantTimeEquals(left: ByteArray, right: ByteArray): Boolean {
        var difference = left.size xor right.size
        val maximum = maxOf(left.size, right.size)
        for (index in 0 until maximum) difference = difference or ((left.getOrElse(index) { 0 }.toInt() xor right.getOrElse(index) { 0 }.toInt()))
        return difference == 0
    }
}

private fun rejected(code: RecipeCatalogVerificationErrorCode): RecipeCatalogVerificationResult.Rejected =
    RecipeCatalogVerificationResult.Rejected(RecipeCatalogVerificationError(code))

internal data class RecipeCatalogEnvelope(
    val catalogId: String,
    val keyId: String,
    val revision: Long,
    val issuedAtEpochSeconds: Long,
    val expiresAtEpochSeconds: Long,
    val payloadHash: ByteArray,
    val signature: ByteArray,
    val payload: ByteArray,
)

internal sealed interface RecipeCatalogEnvelopeParseResult {
    data class Parsed(val envelope: RecipeCatalogEnvelope) : RecipeCatalogEnvelopeParseResult
    data object UnsupportedVersion : RecipeCatalogEnvelopeParseResult
    data object Malformed : RecipeCatalogEnvelopeParseResult
}

/** Fixed binary envelope and its domain-separated signing frame. */
internal object RecipeCatalogEnvelopeWire {
    private val magic = byteArrayOf('Y'.code.toByte(), 'R'.code.toByte(), 'C'.code.toByte(), '2'.code.toByte())
    private const val version = 2
    private val domain = "yokan.recipe-catalog.ed25519.v2\u0000".encodeToByteArray()
    private const val signatureBytes = 64
    private const val hashBytes = 32

    internal fun parse(bytes: ByteArray, maxEnvelopeBytes: Int, maxPayloadBytes: Int, maxKeyIdBytes: Int): RecipeCatalogEnvelopeParseResult {
        if (bytes.size > maxEnvelopeBytes || bytes.size < magic.size + 1 + 2 + 2 + 8 + 8 + 8 + 4 + hashBytes + signatureBytes) {
            return RecipeCatalogEnvelopeParseResult.Malformed
        }
        var offset = 0
        fun read(count: Int): ByteArray? = if (count > bytes.size - offset) null else bytes.copyOfRange(offset, offset + count).also { offset += count }
        if (read(magic.size)?.contentEquals(magic) != true) return RecipeCatalogEnvelopeParseResult.Malformed
        if (read(1)?.firstOrNull()?.toInt()?.and(0xff) != version) return RecipeCatalogEnvelopeParseResult.UnsupportedVersion
        val catalogLength = readU16(read(2) ?: return RecipeCatalogEnvelopeParseResult.Malformed)
        if (catalogLength !in 1..maxKeyIdBytes) return RecipeCatalogEnvelopeParseResult.Malformed
        val catalogBytes = read(catalogLength) ?: return RecipeCatalogEnvelopeParseResult.Malformed
        val catalogId = try { catalogBytes.decodeToString(throwOnInvalidSequence = true) } catch (_: CharacterCodingException) {
            return RecipeCatalogEnvelopeParseResult.Malformed
        }
        if (catalogId.encodeToByteArray().size != catalogLength) return RecipeCatalogEnvelopeParseResult.Malformed
        val keyLength = readU16(read(2) ?: return RecipeCatalogEnvelopeParseResult.Malformed)
        if (keyLength !in 1..maxKeyIdBytes) return RecipeCatalogEnvelopeParseResult.Malformed
        val keyBytes = read(keyLength) ?: return RecipeCatalogEnvelopeParseResult.Malformed
        val keyId = try { keyBytes.decodeToString(throwOnInvalidSequence = true) } catch (_: CharacterCodingException) {
            return RecipeCatalogEnvelopeParseResult.Malformed
        }
        if (keyId.encodeToByteArray().size != keyLength) return RecipeCatalogEnvelopeParseResult.Malformed
        val revision = readI64(read(8) ?: return RecipeCatalogEnvelopeParseResult.Malformed)
        if (revision < 0) return RecipeCatalogEnvelopeParseResult.Malformed
        val issued = readI64(read(8) ?: return RecipeCatalogEnvelopeParseResult.Malformed)
        val expires = readI64(read(8) ?: return RecipeCatalogEnvelopeParseResult.Malformed)
        val payloadLength = readU32(read(4) ?: return RecipeCatalogEnvelopeParseResult.Malformed) ?: return RecipeCatalogEnvelopeParseResult.Malformed
        if (payloadLength > maxPayloadBytes || payloadLength > bytes.size - offset - hashBytes - signatureBytes) return RecipeCatalogEnvelopeParseResult.Malformed
        val hash = read(hashBytes) ?: return RecipeCatalogEnvelopeParseResult.Malformed
        val signature = read(signatureBytes) ?: return RecipeCatalogEnvelopeParseResult.Malformed
        val payload = read(payloadLength) ?: return RecipeCatalogEnvelopeParseResult.Malformed
        if (offset != bytes.size) return RecipeCatalogEnvelopeParseResult.Malformed
        return RecipeCatalogEnvelopeParseResult.Parsed(RecipeCatalogEnvelope(catalogId, keyId, revision, issued, expires, hash, signature, payload))
    }

    internal fun signingFrame(envelope: RecipeCatalogEnvelope): ByteArray = signingFrame(
        envelope.catalogId.encodeToByteArray(), envelope.keyId.encodeToByteArray(), envelope.revision, envelope.issuedAtEpochSeconds, envelope.expiresAtEpochSeconds, envelope.payload.size, envelope.payloadHash,
    )

    internal fun signingFrame(
        catalogId: ByteArray,
        keyId: ByteArray,
        revision: Long,
        issuedAtEpochSeconds: Long,
        expiresAtEpochSeconds: Long,
        payloadLength: Int,
        payloadHash: ByteArray,
    ): ByteArray = domain + writeU16(catalogId.size) + catalogId + writeU16(keyId.size) + keyId + writeI64(revision) + writeI64(issuedAtEpochSeconds) + writeI64(expiresAtEpochSeconds) + writeU32(payloadLength) + payloadHash

    internal fun encodeForTesting(
        catalogId: String,
        keyId: String,
        revision: Long,
        issuedAtEpochSeconds: Long,
        expiresAtEpochSeconds: Long,
        payloadHash: ByteArray,
        signature: ByteArray,
        payload: ByteArray,
    ): ByteArray {
        val catalog = catalogId.encodeToByteArray()
        val key = keyId.encodeToByteArray()
        return magic + byteArrayOf(version.toByte()) + writeU16(catalog.size) + catalog + writeU16(key.size) + key + writeI64(revision) + writeI64(issuedAtEpochSeconds) +
            writeI64(expiresAtEpochSeconds) + writeU32(payload.size) + payloadHash + signature + payload
    }

    private fun readU16(bytes: ByteArray): Int = ((bytes[0].toInt() and 0xff) shl 8) or (bytes[1].toInt() and 0xff)
    private fun readU32(bytes: ByteArray): Int? {
        val value = ((bytes[0].toLong() and 0xff) shl 24) or ((bytes[1].toLong() and 0xff) shl 16) or ((bytes[2].toLong() and 0xff) shl 8) or (bytes[3].toLong() and 0xff)
        return if (value > Int.MAX_VALUE) null else value.toInt()
    }
    private fun readI64(bytes: ByteArray): Long = bytes.fold(0L) { value, byte -> (value shl 8) or (byte.toLong() and 0xff) }
    private fun writeU16(value: Int): ByteArray = byteArrayOf((value ushr 8).toByte(), value.toByte())
    private fun writeU32(value: Int): ByteArray = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
    private fun writeI64(value: Long): ByteArray = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CatalogEnrollmentCodeTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CatalogEnrollmentCodeTest.kt) · test / fixture · 33 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
7: class CatalogEnrollmentCodeTest {
11: fun parsesAndRendersThePortableFixture() {
22: fun rejectsNonCanonicalAndUnsafeValues() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CatalogEnrollmentCodeTest.kt) · SHA-256 `df2513a3f6a9f335a4dbae3741bbe2b251bbb03b32c5076a6a6b300ec3aab549`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class CatalogEnrollmentCodeTest {
    private val fixture = "yokan-catalog:v1:catalog.primary:aHR0cHM6Ly9jYXRhbG9nLmV4YW1wbGUudGVzdC9yZWxlYXNlcy9yMS9jYXRhbG9nLnlyYw:key-01:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8"

    @Test
    fun parsesAndRendersThePortableFixture() {
        val code = requireNotNull(CatalogEnrollmentCode.parse(fixture))

        assertEquals("catalog.primary", code.catalogId)
        assertEquals("https://catalog.example.test/releases/r1/catalog.yrc", code.catalogEnvelopeUrl)
        assertEquals("key-01", code.keyId)
        assertEquals("630dcd2966c4336691125448bbb25b4ff412a49c732db2c8abc1b8581bd710dd", code.publicKeyFingerprint)
        assertEquals(fixture, code.render())
    }

    @Test
    fun rejectsNonCanonicalAndUnsafeValues() {
        listOf(
            fixture.replace("v1", "v2"),
            fixture.replace("aHR0", "aHR0="),
            fixture.dropLast(1),
            fixture.replace("aHR0cHM6Ly9jYXRhbG9nLmV4YW1wbGUudGVzdC9yZWxlYXNlcy9yMS9jYXRhbG9nLnlyYw", "aHR0cHM6Ly9DYXRhbG9nLmV4YW1wbGUudGVzdC9yZWxlYXNlcy9yMS9jYXRhbG9nLnlyYw"),
            "yokan-catalog:v1:catalog.primary:aHR0cHM6Ly8xMjcuMC4wLjEvY2F0YWxvZy55cmM:key-01:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
            "yokan-catalog:v1:catalog.primary:aHR0cHM6Ly9jYXRhbG9nLmV4YW1wbGUudGVzdDo0NDMvY2F0YWxvZy55cmM:key-01:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8",
            "yokan-catalog:v1:catalog.primary:aHR0cHM6Ly9jYXRhbG9nLmV4YW1wbGUudGVzdC9jYXRhbG9nLnlyYw:key-01:AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8A",
        ).forEach { assertNull(CatalogEnrollmentCode.parse(it), it) }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipeSecurityTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipeSecurityTest.kt) · test / fixture · 18 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
7: class DeclarativeExtensionRecipeSecurityTest {
9: fun decodedBundleCannotSerializeHostAuthority() {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipeSecurityTest.kt) · SHA-256 `0994e3a4a4f3b161e54dbb47829849d1587b7e7ebb335317756fcbbab60e0516`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs

class DeclarativeExtensionRecipeSecurityTest {
    @Test
    fun decodedBundleCannotSerializeHostAuthority() {
        listOf("trust", "approval", "session", "policyHandle", "signature", "catalogUrl", "installationState", "key").forEach { forbiddenField ->
            val result = StrictRecipeBundleDecoder.decode(
                validBundle().replace("\"name\":\"Example\"", "\"name\":\"Example\",\"$forbiddenField\":\"forged\"").encodeToByteArray(),
            )
            val rejected = assertIs<RecipeBundleDecodeResult.Rejected>(result)
            assertEquals(RecipeBundleErrorCode.UnknownFieldOrOperation, rejected.error.code)
        }
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipeTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipeTest.kt) · test / fixture · 92 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
9: class DeclarativeExtensionRecipeTest {
11: fun acceptsEntrypointBundleFromDeclaredOrigin() {
18: fun rejectsInvalidOriginsUnsafeUrlComponentsAndMissingCapabilities() {
30: fun rejectsUnknownFieldsOperationsVersionsAndAuthorityDataWithoutLeakingMarkers() {
41: fun scannerRejectsEscapedAndNestedDuplicatesAndDuplicateDiscriminators() {
48: fun scannerRejectsInvalidEncodingMalformedTokensTrailingCommaAndMultipleRoots() {
58: fun scannerHonorsExactAndBeyondStringCollectionAndDepthLimits() {
74: fun legacyStepFormatVersionsAreRejectedAtValidationInsteadOfInstallingDeadRecipes() {
81: fun nonEmptyLegacyStepsAreRejected() {
85: private fun assertRejected(json: String, expected: RecipeBundleErrorCode) = assertRejected(json.encodeToByteArray(), expected)
86: private fun assertRejected(bytes: ByteArray, expected: RecipeBundleErrorCode) = assertEquals(expected, errorFor(bytes))
87: private fun errorFor(json: String): RecipeBundleErrorCode = errorFor(json.encodeToByteArray())
88: private fun errorFor(bytes: ByteArray): RecipeBundleErrorCode = errorFor(StrictRecipeBundleDecoder.decode(bytes))
89: private fun errorFor(result: RecipeBundleDecodeResult): RecipeBundleErrorCode = assertIs<RecipeBundleDecodeResult.Rejected>(result).error.code
92: internal fun validBundle(id: String = "example.source"): String = """{"manifest":{"formatVersion":"2.1","id":"$id","name":"Example","declaredCapabilities":["networkRead","documentExtraction"],"declaredOrigins":[{"id":"primary","origin":"https://example.test"}]},"recipe":{"steps":[]},"entrypoints":{"popular":{"inputs":["pageIndex"],"url":{"origin":{"originId":"primary"},"path":[{"value":"literal","text":"/items"}]},"projection":{"pointer":"/data","mode":"many","fields":{"id":"/id","title":"/title"}},"terminal":{"type":"listing","pageSize":20}}}}"""
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeExtensionRecipeTest.kt) · SHA-256 `607b837637a29683b68fb6fdbd76254d54abd2dfff798869b8ecbe61c1e274ca`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNotEquals
import kotlin.test.assertFalse

class DeclarativeExtensionRecipeTest {
    @Test
    fun acceptsEntrypointBundleFromDeclaredOrigin() {
        val accepted = assertIs<RecipeBundleDecodeResult.Accepted>(StrictRecipeBundleDecoder.decode(validBundle().encodeToByteArray()))
        assertEquals("primary", accepted.bundle.entrypoints.getValue("popular").url.origin.originId)
        assertEquals("https://example.test", accepted.bundle.manifest.declaredOrigins.single().origin)
    }

    @Test
    fun rejectsInvalidOriginsUnsafeUrlComponentsAndMissingCapabilities() {
        listOf(
            "http://example.test", "https://*.example.test", "https://user@example.test", "https://example.test/path",
            "https://example.test?query", "https://example.test#fragment", "https://EXAMPLE.test", "https://example.test:443", "https://192.0.2.1",
        ).forEach { origin -> assertRejected(validBundle().replace("https://example.test", origin), RecipeBundleErrorCode.InvalidValue) }
        assertRejected(validBundle().replace("\"originId\":\"primary\"", "\"originId\":\"missing\""), RecipeBundleErrorCode.InvalidValue)
        assertRejected(validBundle().replace("\"text\":\"/items\"", "\"text\":\"//attacker.test\""), RecipeBundleErrorCode.InvalidValue)
        assertRejected(validBundle().replace("\"text\":\"/items\"", "\"text\":\"/items#fragment\""), RecipeBundleErrorCode.InvalidValue)
        assertRejected(validBundle().replace("[\"networkRead\",\"documentExtraction\"]", "[\"documentExtraction\"]"), RecipeBundleErrorCode.InvalidValue)
    }

    @Test
    fun rejectsUnknownFieldsOperationsVersionsAndAuthorityDataWithoutLeakingMarkers() {
        val marker = "ATTACKER_MARKER_6af27"
        val rejected = assertIs<RecipeBundleDecodeResult.Rejected>(StrictRecipeBundleDecoder.decode(
            validBundle().replace("\"name\":\"Example\"", "\"name\":\"Example\",\"$marker\":\"$marker\"").encodeToByteArray(),
        ))
        assertEquals(RecipeBundleErrorCode.UnknownFieldOrOperation, rejected.error.code)
        assertFalse(rejected.error.detail.contains(marker))
        assertRejected(validBundle().replace("\"literal\"", "\"executeJavaScript\""), RecipeBundleErrorCode.UnknownFieldOrOperation)
    }

    @Test
    fun scannerRejectsEscapedAndNestedDuplicatesAndDuplicateDiscriminators() {
        assertRejected(validBundle().replace("\"id\":\"example.source\"", "\"id\":\"example.source\",\"\\u0069d\":\"other\""), RecipeBundleErrorCode.DuplicateJsonKey)
        assertRejected(validBundle().replace("\"originId\":\"primary\"", "\"originId\":\"primary\",\"\\u006friginId\":\"other\""), RecipeBundleErrorCode.DuplicateJsonKey)
        assertRejected(validBundle().replaceFirst("\"value\":\"literal\"", "\"value\":\"literal\",\"value\":\"hostInput\""), RecipeBundleErrorCode.DuplicateJsonKey)
    }

    @Test
    fun scannerRejectsInvalidEncodingMalformedTokensTrailingCommaAndMultipleRoots() {
        assertRejected(byteArrayOf('{'.code.toByte(), '"'.code.toByte(), 'x'.code.toByte(), '"'.code.toByte(), ':'.code.toByte(), 0xC3.toByte()), RecipeBundleErrorCode.InvalidJson)
        listOf("{\"x\":\"\\u12\"}", "{\"x\":\"\\q\"}", "{\"x\":01}", "{\"x\":1e}", "{\"x\":-}").forEach {
            assertRejected(it, RecipeBundleErrorCode.InvalidJson)
        }
        assertRejected(validBundle().replace("\"documentExtraction\"]", "\"documentExtraction\",]"), RecipeBundleErrorCode.InvalidJson)
        assertRejected(validBundle() + validBundle(), RecipeBundleErrorCode.InvalidJson)
    }

    @Test
    fun scannerHonorsExactAndBeyondStringCollectionAndDepthLimits() {
        assertIs<RecipeBundleDecodeResult.Accepted>(StrictRecipeBundleDecoder.decode(validBundle().replace("\"Example\"", "\"${"a".repeat(RecipeBundleLimits.maxStringCharacters)}\"").encodeToByteArray()))
        assertRejected(validBundle().replace("\"Example\"", "\"${"a".repeat(RecipeBundleLimits.maxStringCharacters + 1)}\""), RecipeBundleErrorCode.StringLimitExceeded)

        val exactCapabilities = List(RecipeBundleLimits.maxCollectionEntries) { if (it == 0) "\"documentExtraction\"" else "\"networkRead\"" }.joinToString(",")
        assertIs<RecipeBundleDecodeResult.Accepted>(StrictRecipeBundleDecoder.decode(validBundle().replace("\"networkRead\",\"documentExtraction\"", exactCapabilities).encodeToByteArray()))
        val beyondCapabilities = List(RecipeBundleLimits.maxCollectionEntries + 1) { "\"networkRead\"" }.joinToString(",")
        assertRejected(validBundle().replace("\"networkRead\",\"documentExtraction\"", beyondCapabilities), RecipeBundleErrorCode.CollectionLimitExceeded)

        val exactDepth = "[".repeat(RecipeBundleLimits.maxJsonDepth) + "0" + "]".repeat(RecipeBundleLimits.maxJsonDepth)
        assertNotEquals(RecipeBundleErrorCode.NestingLimitExceeded, errorFor(exactDepth))
        val beyondDepth = "[".repeat(RecipeBundleLimits.maxJsonDepth + 1) + "0" + "]".repeat(RecipeBundleLimits.maxJsonDepth + 1)
        assertRejected(beyondDepth, RecipeBundleErrorCode.NestingLimitExceeded)
    }

    @Test
    fun legacyStepFormatVersionsAreRejectedAtValidationInsteadOfInstallingDeadRecipes() {
        listOf("1", "2").forEach { version ->
            assertRejected(validBundle().replace("\"formatVersion\":\"2.1\"", "\"formatVersion\":\"$version\""), RecipeBundleErrorCode.UnsupportedFormatVersion)
        }
    }

    @Test
    fun nonEmptyLegacyStepsAreRejected() {
        assertRejected(validBundle().replace("\"steps\":[]", "\"steps\":[{\"operation\":\"buildUrl\"}]"), RecipeBundleErrorCode.InvalidValue)
    }

    private fun assertRejected(json: String, expected: RecipeBundleErrorCode) = assertRejected(json.encodeToByteArray(), expected)
    private fun assertRejected(bytes: ByteArray, expected: RecipeBundleErrorCode) = assertEquals(expected, errorFor(bytes))
    private fun errorFor(json: String): RecipeBundleErrorCode = errorFor(json.encodeToByteArray())
    private fun errorFor(bytes: ByteArray): RecipeBundleErrorCode = errorFor(StrictRecipeBundleDecoder.decode(bytes))
    private fun errorFor(result: RecipeBundleDecodeResult): RecipeBundleErrorCode = assertIs<RecipeBundleDecodeResult.Rejected>(result).error.code
}

internal fun validBundle(id: String = "example.source"): String = """{"manifest":{"formatVersion":"2.1","id":"$id","name":"Example","declaredCapabilities":["networkRead","documentExtraction"],"declaredOrigins":[{"id":"primary","origin":"https://example.test"}]},"recipe":{"steps":[]},"entrypoints":{"popular":{"inputs":["pageIndex"],"url":{"origin":{"originId":"primary"},"path":[{"value":"literal","text":"/items"}]},"projection":{"pointer":"/data","mode":"many","fields":{"id":"/id","title":"/title"}},"terminal":{"type":"listing","pageSize":20}}}}"""
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeRecipeRuntimeTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeRecipeRuntimeTest.kt) · test / fixture · 41 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
10: class DeclarativeRecipeRuntimeTest {
16: fun entrypointProjectsJsonFromTheGrantedOrigin() = runTest {
25: fun brokerExceptionsBecomeBrokerFailureButCancellationPropagates() = runTest {
33: fun malformedJsonResponseIsRejected() = runTest {
38: private fun broker(respond: (RecipeBrokerRequest) -> RecipeBrokerResult) = object : RecipeCapabilityBroker {
39: override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult = respond(request)
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/DeclarativeRecipeRuntimeTest.kt) · SHA-256 `d64c40fc8313981bea23ae6596a72a72526013d96721365e1b068fd158763486`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertIs

class DeclarativeRecipeRuntimeTest {
    private val policy = RecipeExecutionPolicy(mapOf("primary" to "https://example.test"))
    private val inputs = mapOf("pageIndex" to RecipeEntrypointInput.PageIndex(0))
    private val bundle = assertIs<RecipeBundleDecodeResult.Accepted>(StrictRecipeBundleDecoder.decode(validBundle().encodeToByteArray())).bundle

    @Test
    fun entrypointProjectsJsonFromTheGrantedOrigin() = runTest {
        var requested: RecipeBrokerRequest? = null
        val broker = broker { requested = it; RecipeBrokerResult.Document("""{"data":[{"id":"a","title":"A"}]}""".encodeToByteArray()) }
        val completed = assertIs<RecipeEntrypointExecutionResult.Completed>(DeclarativeRecipeRuntime(broker).executeEntrypoint(bundle, "popular", inputs, policy))
        assertEquals(listOf(RecipeEntrypointResult.Item("a", "A", null)), assertIs<RecipeEntrypointResult.Listing>(completed.result).items)
        assertEquals("https://example.test/items", requested?.url)
    }

    @Test
    fun brokerExceptionsBecomeBrokerFailureButCancellationPropagates() = runTest {
        val failing = DeclarativeRecipeRuntime(broker { throw IllegalStateException("boom") })
        assertEquals(RecipeExecutionErrorCode.BrokerFailure, assertIs<RecipeEntrypointExecutionResult.Rejected>(failing.executeEntrypoint(bundle, "popular", inputs, policy)).error.code)
        val cancelling = DeclarativeRecipeRuntime(broker { throw CancellationException("cancel") })
        assertFailsWith<CancellationException> { cancelling.executeEntrypoint(bundle, "popular", inputs, policy) }
    }

    @Test
    fun malformedJsonResponseIsRejected() = runTest {
        val runtime = DeclarativeRecipeRuntime(broker { RecipeBrokerResult.Document("{".encodeToByteArray()) })
        assertEquals(RecipeExecutionErrorCode.InvalidJsonDocument, assertIs<RecipeEntrypointExecutionResult.Rejected>(runtime.executeEntrypoint(bundle, "popular", inputs, policy)).error.code)
    }

    private fun broker(respond: (RecipeBrokerRequest) -> RecipeBrokerResult) = object : RecipeCapabilityBroker {
        override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult = respond(request)
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeCatalogInstallationServiceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeCatalogInstallationServiceTest.kt) · test / fixture · 179 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
15: class RecipeCatalogInstallationServiceTest {
22: fun enrollmentIsExplicitCreateOnlyAndNeverMergesTrust() = runTest {
38: fun badEnvelopeReplayAndExpiryNeverRequestArtifacts() = runTest {
65: fun portableOriginAndSizePolicyRejectBeforeArtifactRequest() = runTest {
83: fun digestIdentitySuccessAndConflictFollowCoordinatorCommit() = runTest {
106: fun downloaderCancellationPropagates() = runTest {
114: private fun service(store: RecipeInstallationStore, downloader: RecipeCatalogDownloader) = RecipeCatalogInstallationService(
118: private fun emptyStore(): InMemoryRecipeInstallationStore = InMemoryRecipeInstallationStore(emptyList(), RecipeInstallationClock { now })
120: private suspend fun signingMaterial(): SigningMaterial {
128: private fun proposal(signing: SigningMaterial): CatalogEnrollmentCode = requireNotNull(
132: private suspend fun signedEnvelope(signing: SigningMaterial, revision: Long, artifacts: List<Artifact>, expires: Long = now + 600): ByteArray {
145: private fun artifactUrl(id: String) = "https://catalog.example.test/$id.recipe.json"
146: private fun recipe(id: String): ByteArray = validBundle(id).encodeToByteArray()
147: private suspend fun sha256(bytes: ByteArray) = provider.get(SHA256).hasher().hash(bytes)
148: private fun ByteArray.toHexString() = joinToString("") { (it.toInt() and 255).toString(16).padStart(2, '0') }
149: private fun u16(value: Int) = byteArrayOf((value ushr 8).toByte(), value.toByte())
150: private fun u32(value: Int) = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
151: private fun i64(value: Long) = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
152: private fun b64(bytes: ByteArray): String = buildString { var index = 0; while (index < bytes.size) { val first = bytes[index++].toInt() and 255; val second = if (index < bytes.size) bytes[index++].toInt() and 255 else -1; val third = if (index < bytes.size) bytes[index++].toInt() and 255 else -1; append(alphabet[first ushr 2]); append(alphabet[((first and 3) shl 4) or if (second < 0) 0 else second ushr 4]); if (second >= 0) append(alphabet[((second and 15) shl 2) or if (third < 0) 0 else third ushr 6]); if (third >= 0) append(alphabet[third and 63]) } }
154: private data class Artifact(val id: String, val bytes: ByteArray, val url: String? = null, val size: Int? = null, val hash: String? = null)
155: private data class SigningMaterial(val key: TrustedCatalogKey, val sign: suspend (ByteArray) -> ByteArray)
161: fun reset(envelope: ByteArray) { catalog = envelope; artifacts.clear(); urls.clear(); failure = null }
162: override suspend fun download(url: String, maxBytes: Int, deadlineMillis: Long): ByteArray {
169: private class RaceStore(private val delegate: InMemoryRecipeInstallationStore) : RecipeInstallationStore {
170: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy) = delegate.enrollIfAbsent(catalogId, trustPolicy)
171: override suspend fun readCatalog(catalogId: String) = delegate.readCatalog(catalogId)
172: override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeCatalogInstallationServiceTest.kt) · SHA-256 `d51edd861639ca9f661c6aa92a5e2bcf6706020db2115f9b8489ca1be8cc74d0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import dev.whyoleg.cryptography.CryptographyProvider
import dev.whyoleg.cryptography.CryptographyProviderApi
import dev.whyoleg.cryptography.algorithms.EdDSA
import dev.whyoleg.cryptography.algorithms.SHA256
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertIs

@OptIn(CryptographyProviderApi::class)
class RecipeCatalogInstallationServiceTest {
    private val provider = CryptographyProvider.Default
    private val now = 1_700_000_000L
    private val catalogId = "catalog.primary"
    private val catalogUrl = "https://catalog.example.test/catalog.yrc"

    @Test
    fun enrollmentIsExplicitCreateOnlyAndNeverMergesTrust() = runTest {
        val signing = signingMaterial()
        val store = emptyStore()
        val service = service(store, FakeDownloader())
        val proposal = proposal(signing)

        assertEquals(RecipeCatalogEnrollmentServiceResult.Created, service.enroll(proposal))
        assertEquals(RecipeCatalogEnrollmentServiceResult.AlreadyEnrolled, service.enroll(proposal))
        assertEquals(
            RecipeCatalogEnrollmentError.MismatchedTrust,
            assertIs<RecipeCatalogEnrollmentServiceResult.Rejected>(service.enroll(proposal(signingMaterial()))).error,
        )
        assertEquals(1, store.readCatalog(catalogId)!!.trustPolicy.trustedKeys.size)
    }

    @Test
    fun badEnvelopeReplayAndExpiryNeverRequestArtifacts() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        val store = emptyStore()
        val downloader = FakeDownloader()
        val service = service(store, downloader)
        val proposal = proposal(signing)
        service.enroll(proposal)

        downloader.catalog = byteArrayOf(0)
        assertEquals(RecipeCatalogInstallError.CatalogRejected, assertIs<RecipeCatalogInstallServiceResult.Rejected>(service.install(proposal, "recipe.one")).error)
        assertEquals(listOf(catalogUrl), downloader.urls)

        downloader.reset(signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact))))
        downloader.artifacts[artifactUrl("recipe.one")] = artifact
        assertIs<RecipeCatalogInstallServiceResult.Applied>(service.install(proposal, "recipe.one"))

        downloader.reset(signedEnvelope(signing, 9, listOf(Artifact("recipe.one", artifact))))
        assertEquals(RecipeCatalogRefreshError.CatalogRejected, assertIs<RecipeCatalogRefreshResult.Rejected>(service.refresh(proposal)).error)
        assertEquals(1, downloader.urls.size)

        downloader.reset(signedEnvelope(signing, 11, listOf(Artifact("recipe.one", artifact)), expires = now))
        assertEquals(RecipeCatalogRefreshError.CatalogRejected, assertIs<RecipeCatalogRefreshResult.Rejected>(service.refresh(proposal)).error)
        assertEquals(1, downloader.urls.size)
    }

    @Test
    fun portableOriginAndSizePolicyRejectBeforeArtifactRequest() = runTest {
        val signing = signingMaterial()
        val store = emptyStore()
        val downloader = FakeDownloader()
        val service = service(store, downloader)
        val proposal = proposal(signing)
        service.enroll(proposal)

        downloader.reset(signedEnvelope(signing, 1, listOf(Artifact("recipe.one", recipe("recipe.one"), url = "https://other.example.test/recipe.one.json"))))
        assertEquals(RecipeCatalogRefreshError.ArtifactPolicyRejected, assertIs<RecipeCatalogRefreshResult.Rejected>(service.refresh(proposal)).error)
        assertEquals(listOf(catalogUrl), downloader.urls)

        downloader.reset(signedEnvelope(signing, 1, listOf(Artifact("recipe.one", recipe("recipe.one"), size = 64 * 1024 + 1))))
        assertEquals(RecipeCatalogInstallError.ArtifactPolicyRejected, assertIs<RecipeCatalogInstallServiceResult.Rejected>(service.install(proposal, "recipe.one")).error)
        assertEquals(listOf(catalogUrl), downloader.urls)
    }

    @Test
    fun digestIdentitySuccessAndConflictFollowCoordinatorCommit() = runTest {
        val signing = signingMaterial()
        val good = recipe("recipe.one")
        val proposal = proposal(signing)

        val digestStore = emptyStore(); val digestDownloader = FakeDownloader(signedEnvelope(signing, 1, listOf(Artifact("recipe.one", good))))
        service(digestStore, digestDownloader).enroll(proposal); digestDownloader.artifacts[artifactUrl("recipe.one")] = "tampered".encodeToByteArray()
        assertEquals(RecipeCatalogInstallError.ArtifactRejected, assertIs<RecipeCatalogInstallServiceResult.Rejected>(service(digestStore, digestDownloader).install(proposal, "recipe.one")).error)

        val identityStore = emptyStore(); val other = recipe("other.id"); val identityDownloader = FakeDownloader(signedEnvelope(signing, 1, listOf(Artifact("recipe.one", other))))
        service(identityStore, identityDownloader).enroll(proposal); identityDownloader.artifacts[artifactUrl("recipe.one")] = other
        assertEquals(RecipeCatalogInstallError.ArtifactRejected, assertIs<RecipeCatalogInstallServiceResult.Rejected>(service(identityStore, identityDownloader).install(proposal, "recipe.one")).error)

        val installed = emptyStore(); val installedDownloader = FakeDownloader(signedEnvelope(signing, 1, listOf(Artifact("recipe.one", good))))
        val installedService = service(installed, installedDownloader); installedService.enroll(proposal); installedDownloader.artifacts[artifactUrl("recipe.one")] = good
        assertIs<RecipeCatalogInstallServiceResult.Applied>(installedService.install(proposal, "recipe.one"))

        val raced = RaceStore(emptyStore()); val raceDownloader = FakeDownloader(signedEnvelope(signing, 1, listOf(Artifact("recipe.one", good))))
        val raceService = service(raced, raceDownloader); raceService.enroll(proposal); raceDownloader.artifacts[artifactUrl("recipe.one")] = good
        assertEquals(RecipeCatalogInstallServiceResult.Conflict, raceService.install(proposal, "recipe.one"))
    }

    @Test
    fun downloaderCancellationPropagates() = runTest {
        val signing = signingMaterial(); val proposal = proposal(signing); val store = emptyStore()
        val downloader = FakeDownloader().also { it.failure = CancellationException("cancelled") }
        val service = service(store, downloader); service.enroll(proposal)

        assertFailsWith<CancellationException> { service.refresh(proposal) }
    }

    private fun service(store: RecipeInstallationStore, downloader: RecipeCatalogDownloader) = RecipeCatalogInstallationService(
        store, downloader, RecipeInstallationClock { now }, RecipeCatalogMonotonicClock { 0 }, RecipeCatalogInstallationPolicy(1_000),
    )

    private fun emptyStore(): InMemoryRecipeInstallationStore = InMemoryRecipeInstallationStore(emptyList(), RecipeInstallationClock { now })

    private suspend fun signingMaterial(): SigningMaterial {
        val pair = provider.get(EdDSA).keyPairGenerator(EdDSA.Curve.Ed25519).generateKey()
        return SigningMaterial(
            TrustedCatalogKey(catalogId, "catalog-key", pair.publicKey.encodeToByteArray(EdDSA.PublicKey.Format.RAW), TrustedCatalogKeyState.Active),
            { frame -> pair.privateKey.signatureGenerator().generateSignature(frame) },
        )
    }

    private fun proposal(signing: SigningMaterial): CatalogEnrollmentCode = requireNotNull(
        CatalogEnrollmentCode.parse("yokan-catalog:v1:$catalogId:${b64(catalogUrl.encodeToByteArray())}:${signing.key.keyId}:${b64(signing.key.rawEd25519PublicKey)}"),
    )

    private suspend fun signedEnvelope(signing: SigningMaterial, revision: Long, artifacts: List<Artifact>, expires: Long = now + 600): ByteArray {
        val entries = mutableListOf<String>()
        for (artifact in artifacts) {
            entries += """{"stableId":"${artifact.id}","releaseVersion":"1.0","sha256":"${artifact.hash ?: sha256(artifact.bytes).toHexString()}","sizeBytes":${artifact.size ?: artifact.bytes.size},"url":"${artifact.url ?: artifactUrl(artifact.id)}"}"""
        }
        val payload = """{"formatVersion":"1","artifacts":[${entries.joinToString(",")}]}""".encodeToByteArray()
        val hash = sha256(payload)
        val frame = "yokan.recipe-catalog.ed25519.v2\u0000".encodeToByteArray() + u16(catalogId.encodeToByteArray().size) + catalogId.encodeToByteArray() +
            u16(signing.key.keyId.encodeToByteArray().size) + signing.key.keyId.encodeToByteArray() + i64(revision) + i64(now - 60) + i64(expires) + u32(payload.size) + hash
        return byteArrayOf('Y'.code.toByte(), 'R'.code.toByte(), 'C'.code.toByte(), '2'.code.toByte(), 2) + u16(catalogId.encodeToByteArray().size) + catalogId.encodeToByteArray() +
            u16(signing.key.keyId.encodeToByteArray().size) + signing.key.keyId.encodeToByteArray() + i64(revision) + i64(now - 60) + i64(expires) + u32(payload.size) + hash + signing.sign(frame) + payload
    }

    private fun artifactUrl(id: String) = "https://catalog.example.test/$id.recipe.json"
    private fun recipe(id: String): ByteArray = validBundle(id).encodeToByteArray()
    private suspend fun sha256(bytes: ByteArray) = provider.get(SHA256).hasher().hash(bytes)
    private fun ByteArray.toHexString() = joinToString("") { (it.toInt() and 255).toString(16).padStart(2, '0') }
    private fun u16(value: Int) = byteArrayOf((value ushr 8).toByte(), value.toByte())
    private fun u32(value: Int) = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
    private fun i64(value: Long) = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
    private fun b64(bytes: ByteArray): String = buildString { var index = 0; while (index < bytes.size) { val first = bytes[index++].toInt() and 255; val second = if (index < bytes.size) bytes[index++].toInt() and 255 else -1; val third = if (index < bytes.size) bytes[index++].toInt() and 255 else -1; append(alphabet[first ushr 2]); append(alphabet[((first and 3) shl 4) or if (second < 0) 0 else second ushr 4]); if (second >= 0) append(alphabet[((second and 15) shl 2) or if (third < 0) 0 else third ushr 6]); if (third >= 0) append(alphabet[third and 63]) } }

    private data class Artifact(val id: String, val bytes: ByteArray, val url: String? = null, val size: Int? = null, val hash: String? = null)
    private data class SigningMaterial(val key: TrustedCatalogKey, val sign: suspend (ByteArray) -> ByteArray)

    private inner class FakeDownloader(var catalog: ByteArray = byteArrayOf()) : RecipeCatalogDownloader {
        val urls = mutableListOf<String>()
        val artifacts = mutableMapOf<String, ByteArray>()
        var failure: Throwable? = null
        fun reset(envelope: ByteArray) { catalog = envelope; artifacts.clear(); urls.clear(); failure = null }
        override suspend fun download(url: String, maxBytes: Int, deadlineMillis: Long): ByteArray {
            urls += url
            failure?.let { throw it }
            return (if (url == catalogUrl) catalog else artifacts[url] ?: error("unexpected artifact")).copyOf()
        }
    }

    private class RaceStore(private val delegate: InMemoryRecipeInstallationStore) : RecipeInstallationStore {
        override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy) = delegate.enrollIfAbsent(catalogId, trustPolicy)
        override suspend fun readCatalog(catalogId: String) = delegate.readCatalog(catalogId)
        override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult {
            delegate.uninstall(candidate.catalogId, "missing")
            return delegate.commitInstall(expectedGeneration, candidate)
        }
    }

    private companion object { const val alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeExtensionRuntimeServiceTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeExtensionRuntimeServiceTest.kt) · test / fixture · 123 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: class RecipeExtensionRuntimeServiceTest {
15: fun factoryRoutesOnlyValidRecipeDiscriminatorAndNeverFallsBack() = runTest {
42: fun invalidPilotInputsAndFiltersFailClosedWithoutResolvingOrPlayback() = runTest {
47: object : RecipeCapabilityBroker { override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult = RecipeBrokerResult.Failed },
57: fun mismatchedManifestIdentityFailsBeforeBroker() = runTest {
66: object : RecipeCapabilityBroker {
67: override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult {
79: fun installedRecipeGetsDeclaredOriginsOffsetPagingAndFallbackPointers() = runTest {
102: object : RecipeCapabilityBroker {
103: override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeExtensionRuntimeServiceTest.kt) · SHA-256 `3efb4ec3c8c0d6392244074002250b4e2e4e1ac48e97709e156103c749e984f0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.services.http.HttpService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlinx.coroutines.test.runTest
import eu.friedcutlet.yokan.services.extensions.DynamicExtensionRuntimeFactory
import eu.friedcutlet.yokan.services.extensions.SourceFilter

class RecipeExtensionRuntimeServiceTest {
    @Test
    fun factoryRoutesOnlyValidRecipeDiscriminatorAndNeverFallsBack() = runTest {
        var resolves = 0
        val factory = DynamicExtensionRuntimeFactory(
            InMemoryYokanDatabase(),
            HttpService { error("legacy runtime must not be reached") },
            recipeRuntime = RecipeRuntimeBindings(
                resolver = VerifiedRecipeBundleResolver { _, _ -> resolves++; null },
                broker = object : RecipeCapabilityBroker { override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult = error("broker must not be reached") },
                policy = RecipeExecutionPolicy(emptyMap()),
            ),
        )
        val valid = RecipeSourceReference("catalog", "recipe")
        val source = DbSource(
            id = recipeSourceId(valid.catalogId, valid.stableId),
            typeSource = RecipeSourceDiscriminator,
            additionalParams = recipeSourceReference(valid.catalogId, valid.stableId),
            sourceCode = "legacy javascript must not execute",
        )
        assertEquals(emptyList(), factory.create(source).popular(1).items)
        assertEquals(1, resolves)

        val malformed = source.copy(additionalParams = "not-a-recipe")
        assertEquals(emptyList(), factory.create(malformed).popular(1).items)
        assertEquals(1, resolves)
    }

    @Test
    fun invalidPilotInputsAndFiltersFailClosedWithoutResolvingOrPlayback() = runTest {
        var resolves = 0
        val service = RecipeExtensionRuntimeService(
            DbSource(sourceCode = "forbidden"), "catalog", "recipe",
            VerifiedRecipeBundleResolver { _, _ -> resolves++; null },
            object : RecipeCapabilityBroker { override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult = RecipeBrokerResult.Failed },
            RecipeExecutionPolicy(emptyMap()),
        )
        assertEquals(emptyList(), service.popular(0).items)
        assertEquals(emptyList(), service.search("q", 1, listOf(SourceFilter("f", "f", "f"))).items)
        assertEquals(emptyList(), service.videoList("1"))
        assertEquals(0, resolves)
    }

    @Test
    fun mismatchedManifestIdentityFailsBeforeBroker() = runTest {
        var requests = 0
        val service = RecipeExtensionRuntimeService(
            DbSource(), "catalog", "expected.recipe",
            VerifiedRecipeBundleResolver { _, _ ->
                DeclarativeExtensionBundle(
                    ExtensionRecipeManifest(RecipeFormatVersion.V21, "other.recipe", "Other", emptyList(), emptyList()),
                )
            },
            object : RecipeCapabilityBroker {
                override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult {
                    requests++
                    return RecipeBrokerResult.Failed
                }
            },
            RecipeExecutionPolicy(emptyMap()),
        )
        assertEquals(emptyList(), service.popular(1).items)
        assertEquals(0, requests)
    }

    @Test
    fun installedRecipeGetsDeclaredOriginsOffsetPagingAndFallbackPointers() = runTest {
        val bundle = assertIs<RecipeBundleDecodeResult.Accepted>(StrictRecipeBundleDecoder.decode(
            """
            {"manifest":{"formatVersion":"2.1","id":"dex","name":"Dex","declaredCapabilities":["networkRead"],"declaredOrigins":[{"id":"api","origin":"https://api.example.test"}]},
             "entrypoints":{
              "popular":{"inputs":["pageOffset"],"url":{"origin":{"originId":"api"},"path":[{"value":"literal","text":"/manga?limit=2&offset="},{"value":"hostInput","input":"pageOffset"}]},
                "projection":{"pointer":"/data","mode":"many","fields":{"id":"/id","title":["/t/en","/t/ja-ro"]}},"terminal":{"type":"listing","pageSize":2}},
              "detail":{"inputs":["itemId"],"url":{"origin":{"originId":"api"},"path":[{"value":"literal","text":"/manga/"},{"value":"hostInput","input":"itemId"}]},
                "projection":{"pointer":"/data","mode":"one","fields":{"id":"/id","title":"/t/en"}},"terminal":{"type":"detail"}},
              "episodes":{"inputs":["itemId"],"url":{"origin":{"originId":"api"},"path":[{"value":"literal","text":"/feed/"},{"value":"hostInput","input":"itemId"}]},
                "projection":{"pointer":"/data","mode":"many","fields":{"id":"/id","number":["/n","/title"]}},"terminal":{"type":"episodes"}}}}
            """.trimIndent().encodeToByteArray(),
        )).bundle
        val responses = mapOf(
            "/manga?limit=2&offset=4" to """{"data":[{"id":"a1-b2","t":{"en":"English"}},{"id":"c3","t":{"ja-ro":"Romaji"}}]}""",
            "/manga?limit=2&offset=0" to """{"data":[{"id":"x","t":{"ko":"untitled in every fallback"}}]}""",
            "/manga/a1-b2" to """{"data":{"id":"a1-b2","t":{"en":"English"}}}""",
            "/feed/a1-b2" to """{"data":[{"id":"e1","n":"12"},{"id":"e2","title":"Oneshot"}]}""",
        )
        val requested = mutableListOf<String>()
        val service = RecipeExtensionRuntimeService(
            DbSource(), "catalog", "dex",
            VerifiedRecipeBundleResolver { _, _ -> bundle },
            object : RecipeCapabilityBroker {
                override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult {
                    requested += request.url
                    return responses[request.pathAndQuery]?.let { RecipeBrokerResult.Document(it.encodeToByteArray()) } ?: RecipeBrokerResult.HttpFailure
                }
            },
            // Installed declarations do not grant access; the host must grant each origin explicitly.
            RecipeExecutionPolicy(mapOf("api" to "https://api.example.test")),
        )

        val page3 = service.popular(3)
        assertEquals(listOf("English" to "a1-b2", "Romaji" to "c3"), page3.items.map { it.title to it.url })
        assertEquals("https://api.example.test/manga?limit=2&offset=4", requested.first())
        // One row without any fallback title rejects the whole page instead of inventing a title.
        assertEquals(emptyList(), service.popular(1).items)
        assertEquals(false, service.supportsLatest())

        val detail = service.detail("a1-b2")
        assertEquals("English", detail.title)
        assertEquals(listOf("12" to "e1", "Oneshot" to "e2"), detail.chapters.map { it.title to it.url })
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeInstallationCoordinatorTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeInstallationCoordinatorTest.kt) · test / fixture · 386 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
14: class RecipeInstallationCoordinatorTest {
20: fun installsVerifiedCatalogArtifactAtomically() = runTest {
35: fun identityDigestAndRecipeFailuresLeaveStateUnchanged() = runTest {
53: fun rejectsRollbackAndConflictingEqualRevisions() = runTest {
66: fun equalRevisionReinstallIsUnchangedAndCanInstallAnotherArtifact() = runTest {
82: fun higherSignedCatalogRevisionAdvancesReplayForIdenticalArtifactAndRelease() = runTest {
95: fun uninstallAndRevocationRacesReturnConflict() = runTest {
116: fun commitClockRechecksCatalogAndKeyExpiryWithoutPublishingState() = runTest {
136: fun storeErrorsAndCompetingCasOrdersFailClosed() = runTest {
164: fun enrollmentIsCreateOnlyAndRejectedPoliciesDoNotMutate() = runTest {
195: fun enrollmentAndCommitQuotasRejectAtomically() = runTest {
233: fun replacementValidationAndEmergencyRevocationPreserveCatalogState() = runTest {
260: fun wrongStoreIdentityAndWireOverlimitEnrollmentFailClosed() = runTest {
270: fun failedWriteIsAtomicAndInputsAreDefensivelyCopied() = runTest {
283: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = mutable.enrollIfAbsent(catalogId, trustPolicy)
284: override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? {
289: override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult =
299: private suspend fun assertEmpty(store: InMemoryRecipeInstallationStore) {
305: private fun assertRejected(result: RecipeInstallationResult, code: RecipeInstallationErrorCode) {
309: private fun store(signing: SigningMaterial, clock: RecipeInstallationClock = TestClock(now)): InMemoryRecipeInstallationStore = InMemoryRecipeInstallationStore(
314: private fun emptyStore(limits: RecipeInstallationStoreLimits = RecipeInstallationStoreLimits()): InMemoryRecipeInstallationStore =
317: private suspend fun signingMaterial(validUntil: Long? = null): SigningMaterial {
325: private suspend fun signedEnvelope(signing: SigningMaterial, revision: Long, artifacts: List<Artifact>, expires: Long = now + 600): ByteArray {
335: private fun recipe(id: String): ByteArray = validBundle(id).encodeToByteArray()
336: private suspend fun sha256(bytes: ByteArray): ByteArray = provider.get(SHA256).hasher().hash(bytes)
337: private fun manualFrame(catalog: String, key: String, revision: Long, issued: Long, expires: Long, payloadLength: Int, hash: ByteArray): ByteArray =
339: private fun manualEnvelope(catalog: String, key: String, revision: Long, issued: Long, expires: Long, hash: ByteArray, signature: ByteArray, payload: ByteArray): ByteArray =
341: private fun u16(value: Int) = byteArrayOf((value ushr 8).toByte(), value.toByte())
342: private fun u32(value: Int) = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
343: private fun i64(value: Long) = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
344: private fun ByteArray.toHexString(): String = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
345: private data class Artifact(val id: String, val bytes: ByteArray, val release: String)
346: private data class SigningMaterial(val key: TrustedCatalogKey, val sign: suspend (ByteArray) -> ByteArray)
348: private fun candidate(snapshot: CatalogInstallationSnapshot, revision: Long, signing: SigningMaterial): RecipeInstallCandidate = RecipeInstallCandidate(
360: private class MutatingStore(private val delegate: RecipeInstallationStore, private val mutate: suspend () -> Unit) : RecipeInstallationStore {
361: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = delegate.enrollIfAbsent(catalogId, trustPolicy)
362: override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = delegate.readCatalog(catalogId)
363: override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult {
369: private class ThrowingReadStore : RecipeInstallationStore {
370: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = error("enroll")
371: override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = error("read")
372: override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = error("commit")
375: private class ThrowingCommitStore(private val delegate: RecipeInstallationStore) : RecipeInstallationStore {
376: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = delegate.enrollIfAbsent(catalogId, trustPolicy)
377: override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = delegate.readCatalog(catalogId)
378: override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = error("commit")
381: private class WrongIdStore : RecipeInstallationStore {
382: override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = RecipeCatalogEnrollmentResult.Rejected
383: override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot = CatalogInstallationSnapshot("other.catalog", CatalogSnapshotGeneration(0), CatalogTrustPolicy("other.catalog", emptyList()), null, emptyMap())
384: override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = error("commit")
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/RecipeInstallationCoordinatorTest.kt) · SHA-256 `c26c93cb3fb0bee834af42dff553162b15e25981620e07423895742dd41b1da6`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import dev.whyoleg.cryptography.CryptographyProvider
import dev.whyoleg.cryptography.CryptographyProviderApi
import dev.whyoleg.cryptography.algorithms.EdDSA
import dev.whyoleg.cryptography.algorithms.SHA256
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertNull

@OptIn(CryptographyProviderApi::class)
class RecipeInstallationCoordinatorTest {
    private val provider = CryptographyProvider.Default
    private val now = 1_700_000_000L
    private val catalogId = "catalog.primary"

    @Test
    fun installsVerifiedCatalogArtifactAtomically() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        val envelope = signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1.0")))
        val store = store(signing)

        val result = RecipeInstallationCoordinator(store).install(catalogId, envelope, artifact, "recipe.one", now)

        assertEquals(10, assertIs<RecipeInstallationResult.Applied>(result).record.catalogRevision)
        val snapshot = store.readCatalog(catalogId)!!
        assertEquals(10, snapshot.acceptanceState!!.highestRevision)
        assertEquals(artifact.toList(), snapshot.installedRecords.getValue("recipe.one").artifactBytes.toList())
    }

    @Test
    fun identityDigestAndRecipeFailuresLeaveStateUnchanged() = runTest {
        val signing = signingMaterial()
        val good = recipe("recipe.one")
        val identityStore = store(signing)
        assertRejected(RecipeInstallationCoordinator(identityStore).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", recipe("other.id"), "1"))), recipe("other.id"), "recipe.one", now), RecipeInstallationErrorCode.ArtifactIdentityMismatch)
        assertEmpty(identityStore)

        val digestStore = store(signing)
        assertRejected(RecipeInstallationCoordinator(digestStore).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", good, "1"))), "tampered".encodeToByteArray(), "recipe.one", now), RecipeInstallationErrorCode.ArtifactVerificationFailed)
        assertEmpty(digestStore)

        val recipeStore = store(signing)
        val malformed = "not-json".encodeToByteArray()
        assertRejected(RecipeInstallationCoordinator(recipeStore).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", malformed, "1"))), malformed, "recipe.one", now), RecipeInstallationErrorCode.RecipeDecodeFailed)
        assertEmpty(recipeStore)
    }

    @Test
    fun rejectsRollbackAndConflictingEqualRevisions() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        val store = store(signing)
        val coordinator = RecipeInstallationCoordinator(store)
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))
        assertRejected(coordinator.install(catalogId, signedEnvelope(signing, 9, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now), RecipeInstallationErrorCode.CatalogVerificationFailed)
        val changed = recipe("recipe.one").decodeToString().replace("Example", "Changed").encodeToByteArray()
        assertRejected(coordinator.install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", changed, "1"))), changed, "recipe.one", now), RecipeInstallationErrorCode.CatalogVerificationFailed)
        assertEquals(10, store.readCatalog(catalogId)!!.acceptanceState!!.highestRevision)
    }

    @Test
    fun equalRevisionReinstallIsUnchangedAndCanInstallAnotherArtifact() = runTest {
        val signing = signingMaterial()
        val first = recipe("recipe.one")
        val second = recipe("recipe.two")
        val envelope = signedEnvelope(signing, 10, listOf(Artifact("recipe.one", first, "1"), Artifact("recipe.two", second, "1")))
        val store = store(signing)
        val coordinator = RecipeInstallationCoordinator(store)
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, envelope, first, "recipe.one", now))
        assertIs<RecipeInstallationResult.Unchanged>(coordinator.install(catalogId, envelope, first, "recipe.one", now))
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, envelope, second, "recipe.two", now))
        assertEquals(setOf("recipe.one", "recipe.two"), store.readCatalog(catalogId)!!.installedRecords.keys)
        assertEquals(true, store.uninstall(catalogId, "recipe.one"))
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, envelope, first, "recipe.one", now))
    }

    @Test
    fun higherSignedCatalogRevisionAdvancesReplayForIdenticalArtifactAndRelease() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        val store = store(signing)
        val coordinator = RecipeInstallationCoordinator(store)
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1.0"))), artifact, "recipe.one", now))
        val result = assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, signedEnvelope(signing, 11, listOf(Artifact("recipe.one", artifact, "1.0"))), artifact, "recipe.one", now))
        assertEquals(11, result.record.catalogRevision)
        assertEquals("1.0", result.record.releaseVersion)
        assertEquals(11, store.readCatalog(catalogId)!!.acceptanceState!!.highestRevision)
    }

    @Test
    fun uninstallAndRevocationRacesReturnConflict() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        val initial = store(signing)
        val coordinator = RecipeInstallationCoordinator(initial)
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))
        val uninstallRace = MutatingStore(initial) { initial.uninstall(catalogId, "recipe.one") }
        assertEquals(RecipeInstallationResult.Conflict, RecipeInstallationCoordinator(uninstallRace).install(catalogId, signedEnvelope(signing, 11, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))

        val revocationStore = store(signing)
        val revoked = signing.key.copy(state = TrustedCatalogKeyState.Revoked)
        val revocationRace = MutatingStore(revocationStore) { revocationStore.replaceTrustPolicy(catalogId, CatalogTrustPolicy(catalogId, listOf(revoked))) }
        assertEquals(RecipeInstallationResult.Conflict, RecipeInstallationCoordinator(revocationRace).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))

        val absentStore = store(signing)
        val absentRace = MutatingStore(absentStore) { absentStore.uninstall(catalogId, "missing") }
        assertEquals(RecipeInstallationResult.Conflict, RecipeInstallationCoordinator(absentRace).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))
        assertIs<RecipeInstallationResult.Applied>(RecipeInstallationCoordinator(absentStore).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))
    }

    @Test
    fun commitClockRechecksCatalogAndKeyExpiryWithoutPublishingState() = runTest {
        val artifact = recipe("recipe.one")
        val catalogClock = TestClock(now)
        val signing = signingMaterial()
        val catalogStore = store(signing, catalogClock)
        val catalogRace = MutatingStore(catalogStore) { catalogClock.value = now + 1 }
        assertRejected(RecipeInstallationCoordinator(catalogRace).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1")), expires = now + 1), artifact, "recipe.one", now), RecipeInstallationErrorCode.StoreRejected)
        assertEmpty(catalogStore)
        assertEquals(0, catalogStore.readCatalog(catalogId)!!.generation.value)

        val keyClock = TestClock(now)
        val expiringKey = signingMaterial(validUntil = now)
        val keyStore = store(expiringKey, keyClock)
        val keyRace = MutatingStore(keyStore) { keyClock.value = now + 1 }
        assertRejected(RecipeInstallationCoordinator(keyRace).install(catalogId, signedEnvelope(expiringKey, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now), RecipeInstallationErrorCode.StoreRejected)
        assertEmpty(keyStore)
        assertEquals(0, keyStore.readCatalog(catalogId)!!.generation.value)
    }

    @Test
    fun storeErrorsAndCompetingCasOrdersFailClosed() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        assertRejected(RecipeInstallationCoordinator(ThrowingReadStore()).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now), RecipeInstallationErrorCode.StoreFailure)
        val untouched = store(signing)
        assertRejected(RecipeInstallationCoordinator(ThrowingCommitStore(untouched)).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now), RecipeInstallationErrorCode.StoreFailure)
        assertEmpty(untouched)

        val highFirst = store(signing)
        val highSnapshot = highFirst.readCatalog(catalogId)!!
        val high = candidate(highSnapshot, 11, signing)
        val staleLow = candidate(highSnapshot, 10, signing)
        assertEquals(RecipeInstallCommitResult.Applied, highFirst.commitInstall(highSnapshot.generation, high))
        assertEquals(RecipeInstallCommitResult.Conflict, highFirst.commitInstall(highSnapshot.generation, staleLow))
        val freshLow = candidate(highFirst.readCatalog(catalogId)!!, 10, signing)
        assertEquals(RecipeInstallCommitResult.Rejected, highFirst.commitInstall(highFirst.readCatalog(catalogId)!!.generation, freshLow))

        val lowFirst = store(signing)
        val lowSnapshot = lowFirst.readCatalog(catalogId)!!
        val low = candidate(lowSnapshot, 10, signing)
        val staleHigh = candidate(lowSnapshot, 11, signing)
        assertEquals(RecipeInstallCommitResult.Applied, lowFirst.commitInstall(lowSnapshot.generation, low))
        assertEquals(RecipeInstallCommitResult.Conflict, lowFirst.commitInstall(lowSnapshot.generation, staleHigh))
        val freshHighSnapshot = lowFirst.readCatalog(catalogId)!!
        assertEquals(RecipeInstallCommitResult.Applied, lowFirst.commitInstall(freshHighSnapshot.generation, candidate(freshHighSnapshot, 11, signing)))
    }

    @Test
    fun enrollmentIsCreateOnlyAndRejectedPoliciesDoNotMutate() = runTest {
        val signing = signingMaterial()
        val replacement = signingMaterial()
        val enrolled = emptyStore()
        assertEquals(RecipeCatalogEnrollmentResult.Created, enrolled.enrollIfAbsent(catalogId, CatalogTrustPolicy(catalogId, listOf(signing.key))))
        val artifact = recipe("recipe.one")
        assertIs<RecipeInstallationResult.Applied>(RecipeInstallationCoordinator(enrolled).install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))
        val before = enrolled.readCatalog(catalogId)!!
        assertEquals(RecipeCatalogEnrollmentResult.AlreadyExists, enrolled.enrollIfAbsent(catalogId, CatalogTrustPolicy(catalogId, listOf(replacement.key))))
        val after = enrolled.readCatalog(catalogId)!!
        assertEquals(before.generation.value, after.generation.value)
        assertEquals(before.acceptanceState!!.highestRevision, after.acceptanceState!!.highestRevision)
        assertEquals(signing.key.rawEd25519PublicKey.toList(), after.trustPolicy.trustedKeys.single().rawEd25519PublicKey.toList())

        val rejected = emptyStore()
        val invalidPolicies = listOf(
            " " to CatalogTrustPolicy(" ", listOf(signing.key.copy(catalogId = " "))),
            catalogId to CatalogTrustPolicy(catalogId, emptyList()),
            catalogId to CatalogTrustPolicy(catalogId, listOf(signing.key.copy(rawEd25519PublicKey = ByteArray(31)))),
            catalogId to CatalogTrustPolicy(catalogId, listOf(signing.key, signing.key.copy())),
            catalogId to CatalogTrustPolicy(catalogId, listOf(signing.key.copy(state = TrustedCatalogKeyState.Revoked))),
            catalogId to CatalogTrustPolicy(catalogId, listOf(signing.key.copy(validFromEpochSeconds = 2, validUntilEpochSeconds = 1))),
            catalogId to CatalogTrustPolicy(catalogId, listOf(signing.key.copy(catalogId = "other.catalog"))),
        )
        invalidPolicies.forEach { (id, policy) ->
            assertEquals(RecipeCatalogEnrollmentResult.Rejected, rejected.enrollIfAbsent(id, policy))
        }
        assertNull(rejected.readCatalog(catalogId))
    }

    @Test
    fun enrollmentAndCommitQuotasRejectAtomically() = runTest {
        val signing = signingMaterial()
        val secondCatalogKey = signing.key.copy(catalogId = "catalog.second")
        val catalogLimited = emptyStore(RecipeInstallationStoreLimits(maxEnrolledCatalogs = 1, maxKeysPerCatalog = 2, maxInstalledRecipesPerCatalog = 2, maxArtifactBytesPerCatalog = 1024))
        assertEquals(RecipeCatalogEnrollmentResult.Created, catalogLimited.enrollIfAbsent(catalogId, CatalogTrustPolicy(catalogId, listOf(signing.key))))
        assertEquals(RecipeCatalogEnrollmentResult.Rejected, catalogLimited.enrollIfAbsent("catalog.second", CatalogTrustPolicy("catalog.second", listOf(secondCatalogKey))))

        val keyLimited = emptyStore(RecipeInstallationStoreLimits(maxEnrolledCatalogs = 2, maxKeysPerCatalog = 1, maxInstalledRecipesPerCatalog = 2, maxArtifactBytesPerCatalog = 1024))
        assertEquals(RecipeCatalogEnrollmentResult.Rejected, keyLimited.enrollIfAbsent(catalogId, CatalogTrustPolicy(catalogId, listOf(signing.key, signing.key.copy(keyId = "second-key")))))
        assertNull(keyLimited.readCatalog(catalogId))

        val first = recipe("recipe.one")
        val second = recipe("recipe.two")
        val recipeLimited = emptyStore(RecipeInstallationStoreLimits(2, 2, 1, 1024 * 1024))
        assertEquals(RecipeCatalogEnrollmentResult.Created, recipeLimited.enrollIfAbsent(catalogId, CatalogTrustPolicy(catalogId, listOf(signing.key))))
        val coordinator = RecipeInstallationCoordinator(recipeLimited)
        val pairEnvelope = signedEnvelope(signing, 10, listOf(Artifact("recipe.one", first, "1"), Artifact("recipe.two", second, "1")))
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, pairEnvelope, first, "recipe.one", now))
        assertRejected(coordinator.install(catalogId, pairEnvelope, second, "recipe.two", now), RecipeInstallationErrorCode.StoreRejected)
        val recipeSnapshot = recipeLimited.readCatalog(catalogId)!!
        assertEquals(1, recipeSnapshot.generation.value)
        assertEquals(setOf("recipe.one"), recipeSnapshot.installedRecords.keys)
        assertEquals(10, recipeSnapshot.acceptanceState!!.highestRevision)

        val byteLimited = emptyStore(RecipeInstallationStoreLimits(2, 2, 2, first.size.toLong()))
        assertEquals(RecipeCatalogEnrollmentResult.Created, byteLimited.enrollIfAbsent(catalogId, CatalogTrustPolicy(catalogId, listOf(signing.key))))
        val byteCoordinator = RecipeInstallationCoordinator(byteLimited)
        assertIs<RecipeInstallationResult.Applied>(byteCoordinator.install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", first, "1"))), first, "recipe.one", now))
        assertIs<RecipeInstallationResult.Applied>(byteCoordinator.install(catalogId, signedEnvelope(signing, 11, listOf(Artifact("recipe.one", first, "1"))), first, "recipe.one", now))
        val larger = recipe("recipe.one").decodeToString().replace("Example", "Longer example name").encodeToByteArray()
        assertRejected(byteCoordinator.install(catalogId, signedEnvelope(signing, 12, listOf(Artifact("recipe.one", larger, "1"))), larger, "recipe.one", now), RecipeInstallationErrorCode.StoreRejected)
        val byteSnapshot = byteLimited.readCatalog(catalogId)!!
        assertEquals(2, byteSnapshot.generation.value)
        assertEquals(11, byteSnapshot.acceptanceState!!.highestRevision)
        assertEquals(first.toList(), byteSnapshot.installedRecords.getValue("recipe.one").artifactBytes.toList())
    }

    @Test
    fun replacementValidationAndEmergencyRevocationPreserveCatalogState() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        val store = store(signing)
        val coordinator = RecipeInstallationCoordinator(store)
        assertIs<RecipeInstallationResult.Applied>(coordinator.install(catalogId, signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1"))), artifact, "recipe.one", now))
        val before = store.readCatalog(catalogId)!!
        val pending = candidate(before, 11, signing)
        val tooManyKeys = CatalogTrustPolicy(catalogId, List(9) { signing.key.copy(keyId = "key-$it") })
        assertEquals(false, store.replaceTrustPolicy(catalogId, tooManyKeys))
        assertEquals(false, store.replaceTrustPolicy(catalogId, CatalogTrustPolicy(catalogId, listOf(signing.key.copy(catalogId = "other.catalog")))))
        val unchanged = store.readCatalog(catalogId)!!
        assertEquals(before.generation.value, unchanged.generation.value)
        assertEquals(before.acceptanceState!!.highestRevision, unchanged.acceptanceState!!.highestRevision)
        assertEquals(before.installedRecords.keys, unchanged.installedRecords.keys)

        val revoked = CatalogTrustPolicy(catalogId, listOf(signing.key.copy(state = TrustedCatalogKeyState.Revoked)))
        assertEquals(true, store.replaceTrustPolicy(catalogId, revoked))
        val after = store.readCatalog(catalogId)!!
        assertEquals(before.generation.value + 1, after.generation.value)
        assertEquals(before.acceptanceState!!.highestRevision, after.acceptanceState!!.highestRevision)
        assertEquals(before.installedRecords.keys, after.installedRecords.keys)
        assertEquals(TrustedCatalogKeyState.Revoked, after.trustPolicy.trustedKeys.single().state)
        assertEquals(RecipeInstallCommitResult.Conflict, store.commitInstall(before.generation, pending))
    }

    @Test
    fun wrongStoreIdentityAndWireOverlimitEnrollmentFailClosed() = runTest {
        val signing = signingMaterial()
        val overlimitId = "a".repeat(65)
        val empty = emptyStore()
        assertEquals(RecipeCatalogEnrollmentResult.Rejected, empty.enrollIfAbsent(overlimitId, CatalogTrustPolicy(overlimitId, listOf(signing.key.copy(catalogId = overlimitId)))))
        assertNull(empty.readCatalog(overlimitId))
        assertRejected(RecipeInstallationCoordinator(WrongIdStore()).install(catalogId, byteArrayOf(), byteArrayOf(), "recipe.one", now), RecipeInstallationErrorCode.StoreFailure)
    }

    @Test
    fun failedWriteIsAtomicAndInputsAreDefensivelyCopied() = runTest {
        val signing = signingMaterial()
        val artifact = recipe("recipe.one")
        val envelope = signedEnvelope(signing, 10, listOf(Artifact("recipe.one", artifact, "1")))
        val failed = store(signing)
        failed.failNextCommit()
        assertRejected(RecipeInstallationCoordinator(failed).install(catalogId, envelope, artifact, "recipe.one", now), RecipeInstallationErrorCode.StoreRejected)
        assertEmpty(failed)

        val copiedEnvelope = envelope.copyOf()
        val copiedArtifact = artifact.copyOf()
        val mutable = store(signing)
        val mutatingRead = object : RecipeInstallationStore {
            override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = mutable.enrollIfAbsent(catalogId, trustPolicy)
            override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? {
                copiedEnvelope.fill(0)
                copiedArtifact.fill(0)
                return mutable.readCatalog(catalogId)
            }
            override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult =
                mutable.commitInstall(expectedGeneration, candidate)
        }
        assertIs<RecipeInstallationResult.Applied>(RecipeInstallationCoordinator(mutatingRead).install(catalogId, copiedEnvelope, copiedArtifact, "recipe.one", now))
        val installed = mutable.readCatalog(catalogId)!!.installedRecords.getValue("recipe.one")
        val leaked = installed.artifactBytes
        leaked.fill(0)
        assertEquals(artifact.toList(), mutable.readCatalog(catalogId)!!.installedRecords.getValue("recipe.one").artifactBytes.toList())
    }

    private suspend fun assertEmpty(store: InMemoryRecipeInstallationStore) {
        val snapshot = store.readCatalog(catalogId)!!
        assertNull(snapshot.acceptanceState)
        assertEquals(emptySet<String>(), snapshot.installedRecords.keys)
    }

    private fun assertRejected(result: RecipeInstallationResult, code: RecipeInstallationErrorCode) {
        assertEquals(code, assertIs<RecipeInstallationResult.Rejected>(result).code)
    }

    private fun store(signing: SigningMaterial, clock: RecipeInstallationClock = TestClock(now)): InMemoryRecipeInstallationStore = InMemoryRecipeInstallationStore(
        listOf(CatalogInstallationSnapshot(catalogId, CatalogSnapshotGeneration(0), CatalogTrustPolicy(catalogId, listOf(signing.key)), null, emptyMap())),
        clock,
    )

    private fun emptyStore(limits: RecipeInstallationStoreLimits = RecipeInstallationStoreLimits()): InMemoryRecipeInstallationStore =
        InMemoryRecipeInstallationStore(emptyList(), TestClock(now), limits)

    private suspend fun signingMaterial(validUntil: Long? = null): SigningMaterial {
        val pair = provider.get(EdDSA).keyPairGenerator(EdDSA.Curve.Ed25519).generateKey()
        return SigningMaterial(
            TrustedCatalogKey(catalogId, "catalog-key", pair.publicKey.encodeToByteArray(EdDSA.PublicKey.Format.RAW), TrustedCatalogKeyState.Active, validUntilEpochSeconds = validUntil),
            { frame -> pair.privateKey.signatureGenerator().generateSignature(frame) },
        )
    }

    private suspend fun signedEnvelope(signing: SigningMaterial, revision: Long, artifacts: List<Artifact>, expires: Long = now + 600): ByteArray {
        val entries = artifacts.map { artifact ->
            "{\"stableId\":\"${artifact.id}\",\"releaseVersion\":\"${artifact.release}\",\"sha256\":\"${sha256(artifact.bytes).toHexString()}\",\"sizeBytes\":${artifact.bytes.size},\"url\":\"https://example.test/${artifact.id}.json\"}"
        }
        val payload = """{"formatVersion":"1","artifacts":[${entries.joinToString(",")}] }""".encodeToByteArray()
        val hash = sha256(payload)
        val frame = manualFrame(catalogId, signing.key.keyId, revision, now - 60, expires, payload.size, hash)
        return manualEnvelope(catalogId, signing.key.keyId, revision, now - 60, expires, hash, signing.sign(frame), payload)
    }

    private fun recipe(id: String): ByteArray = validBundle(id).encodeToByteArray()
    private suspend fun sha256(bytes: ByteArray): ByteArray = provider.get(SHA256).hasher().hash(bytes)
    private fun manualFrame(catalog: String, key: String, revision: Long, issued: Long, expires: Long, payloadLength: Int, hash: ByteArray): ByteArray =
        "yokan.recipe-catalog.ed25519.v2\u0000".encodeToByteArray() + u16(catalog.encodeToByteArray().size) + catalog.encodeToByteArray() + u16(key.encodeToByteArray().size) + key.encodeToByteArray() + i64(revision) + i64(issued) + i64(expires) + u32(payloadLength) + hash
    private fun manualEnvelope(catalog: String, key: String, revision: Long, issued: Long, expires: Long, hash: ByteArray, signature: ByteArray, payload: ByteArray): ByteArray =
        byteArrayOf('Y'.code.toByte(), 'R'.code.toByte(), 'C'.code.toByte(), '2'.code.toByte(), 2) + u16(catalog.encodeToByteArray().size) + catalog.encodeToByteArray() + u16(key.encodeToByteArray().size) + key.encodeToByteArray() + i64(revision) + i64(issued) + i64(expires) + u32(payload.size) + hash + signature + payload
    private fun u16(value: Int) = byteArrayOf((value ushr 8).toByte(), value.toByte())
    private fun u32(value: Int) = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
    private fun i64(value: Long) = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
    private fun ByteArray.toHexString(): String = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
    private data class Artifact(val id: String, val bytes: ByteArray, val release: String)
    private data class SigningMaterial(val key: TrustedCatalogKey, val sign: suspend (ByteArray) -> ByteArray)

    private fun candidate(snapshot: CatalogInstallationSnapshot, revision: Long, signing: SigningMaterial): RecipeInstallCandidate = RecipeInstallCandidate(
        catalogId = catalogId,
        expectedTrustPolicy = snapshot.trustPolicy,
        expectedAcceptanceState = snapshot.acceptanceState,
        acceptedAcceptanceState = CatalogAcceptanceState(catalogId, revision, ByteArray(32) { revision.toByte() }),
        expiresAtEpochSeconds = now + 600,
        signingKeyId = signing.key.keyId,
        signingKeyValidFromEpochSeconds = signing.key.validFromEpochSeconds,
        signingKeyValidUntilEpochSeconds = signing.key.validUntilEpochSeconds,
        record = InstalledRecipeRecord(catalogId, "recipe.one", revision, "1", "0".repeat(64), 1, byteArrayOf(1)),
    )

    private class MutatingStore(private val delegate: RecipeInstallationStore, private val mutate: suspend () -> Unit) : RecipeInstallationStore {
        override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = delegate.enrollIfAbsent(catalogId, trustPolicy)
        override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = delegate.readCatalog(catalogId)
        override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult {
            mutate()
            return delegate.commitInstall(expectedGeneration, candidate)
        }
    }

    private class ThrowingReadStore : RecipeInstallationStore {
        override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = error("enroll")
        override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = error("read")
        override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = error("commit")
    }

    private class ThrowingCommitStore(private val delegate: RecipeInstallationStore) : RecipeInstallationStore {
        override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = delegate.enrollIfAbsent(catalogId, trustPolicy)
        override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot? = delegate.readCatalog(catalogId)
        override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = error("commit")
    }

    private class WrongIdStore : RecipeInstallationStore {
        override suspend fun enrollIfAbsent(catalogId: String, trustPolicy: CatalogTrustPolicy): RecipeCatalogEnrollmentResult = RecipeCatalogEnrollmentResult.Rejected
        override suspend fun readCatalog(catalogId: String): CatalogInstallationSnapshot = CatalogInstallationSnapshot("other.catalog", CatalogSnapshotGeneration(0), CatalogTrustPolicy("other.catalog", emptyList()), null, emptyMap())
        override suspend fun commitInstall(expectedGeneration: CatalogSnapshotGeneration, candidate: RecipeInstallCandidate): RecipeInstallCommitResult = error("commit")
    }
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/TestClock.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/TestClock.kt) · test / fixture · 5 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
3: internal class TestClock(var value: Long) : RecipeInstallationClock {
4: override fun nowEpochSeconds(): Long = value
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/TestClock.kt) · SHA-256 `d9d91c9cf272e6f0699fe587b115f3f0d496726df4b446496f28e8d58976eaf9`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

internal class TestClock(var value: Long) : RecipeInstallationClock {
    override fun nowEpochSeconds(): Long = value
}
```
[complete-source-end]: #

## `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalogTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalogTest.kt) · test / fixture · 205 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
13: class VerifiedRecipeCatalogTest {
19: fun verifiesManualSignedEnvelopeAndIntegrityOnlyArtifactMatch() = runTest {
30: fun manualProtocolVectorBindsDomainIdentityByteOrderLengthsAndSignature() = runTest {
49: fun rejectsPayloadAndSignatureTamperingIncludingRehashedUnsignedPayload() = runTest {
64: fun authenticatedPayloadUsesSharedBoundedStrictJsonPreflight() = runTest {
83: fun scopesKeysAndStateToExpectedStableCatalogIdentity() = runTest {
102: fun rejectsUnknownRevokedMalformedAndOutOfWindowKeys() = runTest {
112: fun authenticSignaturesCoverTimeLifetimeAndWireBoundaries() = runTest {
126: fun acceptsHigherRevisionAndSamePayloadFreshnessRenewalButRejectsRollbackAndConflict() = runTest {
139: fun rejectsUnsafeArtifactMetadataAndIntegrityMismatches() = runTest {
148: private suspend fun verify(signed: SignedCatalog, previous: CatalogAcceptanceState? = null): RecipeCatalogVerificationResult =
151: private suspend fun assertError(envelope: ByteArray, trustPolicy: CatalogTrustPolicy, expected: RecipeCatalogVerificationErrorCode, previous: CatalogAcceptanceState? = null) {
156: private suspend fun signingMaterial(catalog: String = catalogId, keyId: String = "catalog-key"): CatalogSigningMaterial {
164: private fun policy(material: CatalogSigningMaterial, key: TrustedCatalogKey = material.key): CatalogTrustPolicy = CatalogTrustPolicy(material.key.catalogId, listOf(key))
166: private suspend fun signedCatalog(
182: private suspend fun sha256(bytes: ByteArray): ByteArray = provider.get(SHA256).hasher().hash(bytes)
183: private suspend fun catalogPayload(artifactBytes: ByteArray, url: String = "https://example.test/recipe.json"): ByteArray {
188: private fun manualSigningFrame(catalog: String, keyId: String, revision: Long, issued: Long, expires: Long, payloadLength: Int, hash: ByteArray): ByteArray =
192: private fun manualEnvelope(catalog: String, keyId: String, revision: Long, issued: Long, expires: Long, hash: ByteArray, signature: ByteArray, payload: ByteArray): ByteArray =
196: private fun revisionOffset(key: TrustedCatalogKey): Int = 4 + 1 + 2 + key.catalogId.encodeToByteArray().size + 2 + key.keyId.encodeToByteArray().size
197: private fun payloadLengthOffset(key: TrustedCatalogKey): Int = revisionOffset(key) + 8 + 8 + 8
198: private fun signatureOffset(key: TrustedCatalogKey): Int = payloadLengthOffset(key) + 4 + 32
199: private fun u16(value: Int): ByteArray = byteArrayOf((value ushr 8).toByte(), value.toByte())
200: private fun u32(value: Int): ByteArray = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
201: private fun i64(value: Long): ByteArray = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
202: private data class SignedCatalog(val envelope: ByteArray, val payload: ByteArray, val artifactBytes: ByteArray, val signing: CatalogSigningMaterial, val signature: ByteArray)
203: private data class CatalogSigningMaterial(val key: TrustedCatalogKey, val sign: suspend (ByteArray) -> ByteArray)
204: private fun ByteArray.toHexString(): String = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/VerifiedRecipeCatalogTest.kt) · SHA-256 `a8a49fa6716b22b07d25b333cc2c92645f281b881e739d86557b549049cd0eb1`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import dev.whyoleg.cryptography.CryptographyProvider
import dev.whyoleg.cryptography.CryptographyProviderApi
import dev.whyoleg.cryptography.algorithms.EdDSA
import dev.whyoleg.cryptography.algorithms.SHA256
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs

@OptIn(CryptographyProviderApi::class)
class VerifiedRecipeCatalogTest {
    private val provider = CryptographyProvider.Default
    private val now = 1_700_000_000L
    private val catalogId = "catalog.primary"

    @Test
    fun verifiesManualSignedEnvelopeAndIntegrityOnlyArtifactMatch() = runTest {
        val material = signingMaterial()
        val signed = signedCatalog(material)

        val accepted = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed))
        assertEquals(false, accepted.idempotent)
        assertEquals(catalogId, accepted.acceptanceState.catalogId)
        assertEquals(RecipeArtifactEligibility.Eligible, VerifiedRecipeCatalogVerifier.artifactEligibility(accepted.catalog.artifacts.single(), signed.artifactBytes))
    }

    @Test
    fun manualProtocolVectorBindsDomainIdentityByteOrderLengthsAndSignature() = runTest {
        val material = signingMaterial(keyId = "signing-key")
        val payload = catalogPayload("recipe".encodeToByteArray())
        val hash = sha256(payload)
        val revision = 0x0102030405060708L
        val frame = manualSigningFrame(material.key.catalogId, material.key.keyId, revision, now - 60, now + 60, payload.size, hash)

        assertEquals(
            "796f6b616e2e7265636970652d636174616c6f672e656432353531392e763200000f636174616c6f672e7072696d617279000b7369676e696e672d6b65790102030405060708",
            frame.take(70).toByteArray().toHexString(),
        )
        val signature = material.sign(frame)
        val envelope = manualEnvelope(material.key.catalogId, material.key.keyId, revision, now - 60, now + 60, hash, signature, payload)
        val signed = SignedCatalog(envelope, payload, "recipe".encodeToByteArray(), material, signature)

        assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed))
    }

    @Test
    fun rejectsPayloadAndSignatureTamperingIncludingRehashedUnsignedPayload() = runTest {
        val material = signingMaterial()
        val signed = signedCatalog(material)
        assertError(signed.envelope.copyOf().also { it[it.lastIndex] = (it[it.lastIndex] + 1).toByte() }, policy(material), RecipeCatalogVerificationErrorCode.InvalidPayloadDigest)

        val alteredPayload = signed.payload.decodeToString().replace("1.0.0", "2.0.0").encodeToByteArray()
        val rehashedUnsigned = manualEnvelope(catalogId, material.key.keyId, 10, now - 60, now + 60, sha256(alteredPayload), signed.signature, alteredPayload)
        assertError(rehashedUnsigned, policy(material), RecipeCatalogVerificationErrorCode.InvalidSignature)

        val headerTampered = signed.envelope.copyOf().also { it[revisionOffset(material.key)] = (it[revisionOffset(material.key)] + 1).toByte() }
        assertError(headerTampered, policy(material), RecipeCatalogVerificationErrorCode.InvalidSignature)
        assertError(signed.envelope.copyOf().also { it[signatureOffset(material.key)] = (it[signatureOffset(material.key)] + 1).toByte() }, policy(material), RecipeCatalogVerificationErrorCode.InvalidSignature)
    }

    @Test
    fun authenticatedPayloadUsesSharedBoundedStrictJsonPreflight() = runTest {
        val material = signingMaterial()
        val normal = catalogPayload("recipe".encodeToByteArray()).decodeToString()
        val payloads = listOf(
            normal.replace("\"formatVersion\":\"1\"", "\"formatVersion\":\"1\",\"\\u0066ormatVersion\":\"1\""),
            normal.replace("\"releaseVersion\":\"1.0.0\"", "\"releaseVersion\":\"${"a".repeat(RecipeBundleLimits.maxStringCharacters + 1)}\""),
            "[".repeat(RecipeBundleLimits.maxJsonDepth + 1) + "0" + "]".repeat(RecipeBundleLimits.maxJsonDepth + 1),
            "[" + List(RecipeBundleLimits.maxCollectionEntries + 1) { "0" }.joinToString(",") + "]",
            "{\"formatVersion\":",
            normal.replace("\"artifacts\":", "\"unknown\":true,\"artifacts\":"),
            normal.replace("\"formatVersion\":\"1\"", "\"formatVersion\":\"2\""),
        )
        payloads.forEach { payload ->
            val signed = signedCatalog(material, payload = payload.encodeToByteArray())
            assertError(signed.envelope, policy(material), RecipeCatalogVerificationErrorCode.InvalidCatalogPayload)
        }
    }

    @Test
    fun scopesKeysAndStateToExpectedStableCatalogIdentity() = runTest {
        val primary = signingMaterial()
        val other = signingMaterial(catalog = "catalog.other")
        val primaryPolicy = policy(primary)

        assertError(signedCatalog(other).envelope, primaryPolicy, RecipeCatalogVerificationErrorCode.CatalogIdentityMismatch)
        assertError(signedCatalog(primary).envelope, CatalogTrustPolicy(catalogId, listOf(other.key)), RecipeCatalogVerificationErrorCode.InvalidTrustPolicy)

        val signed = signedCatalog(primary)
        val otherKeyUnderExpectedId = other.key.copy(catalogId = catalogId, keyId = primary.key.keyId)
        assertError(signed.envelope, CatalogTrustPolicy(catalogId, listOf(otherKeyUnderExpectedId)), RecipeCatalogVerificationErrorCode.InvalidSignature)
        assertError(signed.envelope, CatalogTrustPolicy(catalogId, listOf(primary.key, otherKeyUnderExpectedId)), RecipeCatalogVerificationErrorCode.InvalidKey)

        val accepted = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed))
        assertError(signed.envelope, primaryPolicy, RecipeCatalogVerificationErrorCode.InvalidAcceptanceState, CatalogAcceptanceState("catalog.other", 10, accepted.acceptanceState.payloadHash))
        assertError(signed.envelope, primaryPolicy, RecipeCatalogVerificationErrorCode.InvalidAcceptanceState, CatalogAcceptanceState(catalogId, -1, accepted.acceptanceState.payloadHash))
    }

    @Test
    fun rejectsUnknownRevokedMalformedAndOutOfWindowKeys() = runTest {
        val material = signingMaterial()
        val signed = signedCatalog(material)
        assertError(signed.envelope, CatalogTrustPolicy(catalogId, listOf(material.key.copy(keyId = "unknown"))), RecipeCatalogVerificationErrorCode.UnknownKey)
        assertError(signed.envelope, policy(material, material.key.copy(state = TrustedCatalogKeyState.Revoked)), RecipeCatalogVerificationErrorCode.RevokedKey)
        assertError(signed.envelope, policy(material, material.key.copy(rawEd25519PublicKey = ByteArray(31))), RecipeCatalogVerificationErrorCode.InvalidKey)
        assertError(signed.envelope, policy(material, material.key.copy(validUntilEpochSeconds = now - 1)), RecipeCatalogVerificationErrorCode.KeyOutsideValidity)
    }

    @Test
    fun authenticSignaturesCoverTimeLifetimeAndWireBoundaries() = runTest {
        val material = signingMaterial()
        assertError(signedCatalog(material, issued = now - 20, expires = now).envelope, policy(material), RecipeCatalogVerificationErrorCode.Expired)
        assertError(signedCatalog(material, issued = now + 301, expires = now + 600).envelope, policy(material), RecipeCatalogVerificationErrorCode.IssuedInFuture)
        assertError(signedCatalog(material, issued = now, expires = now + 14L * 24 * 60 * 60 + 1).envelope, policy(material), RecipeCatalogVerificationErrorCode.InvalidLifetime)

        val signed = signedCatalog(material)
        assertError(signed.envelope + byteArrayOf(0), policy(material), RecipeCatalogVerificationErrorCode.MalformedEnvelope)
        assertError(signed.envelope.copyOf().also { it[4] = 3 }, policy(material), RecipeCatalogVerificationErrorCode.UnsupportedEnvelopeVersion)
        assertError(signed.envelope.copyOf().also { it[5] = 0x80.toByte(); it[6] = 0 }, policy(material), RecipeCatalogVerificationErrorCode.MalformedEnvelope)
        assertError(signed.envelope.copyOf().also { it[payloadLengthOffset(material.key)] = 0x80.toByte() }, policy(material), RecipeCatalogVerificationErrorCode.MalformedEnvelope)
    }

    @Test
    fun acceptsHigherRevisionAndSamePayloadFreshnessRenewalButRejectsRollbackAndConflict() = runTest {
        val material = signingMaterial()
        val first = signedCatalog(material, revision = 10)
        val state = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(first)).acceptanceState
        assertError(signedCatalog(material, revision = 9).envelope, policy(material), RecipeCatalogVerificationErrorCode.Rollback, state)
        assertError(signedCatalog(material, revision = 10, artifactBytes = "changed".encodeToByteArray()).envelope, policy(material), RecipeCatalogVerificationErrorCode.RevisionConflict, state)
        assertEquals(true, assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signedCatalog(material, revision = 10, issued = now - 30, expires = now + 120), state)).idempotent)
        val higher = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signedCatalog(material, revision = 11, artifactBytes = "changed".encodeToByteArray()), state))
        assertEquals(false, higher.idempotent)
        assertEquals(11, higher.acceptanceState.highestRevision)
    }

    @Test
    fun rejectsUnsafeArtifactMetadataAndIntegrityMismatches() = runTest {
        val material = signingMaterial()
        assertError(signedCatalog(material, url = "http://example.test/recipe.json").envelope, policy(material), RecipeCatalogVerificationErrorCode.InvalidArtifactMetadata)
        val signed = signedCatalog(material)
        val artifact = assertIs<RecipeCatalogVerificationResult.Accepted>(verify(signed)).catalog.artifacts.single()
        assertEquals(RecipeArtifactEligibilityError.SizeMismatch, assertIs<RecipeArtifactEligibility.Rejected>(VerifiedRecipeCatalogVerifier.artifactEligibility(artifact, ByteArray(1))).error)
        assertEquals(RecipeArtifactEligibilityError.DigestMismatch, assertIs<RecipeArtifactEligibility.Rejected>(VerifiedRecipeCatalogVerifier.artifactEligibility(artifact, signed.artifactBytes.copyOf().also { it[0] = (it[0] + 1).toByte() })).error)
    }

    private suspend fun verify(signed: SignedCatalog, previous: CatalogAcceptanceState? = null): RecipeCatalogVerificationResult =
        VerifiedRecipeCatalogVerifier.verify(signed.envelope, policy(signed.signing), previous, now)

    private suspend fun assertError(envelope: ByteArray, trustPolicy: CatalogTrustPolicy, expected: RecipeCatalogVerificationErrorCode, previous: CatalogAcceptanceState? = null) {
        val rejected = assertIs<RecipeCatalogVerificationResult.Rejected>(VerifiedRecipeCatalogVerifier.verify(envelope, trustPolicy, previous, now))
        assertEquals(expected, rejected.error.code)
    }

    private suspend fun signingMaterial(catalog: String = catalogId, keyId: String = "catalog-key"): CatalogSigningMaterial {
        val pair = provider.get(EdDSA).keyPairGenerator(EdDSA.Curve.Ed25519).generateKey()
        return CatalogSigningMaterial(
            TrustedCatalogKey(catalog, keyId, pair.publicKey.encodeToByteArray(EdDSA.PublicKey.Format.RAW), TrustedCatalogKeyState.Active),
            sign = { frame -> pair.privateKey.signatureGenerator().generateSignature(frame) },
        )
    }

    private fun policy(material: CatalogSigningMaterial, key: TrustedCatalogKey = material.key): CatalogTrustPolicy = CatalogTrustPolicy(material.key.catalogId, listOf(key))

    private suspend fun signedCatalog(
        signing: CatalogSigningMaterial,
        revision: Long = 10,
        issued: Long = now - 60,
        expires: Long = now + 60,
        artifactBytes: ByteArray = "recipe".encodeToByteArray(),
        url: String = "https://example.test/recipe.json",
        payload: ByteArray? = null,
    ): SignedCatalog {
        val actualPayload = payload ?: catalogPayload(artifactBytes, url)
        val hash = sha256(actualPayload)
        val frame = manualSigningFrame(signing.key.catalogId, signing.key.keyId, revision, issued, expires, actualPayload.size, hash)
        val signature = signing.sign(frame)
        return SignedCatalog(manualEnvelope(signing.key.catalogId, signing.key.keyId, revision, issued, expires, hash, signature, actualPayload), actualPayload, artifactBytes, signing, signature)
    }

    private suspend fun sha256(bytes: ByteArray): ByteArray = provider.get(SHA256).hasher().hash(bytes)
    private suspend fun catalogPayload(artifactBytes: ByteArray, url: String = "https://example.test/recipe.json"): ByteArray {
        val digest = sha256(artifactBytes).toHexString()
        return """{"formatVersion":"1","artifacts":[{"stableId":"example.recipe","releaseVersion":"1.0.0","sha256":"$digest","sizeBytes":${artifactBytes.size},"url":"$url"}]}""".encodeToByteArray()
    }

    private fun manualSigningFrame(catalog: String, keyId: String, revision: Long, issued: Long, expires: Long, payloadLength: Int, hash: ByteArray): ByteArray =
        "yokan.recipe-catalog.ed25519.v2\u0000".encodeToByteArray() + u16(catalog.encodeToByteArray().size) + catalog.encodeToByteArray() +
            u16(keyId.encodeToByteArray().size) + keyId.encodeToByteArray() + i64(revision) + i64(issued) + i64(expires) + u32(payloadLength) + hash

    private fun manualEnvelope(catalog: String, keyId: String, revision: Long, issued: Long, expires: Long, hash: ByteArray, signature: ByteArray, payload: ByteArray): ByteArray =
        byteArrayOf('Y'.code.toByte(), 'R'.code.toByte(), 'C'.code.toByte(), '2'.code.toByte(), 2) + u16(catalog.encodeToByteArray().size) + catalog.encodeToByteArray() +
            u16(keyId.encodeToByteArray().size) + keyId.encodeToByteArray() + i64(revision) + i64(issued) + i64(expires) + u32(payload.size) + hash + signature + payload

    private fun revisionOffset(key: TrustedCatalogKey): Int = 4 + 1 + 2 + key.catalogId.encodeToByteArray().size + 2 + key.keyId.encodeToByteArray().size
    private fun payloadLengthOffset(key: TrustedCatalogKey): Int = revisionOffset(key) + 8 + 8 + 8
    private fun signatureOffset(key: TrustedCatalogKey): Int = payloadLengthOffset(key) + 4 + 32
    private fun u16(value: Int): ByteArray = byteArrayOf((value ushr 8).toByte(), value.toByte())
    private fun u32(value: Int): ByteArray = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())
    private fun i64(value: Long): ByteArray = ByteArray(8) { index -> (value ushr (56 - index * 8)).toByte() }
    private data class SignedCatalog(val envelope: ByteArray, val payload: ByteArray, val artifactBytes: ByteArray, val signing: CatalogSigningMaterial, val signature: ByteArray)
    private data class CatalogSigningMaterial(val key: TrustedCatalogKey, val sign: suspend (ByteArray) -> ByteArray)
    private fun ByteArray.toHexString(): String = joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }
}
```
[complete-source-end]: #

## `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloaderTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloaderTest.kt) · test / fixture · 146 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
22: class CapabilityCatalogDownloaderTest {
24: fun invalidCatalogUrlsFailBeforeDnsResolution() = runTest {
41: fun mixedOrForbiddenDnsSnapshotsFailClosed() = runTest {
50: fun loopbackHttpCatalogsNeedDeveloperMode(): Unit = kotlinx.coroutines.runBlocking {
75: fun snapshotDnsAndPeerMembershipAreExact() {
87: fun responsePoliciesRejectStatusEncodingMimeHeadersAndSize() {
98: fun bodyCapIsStreamingAndLimitsAreBounded() {
105: fun timeoutBecomesClosedFailureAndCancellationPropagates() = runTest {
113: fun dedicatedSessionDisablesStatefulAndUnsafeTransportFeatures() {
128: private fun response(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloaderTest.kt) · SHA-256 `6f0826a4ef3dcf675fefdda51bb089ac36125862906220ef7964711b53c6d017`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
import java.io.ByteArrayInputStream
import java.net.InetAddress
import java.net.Proxy
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class CapabilityCatalogDownloaderTest {
    @Test
    fun invalidCatalogUrlsFailBeforeDnsResolution() = runTest {
        var resolved = false
        val downloader = CapabilityCatalogDownloader(RecipeHostResolver { resolved = true; listOf(InetAddress.getByName("8.8.8.8")) })
        listOf(
            "http://catalog.example.test/catalog.yrc",
            "https://Catalog.example.test/catalog.yrc",
            "https://catalog.example.test:443/catalog.yrc",
            "https://127.0.0.1/catalog.yrc",
            "https://user@catalog.example.test/catalog.yrc",
            "https://catalog.example.test/catalog.yrc?query=x",
            "https://catalog.example.test/catalog.yrc#fragment",
            "https://catalog.example.test\\catalog.yrc",
        ).forEach { url -> assertFailsWith<RecipeCatalogDownloadException> { downloader.download(url, 64, 1_000) } }
        assertFalse(resolved)
    }

    @Test
    fun mixedOrForbiddenDnsSnapshotsFailClosed() = runTest {
        val validUrl = "https://catalog.example.test/catalog.yrc"
        val forbidden = CapabilityCatalogDownloader(RecipeHostResolver { listOf(InetAddress.getByName("127.0.0.1")) })
        val mixed = CapabilityCatalogDownloader(RecipeHostResolver { listOf(InetAddress.getByName("8.8.8.8"), InetAddress.getByName("127.0.0.1")) })
        assertFailsWith<RecipeCatalogDownloadException> { forbidden.download(validUrl, 64, 1_000) }
        assertFailsWith<RecipeCatalogDownloadException> { mixed.download(validUrl, 64, 1_000) }
    }

    @Test
    fun loopbackHttpCatalogsNeedDeveloperMode(): Unit = kotlinx.coroutines.runBlocking {
        val body = "signed-envelope".encodeToByteArray()
        val server = com.sun.net.httpserver.HttpServer.create(java.net.InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 0)
        server.createContext("/") { exchange ->
            exchange.responseHeaders.add("Content-Type", "application/octet-stream")
            exchange.sendResponseHeaders(if (exchange.requestURI.path == "/catalog.yrc") 200 else 404, body.size.toLong())
            exchange.responseBody.use { it.write(body) }
        }
        server.start()
        try {
            val url = "http://127.0.0.1:${server.address.port}/catalog.yrc"
            var developerMode = false
            val downloader = CapabilityCatalogDownloader(RecipeHostResolver { error("loopback must not resolve") }, developerMode = { developerMode })
            assertFailsWith<RecipeCatalogDownloadException> { downloader.download(url, 64, 5_000) }
            developerMode = true
            assertContentEquals(body, downloader.download(url, 64, 5_000))
            // Only the literal loopback address is admitted; other plain-HTTP hosts stay rejected.
            assertFailsWith<RecipeCatalogDownloadException> { downloader.download("http://localhost:${server.address.port}/catalog.yrc", 64, 5_000) }
            assertFailsWith<RecipeCatalogDownloadException> { downloader.download("http://127.0.0.1:${server.address.port}/a/../catalog.yrc", 64, 5_000) }
        } finally {
            server.stop(0)
        }
    }

    @Test
    fun snapshotDnsAndPeerMembershipAreExact() {
        val first = InetAddress.getByName("8.8.8.8")
        val second = InetAddress.getByName("1.1.1.1")
        val dns = SnapshotDns("catalog.example.test", listOf(first))
        assertEquals(listOf(first), dns.lookup("catalog.example.test"))
        assertFailsWith<Exception> { dns.lookup("other.example.test") }
        assertTrue(approvedPeerAddresses(first, first, listOf(first)))
        assertFalse(approvedPeerAddresses(first, second, listOf(first)))
        assertFalse(approvedPeerAddresses(null, first, listOf(first)))
    }

    @Test
    fun responsePoliciesRejectStatusEncodingMimeHeadersAndSize() {
        assertFalse(catalogResponseAllowed(response(302), 64, 64, 8_192))
        assertFalse(catalogResponseAllowed(response(200, encoding = "gzip"), 64, 64, 8_192))
        assertFalse(catalogResponseAllowed(response(200, mime = "text/html"), 64, 64, 8_192))
        assertFalse(catalogResponseAllowed(response(200, headers = listOf("X-Long" to "x".repeat(32))), 64, 64, 8))
        assertFalse(catalogResponseAllowed(response(200, bytes = ByteArray(65)), 64, 64, 8_192))
        assertTrue(catalogResponseAllowed(response(200, mime = "application/problem+json"), 64, 64, 8_192))
        assertTrue(catalogResponseAllowed(response(200, mime = "text/plain; charset=utf-8"), 64, 64, 8_192))
    }

    @Test
    fun bodyCapIsStreamingAndLimitsAreBounded() {
        assertContentEquals(byteArrayOf(1, 2), ByteArrayInputStream(byteArrayOf(1, 2)).readCatalogCapped(2))
        assertFailsWith<RecipeCatalogDownloadException> { ByteArrayInputStream(byteArrayOf(1, 2, 3)).readCatalogCapped(2) }
        assertFailsWith<RecipeCatalogDownloadException> { ByteArrayInputStream(byteArrayOf()).readCatalogCapped(96 * 1024 + 1) }
    }

    @Test
    fun timeoutBecomesClosedFailureAndCancellationPropagates() = runTest {
        val timeout = CapabilityCatalogDownloader(RecipeHostResolver { delay(100); listOf(InetAddress.getByName("8.8.8.8")) })
        assertFailsWith<RecipeCatalogDownloadException> { timeout.download("https://catalog.example.test/catalog.yrc", 64, 1) }
        val cancelled = CapabilityCatalogDownloader(RecipeHostResolver { throw CancellationException("cancel") })
        assertFailsWith<CancellationException> { cancelled.download("https://catalog.example.test/catalog.yrc", 64, 1_000) }
    }

    @Test
    fun dedicatedSessionDisablesStatefulAndUnsafeTransportFeatures() {
        val client = snapshotOkHttpClient("catalog.example.test", listOf(InetAddress.getByName("8.8.8.8")), AtomicBoolean())
        try {
            assertFalse(client.followRedirects)
            assertFalse(client.followSslRedirects)
            assertFalse(client.retryOnConnectionFailure)
            assertEquals(Proxy.NO_PROXY, client.proxy)
            assertEquals(okhttp3.CookieJar.NO_COOKIES, client.cookieJar)
            assertEquals(null, client.cache)
        } finally {
            client.dispatcher.cancelAll()
            client.connectionPool.evictAll()
        }
    }

    private fun response(
        status: Int,
        mime: String = "application/json",
        encoding: String? = null,
        headers: List<Pair<String, String>> = emptyList(),
        bytes: ByteArray = byteArrayOf(1),
    ): Response {
        val builder = Response.Builder()
            .request(Request.Builder().url("https://catalog.example.test/catalog.yrc").build())
            .protocol(Protocol.HTTP_2)
            .code(status)
            .message("fixture")
            .header("Content-Type", mime)
            .body(bytes.toResponseBody(mime.substringBefore(';').toMediaType()))
        encoding?.let { builder.header("Content-Encoding", it) }
        headers.forEach { (name, value) -> builder.addHeader(name, value) }
        return builder.build()
    }
}
```
[complete-source-end]: #

## `composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.ios.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.ios.kt) · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
4: actual fun createPlatformRecipeServices(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/iosMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.ios.kt) · SHA-256 `dca253bb4e34230029a55d5e21c5f5159922552d4199ed061bf3c8bc7dedb5ce`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.database.YokanDatabase
actual fun createPlatformRecipeServices(
    database: YokanDatabase,
    clock: RecipeInstallationClock,
): PlatformRecipeServices = unavailablePlatformRecipeServices(clock)
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloader.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloader.kt) · implementation · 136 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
17: class RecipeCatalogDownloadException : IOException("catalog download failed")
23: class CapabilityCatalogDownloader(
33: override suspend fun download(url: String, maxBytes: Int, deadlineMillis: Long): ByteArray {
68: private suspend fun execute(client: OkHttpClient, url: String, maxBytes: Int, peerMismatch: AtomicBoolean): ByteArray = withContext(Dispatchers.IO) {
93: internal fun parseCatalogEndpoint(url: String): CatalogEndpoint? {
101: internal data class CatalogEndpoint(val host: String)
103: internal fun catalogResponseAllowed(response: Response, maxBytes: Int, maxHeaderCount: Int, maxHeaderCharacters: Int): Boolean =
108: internal fun catalogHeadersAllowed(response: Response, maxHeaderCount: Int, maxHeaderCharacters: Int): Boolean {
118: internal fun catalogMimeAllowed(raw: String?): Boolean {
124: internal fun java.io.InputStream.readCatalogCapped(maxBytes: Int): ByteArray {
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityCatalogDownloader.kt) · SHA-256 `1601bafe729880de9f14cea7c90c471adda934824b60aa185a4728cd2d94e486`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.concurrent.atomic.AtomicBoolean

/** Closed transport error: callers must not expose URL, parser, or response details. */
class RecipeCatalogDownloadException : IOException("catalog download failed")

/**
 * Dedicated native catalog transport; it does not share broker requests, clients, or session state.
 * [developerMode] additionally admits plain-HTTP `127.0.0.1` catalogs for local test servers.
 */
class CapabilityCatalogDownloader(
    private val resolver: RecipeHostResolver = SystemRecipeHostResolver,
    private val maxHeaderCount: Int = 64,
    private val maxHeaderCharacters: Int = 8 * 1024,
    private val developerMode: () -> Boolean = { false },
) : RecipeCatalogDownloader {
    init {
        require(maxHeaderCount > 0 && maxHeaderCharacters > 0)
    }

    override suspend fun download(url: String, maxBytes: Int, deadlineMillis: Long): ByteArray {
        val loopback = loopbackCatalogOrigin(url)
        val endpoint = if (loopback == null) parseCatalogEndpoint(url) ?: throw RecipeCatalogDownloadException() else null
        if (loopback != null && (!developerMode() || url.any { it.code !in 0x21..0x7e || it == '\\' || it == '?' || it == '#' } || !RecipeSyntax.isCanonicalPath(url.substring(loopback.length)))) {
            throw RecipeCatalogDownloadException()
        }
        if (maxBytes !in 1..MAX_RESPONSE_BYTES || deadlineMillis !in 1..MAX_DEADLINE_MILLIS) throw RecipeCatalogDownloadException()
        return try {
            withTimeout(deadlineMillis) {
                val peerMismatch = AtomicBoolean(false)
                val client = if (endpoint == null) {
                    isolatedOkHttpBuilder().build()
                } else {
                    val resolved = resolver.resolve(endpoint.host)
                    if (!approvedSnapshot(resolved)) throw RecipeCatalogDownloadException()
                    snapshotOkHttpClient(endpoint.host, resolved.distinct(), peerMismatch)
                }
                try {
                    execute(client, url, maxBytes, peerMismatch)
                } finally {
                    client.dispatcher.cancelAll()
                    client.connectionPool.evictAll()
                    client.cache?.close()
                }
            }
        } catch (_: TimeoutCancellationException) {
            throw RecipeCatalogDownloadException()
        } catch (error: CancellationException) {
            throw error
        } catch (_: Throwable) {
            // Closed transport error: every other failure, including our own, collapses to one opaque exception.
            throw RecipeCatalogDownloadException()
        }
    }

    private suspend fun execute(client: OkHttpClient, url: String, maxBytes: Int, peerMismatch: AtomicBoolean): ByteArray = withContext(Dispatchers.IO) {
        val request = Request.Builder().url(url).header("Accept-Encoding", "identity").get().build()
        val call = client.newCall(request)
        val cancellation = currentCoroutineContext()[kotlinx.coroutines.Job]?.invokeOnCompletion { call.cancel() }
        try {
            call.execute().use { response ->
                if (peerMismatch.get() || !catalogResponseAllowed(response, maxBytes, maxHeaderCount, maxHeaderCharacters)) throw RecipeCatalogDownloadException()
                response.body.byteStream().readCatalogCapped(maxBytes)
            }
        } catch (error: CancellationException) {
            throw error
        } catch (_: Throwable) {
            throw RecipeCatalogDownloadException()
        } finally {
            cancellation?.dispose()
            call.cancel()
        }
    }

    private companion object {
        const val MAX_RESPONSE_BYTES = RecipeCatalogLimits.maxEnvelopeBytes
        const val MAX_DEADLINE_MILLIS = 30_000L
    }
}

internal fun parseCatalogEndpoint(url: String): CatalogEndpoint? {
    if (url.length !in 9..2_048 || !url.startsWith("https://") || url.any { it.code !in 0x21..0x7e || it == '\\' || it == '?' || it == '#' }) return null
    val authorityEnd = url.indexOf('/', 8).takeIf { it >= 0 } ?: return null
    val host = url.substring(8, authorityEnd)
    if (!RecipeSyntax.isHost(host) || !RecipeSyntax.isCanonicalPath(url.substring(authorityEnd))) return null
    return CatalogEndpoint(host)
}

internal data class CatalogEndpoint(val host: String)

internal fun catalogResponseAllowed(response: Response, maxBytes: Int, maxHeaderCount: Int, maxHeaderCharacters: Int): Boolean =
    response.code in 200..299 && maxBytes in 1..RecipeCatalogLimits.maxEnvelopeBytes && catalogHeadersAllowed(response, maxHeaderCount, maxHeaderCharacters) &&
        identityContentEncoding(response.header("Content-Encoding")) && catalogMimeAllowed(response.header("Content-Type")) &&
        response.body.contentLength().let { it == -1L || it in 0..maxBytes }

internal fun catalogHeadersAllowed(response: Response, maxHeaderCount: Int, maxHeaderCharacters: Int): Boolean {
    if (maxHeaderCount <= 0 || maxHeaderCharacters <= 0 || response.headers.size > maxHeaderCount) return false
    var characters = 0
    for (index in 0 until response.headers.size) {
        characters += response.headers.name(index).length + response.headers.value(index).length
        if (characters > maxHeaderCharacters) return false
    }
    return true
}

internal fun catalogMimeAllowed(raw: String?): Boolean {
    val mime = raw?.substringBefore(';')?.trim()?.lowercase() ?: return false
    return mime == "application/octet-stream" || mime == "application/json" || mime == "text/plain" ||
        (mime.startsWith("application/") && mime.endsWith("+json"))
}

internal fun java.io.InputStream.readCatalogCapped(maxBytes: Int): ByteArray {
    if (maxBytes !in 1..RecipeCatalogLimits.maxEnvelopeBytes) throw RecipeCatalogDownloadException()
    val output = ByteArrayOutputStream(minOf(maxBytes, 8 * 1024))
    val buffer = ByteArray(8 * 1024)
    var total = 0
    while (true) {
        val read = read(buffer)
        if (read < 0) return output.toByteArray()
        if (read > maxBytes - total) throw RecipeCatalogDownloadException()
        output.write(buffer, 0, read)
        total += read
    }
}
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityHttpsBroker.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityHttpsBroker.kt) · implementation · 148 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
30: fun interface RecipeHostResolver {
31: suspend fun resolve(hostname: String): List<InetAddress>
34: object SystemRecipeHostResolver : RecipeHostResolver {
35: override suspend fun resolve(hostname: String): List<InetAddress> = runInterruptible(Dispatchers.IO) {
41: class CapabilityHttpsBroker(
46: override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult {
71: private fun requestHost(request: RecipeBrokerRequest): String? {
77: private fun jsonContent(raw: String?): Boolean {
82: private fun acceptableHeaders(headers: Set<Map.Entry<String, List<String>>>): Boolean {
101: internal fun isolatedOkHttpBuilder(): OkHttpClient.Builder = OkHttpClient.Builder()
111: internal fun snapshotOkHttpClient(host: String, snapshot: List<InetAddress>, peerMismatch: AtomicBoolean): OkHttpClient = isolatedOkHttpBuilder()
116: internal class SnapshotDns(private val hostname: String, private val snapshot: List<InetAddress>) : Dns {
117: override fun lookup(hostname: String): List<InetAddress> = if (hostname == this.hostname) snapshot else throw IOException("unapproved DNS host")
120: private class SnapshotPeerListener(private val snapshot: List<InetAddress>, private val failed: AtomicBoolean) : EventListener() {
121: override fun connectionAcquired(call: Call, connection: Connection) {
131: internal fun approvedAddress(address: InetAddress): Boolean = when (address) {
143: internal fun approvedSnapshot(addresses: List<InetAddress>): Boolean = addresses.isNotEmpty() && addresses.all(::approvedAddress)
145: internal fun identityContentEncoding(value: String?): Boolean = value == null || value.split(',').all { it.trim().equals("identity", ignoreCase = true) }
147: internal fun approvedPeerAddresses(routePeer: InetAddress?, socketPeer: InetAddress?, snapshot: List<InetAddress>): Boolean =
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityHttpsBroker.kt) · SHA-256 `0f017e4782f23b8d2cb1ead07ed9db9de2168e89719ea6378957cb52049cddc0`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import io.ktor.client.HttpClient
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsChannel
import io.ktor.http.HttpHeaders
import io.ktor.utils.io.readBuffer
import kotlinx.io.readByteArray
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runInterruptible
import kotlinx.coroutines.withTimeout
import eu.friedcutlet.yokan.services.catchingNonCancellation
import okhttp3.Call
import okhttp3.Connection
import okhttp3.ConnectionPool
import okhttp3.CookieJar
import okhttp3.Dns
import okhttp3.EventListener
import okhttp3.OkHttpClient
import java.io.IOException
import java.net.Inet4Address
import java.net.Inet6Address
import java.net.InetAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean

/** Broker-owned DNS boundary. A production host may replace this with its approved resolver. */
fun interface RecipeHostResolver {
    suspend fun resolve(hostname: String): List<InetAddress>
}

object SystemRecipeHostResolver : RecipeHostResolver {
    override suspend fun resolve(hostname: String): List<InetAddress> = runInterruptible(Dispatchers.IO) {
        InetAddress.getAllByName(hostname).toList()
    }
}

/** Native-only, stateless HTTPS broker. It owns no cookies, cache, proxy, session, or DNS state. */
class CapabilityHttpsBroker(
    private val resolver: RecipeHostResolver = SystemRecipeHostResolver,
    private val maxHeaderCount: Int = 64,
    private val maxHeaderCharacters: Int = 8 * 1024,
) : RecipeCapabilityBroker {
    override suspend fun fetch(request: RecipeBrokerRequest): RecipeBrokerResult {
        val host = requestHost(request) ?: return RecipeBrokerResult.OriginDenied
        val resolved = catchingNonCancellation { resolver.resolve(host) }.getOrElse { return RecipeBrokerResult.Failed }
        if (!approvedSnapshot(resolved)) return RecipeBrokerResult.OriginDenied
        val peerMismatch = AtomicBoolean(false)
        val client = HttpClient(OkHttp) {
            expectSuccess = false
            followRedirects = false
            engine { preconfigured = snapshotOkHttpClient(host, resolved.distinct(), peerMismatch) }
        }
        return try {
            catchingNonCancellation { withTimeout(request.deadlineMillis) {
                val response = client.get(request.url)
                if (peerMismatch.get() || response.status.value !in 200..299) return@withTimeout RecipeBrokerResult.HttpFailure
                // Deliberately identity-only until compressed and decompressed byte accounting is one policy.
                if (!identityContentEncoding(response.headers[HttpHeaders.ContentEncoding]) || !jsonContent(response.headers[HttpHeaders.ContentType]) || !acceptableHeaders(response.headers.entries())) return@withTimeout RecipeBrokerResult.Failed
                val bytes = response.bodyAsChannel().readBuffer(request.maxDocumentBytes.toLong() + 1).readByteArray()
                if (bytes.size > request.maxDocumentBytes) RecipeBrokerResult.ResponseTooLarge else RecipeBrokerResult.Document(bytes)
            } }.getOrDefault(RecipeBrokerResult.Failed)
        } finally {
            client.close()
        }
    }

    /** The origin's host when [request] is within broker limits, else null. */
    private fun requestHost(request: RecipeBrokerRequest): String? {
        if (request.maxDocumentBytes !in 1..MAX_RESPONSE_BYTES || request.deadlineMillis !in 1..MAX_DEADLINE_MILLIS || request.originId.isBlank()) return null
        if (!request.pathAndQuery.startsWith('/') || request.pathAndQuery.startsWith("//") || request.pathAndQuery.any { it == '#' || it == '\\' || it.code < 0x20 }) return null
        return ORIGIN.matchEntire(request.origin)?.groupValues?.get(1)?.takeIf(RecipeSyntax::isHost)
    }

    private fun jsonContent(raw: String?): Boolean {
        val mime = raw?.substringBefore(';')?.trim()?.lowercase() ?: return false
        return mime == "application/json" || (mime.startsWith("application/") && mime.endsWith("+json"))
    }

    private fun acceptableHeaders(headers: Set<Map.Entry<String, List<String>>>): Boolean {
        var count = 0
        var characters = 0
        for ((name, values) in headers) for (value in values) {
            count++
            characters += name.length + value.length
            if (count > maxHeaderCount || characters > maxHeaderCharacters) return false
        }
        return true
    }

    private companion object {
        const val MAX_RESPONSE_BYTES = 256 * 1024
        const val MAX_DEADLINE_MILLIS = 30_000L
        val ORIGIN = Regex("https://([a-z0-9.-]+)")
    }
}

/** Session-free OkHttp settings shared by the broker and the catalog downloader: no redirects, retries, proxy, cookies, cache or pooling. */
internal fun isolatedOkHttpBuilder(): OkHttpClient.Builder = OkHttpClient.Builder()
    .followRedirects(false)
    .followSslRedirects(false)
    .retryOnConnectionFailure(false)
    .proxy(Proxy.NO_PROXY)
    .cookieJar(CookieJar.NO_COOKIES)
    .cache(null)
    .connectionPool(ConnectionPool(0, 1, TimeUnit.MILLISECONDS))

/** [isolatedOkHttpBuilder] pinned to a pre-approved DNS snapshot; [peerMismatch] is set if a connection leaves it. */
internal fun snapshotOkHttpClient(host: String, snapshot: List<InetAddress>, peerMismatch: AtomicBoolean): OkHttpClient = isolatedOkHttpBuilder()
    .dns(SnapshotDns(host, snapshot))
    .eventListenerFactory { SnapshotPeerListener(snapshot, peerMismatch) }
    .build()

internal class SnapshotDns(private val hostname: String, private val snapshot: List<InetAddress>) : Dns {
    override fun lookup(hostname: String): List<InetAddress> = if (hostname == this.hostname) snapshot else throw IOException("unapproved DNS host")
}

private class SnapshotPeerListener(private val snapshot: List<InetAddress>, private val failed: AtomicBoolean) : EventListener() {
    override fun connectionAcquired(call: Call, connection: Connection) {
        val routePeer = connection.route().socketAddress.address
        val socketPeer = connection.socket().inetAddress
        if (!approvedPeerAddresses(routePeer, socketPeer, snapshot) || connection.handshake() == null) {
            failed.set(true)
            call.cancel()
        }
    }
}

internal fun approvedAddress(address: InetAddress): Boolean = when (address) {
    is Inet4Address -> {
        val value = address.address.map { it.toInt() and 0xff }
        !address.isAnyLocalAddress && !address.isLoopbackAddress && !address.isLinkLocalAddress && !address.isSiteLocalAddress && !address.isMulticastAddress &&
            value[0] !in setOf(0, 10, 127, 192, 198, 203, 224, 240, 255) && !(value[0] == 100 && value[1] in 64..127) &&
            !(value[0] == 172 && value[1] in 16..31) && !(value[0] == 192 && value[1] == 0) && !(value[0] == 192 && value[1] == 88) && !(value[0] == 192 && value[1] == 175) && !(value[0] == 198 && value[1] in 18..19)
    }
    is Inet6Address -> !address.isAnyLocalAddress && !address.isLoopbackAddress && !address.isLinkLocalAddress && !address.isSiteLocalAddress && !address.isMulticastAddress &&
        (address.address[0].toInt() and 0xfe) != 0xfc
    else -> false
}

internal fun approvedSnapshot(addresses: List<InetAddress>): Boolean = addresses.isNotEmpty() && addresses.all(::approvedAddress)

internal fun identityContentEncoding(value: String?): Boolean = value == null || value.split(',').all { it.trim().equals("identity", ignoreCase = true) }

internal fun approvedPeerAddresses(routePeer: InetAddress?, socketPeer: InetAddress?, snapshot: List<InetAddress>): Boolean =
    routePeer != null && socketPeer != null && snapshot.any { it == routePeer } && snapshot.any { it == socketPeer }
```
[complete-source-end]: #

## `composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.jvm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.jvm.kt) · implementation · 21 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
6: actual fun createPlatformRecipeServices(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.jvm.kt) · SHA-256 `256f99df27187825aeed6fc3edea0c4209bf1b977f034619db4b5f6a31b8ef4f`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.database.YokanDatabase
import eu.friedcutlet.yokan.database.room.RoomRecipeInstallationStore
import eu.friedcutlet.yokan.database.room.RoomYokanDatabase
actual fun createPlatformRecipeServices(
    database: YokanDatabase,
    clock: RecipeInstallationClock,
): PlatformRecipeServices {
    val roomDatabase = database as? RoomYokanDatabase ?: return unavailablePlatformRecipeServices(clock)
    val store = RoomRecipeInstallationStore(roomDatabase.room, clock)
    return PlatformRecipeServices(
        installation = RecipeCatalogInstallationService(store, CapabilityCatalogDownloader(developerMode = { database.settings().developerMode }), clock),
        runtimeBindings = RecipeRuntimeBindings(
            resolver = InstalledRecipeBundleResolver(store),
            broker = CapabilityHttpsBroker(),
            // Host limits only: an installed recipe is granted exactly its own declared origins at execution time.
            policy = RecipeExecutionPolicy(emptyMap()),
        ),
    )
}
```
[complete-source-end]: #

## `composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityHttpsBrokerTest.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityHttpsBrokerTest.kt) · test / fixture · 49 lines.
- Manual task: Recreate the fixtures and assertions in this file after its production contract exists. Run it in its original source set; distinguish deterministic checks from native/live integration checks.

Declaration checklist (source line numbers):
```text
12: class CapabilityHttpsBrokerTest {
14: fun rejectsUnsafeRequestsBeforeResolutionAndForbiddenResolverAnswers() = runTest {
28: fun addressAndCancellationPolicyFailClosed() = runTest {
45: private fun request(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/jvmCommonTest/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/CapabilityHttpsBrokerTest.kt) · SHA-256 `62ea22ebaf41c46a7e7a2ca64ab864d18ea36fbb9a74e06fcc9fe300fd9e3a2e`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.test.runTest
import java.net.InetAddress
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class CapabilityHttpsBrokerTest {
    @Test
    fun rejectsUnsafeRequestsBeforeResolutionAndForbiddenResolverAnswers() = runTest {
        var calls = 0
        val resolver = RecipeHostResolver { calls++; listOf(InetAddress.getByName("8.8.8.8")) }
        val broker = CapabilityHttpsBroker(resolver)
        assertEquals(RecipeBrokerResult.OriginDenied, broker.fetch(request(origin = "http://example.test")))
        assertEquals(RecipeBrokerResult.OriginDenied, broker.fetch(request(origin = "https://example.test:443")))
        assertEquals(RecipeBrokerResult.OriginDenied, broker.fetch(request(origin = "https://example.test:8443")))
        assertEquals(RecipeBrokerResult.OriginDenied, broker.fetch(request(path = "//attacker.test")))
        assertEquals(0, calls)
        assertEquals(RecipeBrokerResult.OriginDenied, CapabilityHttpsBroker(RecipeHostResolver { listOf(InetAddress.getByName("127.0.0.1")) }).fetch(request()))
        assertEquals(RecipeBrokerResult.OriginDenied, CapabilityHttpsBroker(RecipeHostResolver { listOf(InetAddress.getByName("8.8.8.8"), InetAddress.getByName("127.0.0.1")) }).fetch(request()))
    }

    @Test
    fun addressAndCancellationPolicyFailClosed() = runTest {
        assertFalse(approvedAddress(InetAddress.getByName("127.0.0.1")))
        assertFalse(approvedAddress(InetAddress.getByName("10.0.0.1")))
        assertFalse(approvedAddress(InetAddress.getByName("100.64.0.1")))
        assertTrue(approvedAddress(InetAddress.getByName("8.8.8.8")))
        assertTrue(identityContentEncoding(null))
        assertTrue(identityContentEncoding("identity"))
        assertFalse(identityContentEncoding("gzip"))
        assertFalse(identityContentEncoding("identity, br"))
        val approved = InetAddress.getByName("8.8.8.8")
        assertTrue(approvedPeerAddresses(approved, approved, listOf(approved)))
        assertFalse(approvedPeerAddresses(approved, InetAddress.getByName("1.1.1.1"), listOf(approved)))
        assertFailsWith<CancellationException> {
            CapabilityHttpsBroker(RecipeHostResolver { throw CancellationException("cancel") }).fetch(request())
        }
    }

    private fun request(
        origin: String = "https://example.test",
        path: String = "/data?x=1",
    ) = RecipeBrokerRequest("primary", origin, path, 1_024, 1_000)
}
```
[complete-source-end]: #

## `composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.wasm.kt`

- [Source](/Users/duongph/Projects/yokan/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.wasm.kt) · implementation · 7 lines.
- Manual task: Implement the declarations below; preserve nullability, defaults, error paths, cancellation, resource ownership and externally visible behavior.

Declaration checklist (source line numbers):
```text
4: actual fun createPlatformRecipeServices(
```

[complete-source-start]: #
[Exact file bytes / download](source/composeApp/src/wasmJsMain/kotlin/eu/friedcutlet/yokan/services/extensions/recipe/PlatformRecipeServices.wasm.kt) · SHA-256 `dca253bb4e34230029a55d5e21c5f5159922552d4199ed061bf3c8bc7dedb5ce`.

### Complete file

```kotlin
package eu.friedcutlet.yokan.services.extensions.recipe

import eu.friedcutlet.yokan.database.YokanDatabase
actual fun createPlatformRecipeServices(
    database: YokanDatabase,
    clock: RecipeInstallationClock,
): PlatformRecipeServices = unavailablePlatformRecipeServices(clock)
```
[complete-source-end]: #

