Cotton code
402 lines · 14.6 KB · RustRaw
//! `SecretPayload.swift` — what is INSIDE a sealed secret, as Swift.//!//! The declaration is `cotton_core::vault::payload`: [`SECRET_KINDS`] is the//! data half (which field belongs to which kind, and which one is PRIMARY) and//! `SecretPayload` is the serde half, and `payload_tests.rs` holds the two to//! each other field for field. This renderer reads the data half, exactly as//! `retired.rs` reads `language::retired_terms` — the Swift is a twin of the//! Rust, never a second declaration of it.//!//! **Why generate it rather than write it once by hand.** A payload is sealed//! bytes: nothing in the file, on the wire or in a test can read one to notice//! that Swift spells a field `id_type` where Rust spells it `idType`, or that//! the phone stopped writing `totp` when the Rust side added it. A hand-written//! twin drifts silently and the failure is a person's password that will not//! decode. `--check` compares BYTES, so the drift is a red CI run instead.//!//! **The wire form is FLAT and tagged on `kind`** — `{"kind":"login",//! "password":"…"}` — which is what `#[serde(tag = "kind")]` writes and what//! Swift's own synthesized `Codable` for an enum with associated values does//! NOT write. So the enum's `Codable` is written out here: read the tag from a//! one-key container, then decode the kind's struct from the SAME decoder, and//! encode the same way round. That is the whole reason this file is generated//! rather than four lines of `case` in the app.use cotton_core::vault::payload::{SecretKindSpec, HINT_CHARS, SECRET_KINDS};use crate::swift::{generated_header, swift_str};/// `api_key` → `ApiKey`. The type name half of a kind.fn pascal(value: &str) -> String {    value        .split('_')        .map(|word| {            let mut chars = word.chars();            match chars.next() {                Some(first) => first.to_uppercase().chain(chars).collect::<String>(),                None => String::new(),            }        })        .collect()}/// `api_key` → `apiKey`, `id_type` → `idType`. Swift spells a member in lower/// camel; the JSON key stays the declaration's own spelling, and a `CodingKeys`/// row carries the difference wherever there is one.fn camel(value: &str) -> String {    let pascal = pascal(value);    let mut chars = pascal.chars();    match chars.next() {        Some(first) => first.to_lowercase().chain(chars).collect(),        None => String::new(),    }}/// The Swift type of one kind's payload.fn struct_name(spec: &SecretKindSpec) -> String {    format!("Secret{}", pascal(spec.kind.as_str()))}/// One kind's struct: its fields, its `CodingKeys` when a name differs from the/// JSON key, a memberwise `init` with every optional defaulted, and the primary/// field read back by name.fn payload_struct(spec: &SecretKindSpec) -> String {    let name = struct_name(spec);    let kind = spec.kind.as_str();    let properties: Vec<String> = spec        .fields        .iter()        .map(|field| {            let optional = if field.required { "" } else { "?" };            format!(                "    /// {}\n    public var {}: String{optional}",                field.meaning,                camel(field.name)            )        })        .collect();    let parameters: Vec<String> = spec        .fields        .iter()        .map(|field| {            if field.required {                format!("{}: String", camel(field.name))            } else {                format!("{}: String? = nil", camel(field.name))            }        })        .collect();    let assignments: Vec<String> = spec        .fields        .iter()        .map(|field| {            let member = camel(field.name);            format!("        self.{member} = {member}")        })        .collect();    // Only emitted when some field's Swift name is not its JSON key: a    // `CodingKeys` that says nothing is a place for a later field to be    // forgotten out of.    let keys = if spec.fields.iter().any(|field| camel(field.name) != field.name) {        let rows: Vec<String> = spec            .fields            .iter()            .map(|field| {                let member = camel(field.name);                if member == field.name {                    format!("        case {member}")                } else {                    format!("        case {member} = {}", swift_str(field.name))                }            })            .collect();        format!(            "\n    /// The JSON keys are the Rust declaration's own spelling.\n    \             private enum CodingKeys: String, CodingKey {{\n{}\n    }}\n",            rows.join("\n")        )    } else {        String::new()    };    format!(        r#"/// A `{kind}` secret's payload.public struct {name}: Sendable, Equatable, Codable {{{properties}    public init({parameters}) {{{assignments}    }}{keys}    /// The field a hint is taken from, and the one Copy copies.    public var primaryField: String {{ {primary} }}}}"#,        properties = properties.join("\n"),        parameters = parameters.join(", "),        assignments = assignments.join("\n"),        primary = camel(spec.primary),    )}pub fn render_payload() -> String {    let header = generated_header("cotton-core — vault/payload.rs");    let count = SECRET_KINDS.len();    let kind_cases: Vec<String> = SECRET_KINDS        .iter()        .map(|spec| {            format!(                "    case {} = {}",                camel(spec.kind.as_str()),                swift_str(spec.kind.as_str())            )        })        .collect();    let structs: Vec<String> = SECRET_KINDS.iter().map(payload_struct).collect();    let payload_cases: Vec<String> = SECRET_KINDS        .iter()        .map(|spec| {            format!(                "    case {}({})",                camel(spec.kind.as_str()),                struct_name(spec)            )        })        .collect();    let kind_of: Vec<String> = SECRET_KINDS        .iter()        .map(|spec| {            let case = camel(spec.kind.as_str());            format!("        case .{case}: return .{case}")        })        .collect();    let primary_of: Vec<String> = SECRET_KINDS        .iter()        .map(|spec| {            let case = camel(spec.kind.as_str());            format!("        case .{case}(let payload): return payload.primaryField")        })        .collect();    let decode_cases: Vec<String> = SECRET_KINDS        .iter()        .map(|spec| {            format!(                "        case .{case}: self = .{case}(try {name}(from: decoder))",                case = camel(spec.kind.as_str()),                name = struct_name(spec)            )        })        .collect();    let encode_cases: Vec<String> = SECRET_KINDS        .iter()        .map(|spec| {            format!(                "        case .{}(let payload): try payload.encode(to: encoder)",                camel(spec.kind.as_str())            )        })        .collect();    format!(        r#"{header}//// The {count} shapes a secret's sealed bytes can take.//// Read from `crates/cotton-core/src/vault/payload.rs`, which is where a kind is// declared; a kind is NEVER declared here. The plain columns of the row —// `kind`, `name`, `site`, `username`, `service` — are what a list shows and what// search indexes, and they are deliberately NOT repeated in here: a second copy// of a name inside the sealed bytes would be a second answer to what a secret is// called, and the sealed one is the one nothing can read to check.//// The wire form is FLAT and tagged on `kind`, so `{{"kind":"login",// "password":"…"}}` is one object rather than a nested one. Swift's synthesized// `Codable` for an enum with associated values writes a nested shape instead,// which is why `init(from:)` and `encode(to:)` are spelled out below.//// An unset optional is ABSENT rather than null, at both ends: Swift's// synthesized coding uses `encodeIfPresent`/`decodeIfPresent` for an optional// property, and the Rust side carries `skip_serializing_if`. Two spellings of// nothing would be two payloads that are the same secret.import Foundation/// What a secret IS — the same string the row's `kind` column holds.public enum SecretKind: String, Sendable, Equatable, CaseIterable, Codable {{{kind_cases}}}{structs}/// One secret's payload — everything the person actually has to keep.public enum SecretPayload: Sendable, Equatable {{{payload_cases}    public var kind: SecretKind {{        switch self {{{kind_of}        }}    }}    /// The VALUE of the kind's primary field: what a hint is taken from, what a    /// `raw` placement writes, and what Copy copies.    public var primaryField: String {{        switch self {{{primary_of}        }}    }}    /// The last {hint} characters of the primary field — what a list shows    /// INSTEAD of the secret. Characters, not bytes: a value ending outside    /// ASCII must not be cut through the middle of one.    public var hint: String {{ SecretPayload.hint(of: primaryField) }}    public static func hint(of value: String) -> String {{        String(value.suffix({hint}))    }}    /// The sealed bytes, once they are open.    public static func decode(_ json: Data) throws -> SecretPayload {{        try JSONDecoder().decode(SecretPayload.self, from: json)    }}    /// The bytes to seal.    public func encoded() throws -> Data {{        try JSONEncoder().encode(self)    }}}}extension SecretPayload: Codable {{    private enum TagKey: String, CodingKey {{        case kind    }}    public init(from decoder: Decoder) throws {{        let tag = try decoder.container(keyedBy: TagKey.self).decode(SecretKind.self, forKey: .kind)        switch tag {{{decode_cases}        }}    }}    public func encode(to encoder: Encoder) throws {{        var tag = encoder.container(keyedBy: TagKey.self)        try tag.encode(kind, forKey: .kind)        switch self {{{encode_cases}        }}    }}}}"#,        kind_cases = kind_cases.join("\n"),        structs = structs.join("\n\n"),        payload_cases = payload_cases.join("\n"),        kind_of = kind_of.join("\n"),        primary_of = primary_of.join("\n"),        decode_cases = decode_cases.join("\n"),        encode_cases = encode_cases.join("\n"),        hint = HINT_CHARS,    )}/// The Android JVM twin. Field names and optionality come only from SECRET_KINDS.pub fn render_kotlin_payload() -> String {    let mut output = String::from(        "// GENERATED by `cotton-gen` from crates/cotton-core/src/vault/payload.rs. Do not edit.\n\         // Run pnpm gen:design; pnpm gen:design:check guards drift.\n\n\         package com.cottondb.android.generated\n\n\         import kotlinx.serialization.json.JsonNull\n\         import kotlinx.serialization.json.JsonObject\n\         import kotlinx.serialization.json.JsonPrimitive\n\         import kotlinx.serialization.json.buildJsonObject\n\         import kotlinx.serialization.json.put\n\n\         enum class SecretKind(val wireName: String) {\n",    );    for spec in SECRET_KINDS {        output.push_str(&format!(            "    {}(\"{}\"),\n",            pascal(spec.kind.as_str()), spec.kind.as_str()        ));    }    output.push_str(        "    ;\n\n    companion object {\n\         \x20       fun fromWire(value: String): SecretKind = entries.firstOrNull { it.wireName == value }\n\         \x20           ?: throw IllegalArgumentException(\"Unknown secret kind.\")\n\         \x20   }\n}\n\n\         /** Transient authenticated values. Never persist or log the payload JSON. */\n\         sealed interface SecretPayload {\n\         \x20   val kind: SecretKind\n\         \x20   val primaryField: String\n\         \x20   fun fieldsJson(): JsonObject\n\n\         \x20   fun payloadJson(): JsonObject = buildJsonObject {\n\         \x20       put(\"kind\", kind.wireName)\n\         \x20       fieldsJson().forEach { (key, value) -> put(key, value) }\n\         \x20   }\n\n",    );    for spec in SECRET_KINDS {        let name = pascal(spec.kind.as_str());        output.push_str(&format!("    data class {name}(\n"));        for field in spec.fields {            let optional = if field.required { "" } else { "? = null" };            output.push_str(&format!("        val {}: String{optional},\n", camel(field.name)));        }        output.push_str(&format!(            "    ) : SecretPayload {{\n        override val kind = SecretKind.{name}\n\             \x20       override val primaryField: String get() = {}\n\             \x20       override fun toString(): String = \"SecretPayload.{name}(<redacted>)\"\n\             \x20       override fun fieldsJson(): JsonObject = buildJsonObject {{\n",            camel(spec.primary)        ));        for field in spec.fields {            let member = camel(field.name);            let key = field.name;            if field.required {                output.push_str(&format!("            put(\"{key}\", {member})\n"));            } else {                output.push_str(&format!("            {member}?.let {{ put(\"{key}\", it) }}\n"));            }        }        output.push_str("        }\n    }\n\n");    }    output.push_str(        "    companion object {\n\         \x20       fun decode(value: JsonObject): SecretPayload = when (SecretKind.fromWire(value.requiredString(\"kind\"))) {\n",    );    for spec in SECRET_KINDS {        let name = pascal(spec.kind.as_str());        output.push_str(&format!("            SecretKind.{name} -> {name}(\n"));        for field in spec.fields {            let reader = if field.required { "requiredString" } else { "optionalString" };            output.push_str(&format!(                "                {} = value.{reader}(\"{}\"),\n",                camel(field.name), field.name            ));        }        output.push_str("            )\n");    }    output.push_str(        "        }\n    }\n}\n\n\         private fun JsonObject.requiredString(key: String): String =\n\         \x20   (this[key] as? JsonPrimitive)?.takeIf { it.isString }?.content\n\         \x20       ?: throw IllegalArgumentException(\"A required secret field is missing or invalid.\")\n\n\         private fun JsonObject.optionalString(key: String): String? {\n\         \x20   val value = this[key]\n\         \x20   if (value == null || value is JsonNull) return null\n\         \x20   return (value as? JsonPrimitive)?.takeIf { it.isString }?.content\n\         \x20       ?: throw IllegalArgumentException(\"An optional secret field is invalid.\")\n\         }\n",    );    output}#[cfg(test)]#[path = "payload_tests.rs"]mod tests;