//! JSON message envelope shared by host and plugin. //! //! Every exchange is one line of JSON per message: //! //! - Host → Plugin: a [`Request`] — `{"op": "...", ...params}`. //! - Plugin → Host (non-terminal): an [`Ask`] — `{"ask": "...", ...}` //! asking the host to render a UI element and reply with an //! [`Answer`] or [`Ack`]. //! - Plugin → Host (terminal): a [`Terminal`] — either //! `{"ok": true, "data": ...}` or `{"ok": false, "error": {...}}`. use serde::{Deserialize, Serialize}; use serde_json::Value; // --------------------------------------------------------------------------- // Handshake // --------------------------------------------------------------------------- /// The handshake request. Always the first message the host sends. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Hello { pub op: HelloOp, pub protocol_version: u32, } impl Hello { pub fn new(protocol_version: u32) -> Self { Self { op: HelloOp::Hello, protocol_version, } } } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum HelloOp { Hello, } /// Plugin's response to `hello`: its identity, protocol version, what /// ops it can service, and the schema of options (credentials + /// configuration) the host should collect before calling authed ops. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HelloData { pub name: String, pub protocol_version: u32, #[serde(default)] pub kind: Option, #[serde(default)] pub capabilities: Vec, #[serde(default)] pub options_schema: Vec, } /// One field in a plugin's options schema. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct OptionField { pub name: String, pub label: String, #[serde(default)] pub help: Option, /// `true` → mask on input, store in credentials file. #[serde(default)] pub secret: bool, /// `true` → prompt/flag must produce a value; the host refuses to /// call authed ops with a missing required field. #[serde(default)] pub required: bool, /// Optional default value for non-secret convenience options. #[serde(default)] pub default: Option, } // --------------------------------------------------------------------------- // Host → plugin messages // --------------------------------------------------------------------------- /// A request the host sends to the plugin after the handshake. /// /// The shape is `{"op": "", ...per-op params}`. Responses to /// non-terminal `ask` messages use [`Answer`] / [`Ack`] instead — /// they're not `Request`s and don't carry an `op`. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Request { pub op: String, #[serde(flatten)] pub params: Value, } /// Convenience wrapper for a host request carrying the currently- /// assembled credentials for the session. The plugin is expected to /// have consumed this via the `init` op before any authed call. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Credentials(pub Value); impl Credentials { pub fn object(obj: serde_json::Map) -> Self { Self(Value::Object(obj)) } pub fn empty() -> Self { Self(Value::Object(serde_json::Map::new())) } } // --------------------------------------------------------------------------- // Plugin → host messages // --------------------------------------------------------------------------- /// Anything the plugin can send back for a given op: a terminal `ok` /// / `error`, or a non-terminal `ask` that waits on the host. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum Response { Terminal(Terminal), Ask(Ask), } /// Terminal plugin response. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum Terminal { Ok { ok: OkTrue, #[serde(default)] data: Value, }, Err { ok: OkFalse, error: ErrorBody, }, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(try_from = "bool", into = "bool")] pub struct OkTrue; impl TryFrom for OkTrue { type Error = &'static str; fn try_from(v: bool) -> Result { if v { Ok(Self) } else { Err("expected true") } } } impl From for bool { fn from(_: OkTrue) -> Self { true } } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)] #[serde(try_from = "bool", into = "bool")] pub struct OkFalse; impl TryFrom for OkFalse { type Error = &'static str; fn try_from(v: bool) -> Result { if !v { Ok(Self) } else { Err("expected false") } } } impl From for bool { fn from(_: OkFalse) -> Self { false } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ErrorBody { pub code: String, pub message: String, #[serde(default)] pub retryable: bool, } /// Non-terminal "I need something from the human" message. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Ask { #[serde(flatten)] pub kind: AskKind, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "ask", rename_all = "snake_case")] pub enum AskKind { Prompt { name: String, label: String, #[serde(default)] secret: bool, }, Select { name: String, label: String, options: Vec, }, Confirm { name: String, label: String, }, OpenUrl { url: String, }, Info { text: String, }, } /// Host's response to a [`AskKind::Prompt`] / [`AskKind::Select`] / /// [`AskKind::Confirm`]. Keyed by the `name` of the ask, mirroring the /// plugin's field names. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Answer { pub answer: Value, } /// Host's acknowledgement for a [`AskKind::OpenUrl`] / [`AskKind::Info`]. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Ack { pub ack: bool, } /// A capability the host needs that the plugin didn't advertise. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CapabilityMissing { pub capability: String, } /// Current protocol version understood by this crate. pub const PROTOCOL_VERSION: u32 = 1; #[cfg(test)] mod tests { use super::*; use serde_json::json; #[test] fn hello_serialises_as_expected() { let m = Hello::new(1); let got = serde_json::to_value(&m).unwrap(); assert_eq!(got, json!({"op": "hello", "protocol_version": 1})); } #[test] fn ok_and_err_are_disambiguated_by_untagged_ok_bool() { let ok_json = json!({"ok": true, "data": {"x": 1}}); let err_json = json!({"ok": false, "error": {"code": "x", "message": "y"}}); let ok: Terminal = serde_json::from_value(ok_json).unwrap(); let err: Terminal = serde_json::from_value(err_json).unwrap(); assert!(matches!(ok, Terminal::Ok { .. })); assert!(matches!(err, Terminal::Err { .. })); } #[test] fn ask_prompt_round_trips() { let a = Ask { kind: AskKind::Prompt { name: "api_token".into(), label: "API token".into(), secret: true, }, }; let value = serde_json::to_value(&a).unwrap(); assert_eq!( value, json!({ "ask": "prompt", "name": "api_token", "label": "API token", "secret": true, }) ); let back: Ask = serde_json::from_value(value).unwrap(); match back.kind { AskKind::Prompt { name, label, secret, } => { assert_eq!(name, "api_token"); assert_eq!(label, "API token"); assert!(secret); } _ => panic!("expected prompt"), } } #[test] fn response_dispatches_ask_vs_terminal() { let ask: Response = serde_json::from_value(json!({"ask": "info", "text": "hi"})).unwrap(); assert!(matches!(ask, Response::Ask(_))); let ok: Response = serde_json::from_value(json!({"ok": true, "data": {}})).unwrap(); assert!(matches!(ok, Response::Terminal(Terminal::Ok { .. }))); } #[test] fn hello_data_parses_capabilities_and_schema() { let v = json!({ "name": "cloudflare", "protocol_version": 1, "kind": "dns", "capabilities": ["list_txt", "upsert_txt"], "options_schema": [ {"name": "api_token", "label": "API token", "secret": true, "required": true} ] }); let hd: HelloData = serde_json::from_value(v).unwrap(); assert_eq!(hd.name, "cloudflare"); assert_eq!(hd.capabilities, vec!["list_txt", "upsert_txt"]); assert_eq!(hd.options_schema.len(), 1); assert!(hd.options_schema[0].secret); assert!(hd.options_schema[0].required); } }