tilo_actions/remote/confirmation.rs
1//! Asking the person, on their own device, about one invocation one of their
2//! devices answers.
3//!
4//! An action the person's grants leave to them asks first. At a device that
5//! is not theirs there is nobody at its screen to ask, so the question
6//! travels to one of their own devices and back. What comes back names that
7//! one invocation; nothing about a grant changes.
8
9use serde::{Deserialize, Serialize};
10
11/// Explicit confirmation carried with an invocation.
12#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13pub enum Confirmation {
14 /// The host that placed a browser window hands it a call of a key its person let operate
15 /// web pages: their standing permission, not an answer to an ask. Only
16 /// `tilo_action_services::browser::host_answered` reads it, from that host's link alone; nothing else
17 /// takes it as a confirmation, so a caller that writes it is asked like one that wrote none.
18 Operated,
19 /// The caller typed the phrase the contract asks for.
20 Phrase(String),
21 /// The person approved the asked invocation record this call was kept as
22 /// ([`super::asked`]). Only the dispatch sets it, when it admits the call
23 /// again on their answer; admission drops it from anything a caller sent.
24 Asked(super::asked::Approval),
25}
26
27/// What a confirmation is bound to of an invocation's arguments: their
28/// digest, so a provider that keeps the person's answer for one invocation keeps
29/// no raw input, and arguments other than the ones answered find no answer.
30/// `argument` is the invocation's argument as it travels
31/// ([`InvokeArgument::to_slot`](super::InvokeArgument::to_slot)).
32#[must_use]
33pub fn argument_digest(argument: Option<&str>) -> [u8; 32] {
34 let mut hasher = blake3::Hasher::new();
35 match argument {
36 Some(value) => {
37 hasher.update(b"some\0");
38 hasher.update(value.as_bytes());
39 }
40 None => {
41 hasher.update(b"none\0");
42 }
43 }
44 *hasher.finalize().as_bytes()
45}
46
47/// A question a device of the person's puts to them on another of their
48/// own devices: one invocation of an action their grants leave to them.
49///
50/// The device asking is the transport-authenticated one, so the labels here
51/// are shown as that device's own words; the answer names this one
52/// invocation and nothing else.
53#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(deny_unknown_fields)]
55pub struct ConfirmationQuestion {
56 /// Names this question, so the answer names it back.
57 pub id: [u8; 32],
58 /// The device that asks, as it is labelled to the person.
59 pub device_label: String,
60 /// The agent the invocation is by, by its id: the device asks for an agent it acts for
61 /// over its own session. Empty for the person's own invocation.
62 #[serde(default)]
63 pub agent: String,
64 /// The workspace the invocation runs in.
65 pub workspace: String,
66 /// The group the invocation is a step of, by the title its agent gave it;
67 /// empty when it named none.
68 pub title: String,
69 /// The action by the title its app declares, and the record it acts on
70 /// by its name, as the asking device labels them.
71 pub action_label: String,
72 pub resource_label: String,
73 /// The arguments it would run with, as a reviewer reads them
74 /// ([`Draft::summary`](crate::draft::Draft::summary)): secrets withheld.
75 pub arguments: Vec<(String, String)>,
76 /// What the action risks, by [`RiskLevel::name`](crate::RiskLevel::name).
77 pub risk: String,
78 /// What it is able to do, by [`ActionKind`](crate::ActionKind)'s name
79 /// (`read`, `undoable`, `outside`); empty when the asker cannot say.
80 pub kind: String,
81 /// Whether Undo takes it back
82 /// ([`ActionContract::can_be_undone`](crate::ActionContract::can_be_undone)).
83 pub undoable: bool,
84 /// What the agent asks in its own words, where it asks the person
85 /// something rather than to allow an action ([`ASK`]): the action fields
86 /// above are empty then, and the person answers with one of its choices.
87 #[serde(default)]
88 pub ask: Option<PersonAsk>,
89}
90
91/// The person's answer to a [`ConfirmationQuestion`].
92#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
93pub enum ConfirmationReply {
94 /// Run this one invocation.
95 AllowOnce,
96 /// Do not carry it out; for a [`PersonAsk`], the person chose not to answer.
97 Deny,
98 /// The person's answer to a [`PersonAsk`]: one of its choices.
99 Replied(String),
100}
101
102/// The provider an agent asks its person under: its [`ASK`] puts a
103/// [`PersonAsk`] to the person the agent acts for, on their own devices, and
104/// succeeds with their answer ([`PersonAnswer`]).
105pub const ASK_PROVIDER: &str = "tilo.person";
106/// The resource [`ASK`] is an action of: the person the caller acts for.
107pub const ASK_RESOURCE: &str = "person";
108/// Ask the person a question and wait for their answer.
109pub const ASK: &str = "ask";
110/// The longest question, in characters.
111pub const MAX_ASK_CHARS: usize = 2_000;
112/// The most choices a question offers.
113pub const MAX_ASK_CHOICES: usize = 8;
114/// The longest choice, in characters.
115pub const MAX_CHOICE_CHARS: usize = 80;
116
117/// What a question with no choices is refused with: words come as a reply in the conversation,
118/// and a secret only through the vault's `ask`.
119pub const ASK_WITH_CHOICES: &str = "choices: a question is answered only with one of its \
120 choices, at least one. To hear your person in their own words, ask in the conversation \
121 and read their reply there. For a password, a key or another secret, use the vault's \
122 `ask` (Ask your person for a secret).";
123
124/// What [`ASK`] is invoked on.
125#[must_use]
126pub fn ask_target() -> super::RemoteActionTarget {
127 super::RemoteActionTarget {
128 provider: ASK_PROVIDER.to_owned(),
129 address: super::ActionAddress::new(ASK_RESOURCE, ASK),
130 }
131}
132
133/// Whether `target` asks the person.
134#[must_use]
135pub fn is_ask(target: &super::RemoteActionTarget) -> bool {
136 target.provider == ASK_PROVIDER
137 && target.address.resource == ASK_RESOURCE
138 && target.address.action == ASK
139}
140
141/// A question an agent puts to its person in its own words, answered with one of its choices.
142/// It waits on their devices until they answer. Nothing in it holds words of the person's:
143/// what they want to say in their own words they say in the conversation.
144#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
145#[serde(default, deny_unknown_fields)]
146pub struct PersonAsk {
147 /// The question, as the agent words it.
148 pub question: String,
149 /// The answers the person picks from, in order: at least one.
150 pub choices: Vec<String>,
151}
152
153impl PersonAsk {
154 /// The question as it is put: trimmed, with its choices.
155 ///
156 /// # Errors
157 /// What makes it no question to put: empty, too long, no choices ([`ASK_WITH_CHOICES`]), or
158 /// choices that are empty, repeated, too long or too many.
159 pub fn checked(mut self) -> Result<Self, String> {
160 let question = self.question.trim().to_owned();
161 self.question = question;
162 if self.question.is_empty() || self.question.chars().count() > MAX_ASK_CHARS {
163 return Err(format!("question: 1 to {MAX_ASK_CHARS} characters"));
164 }
165 if self.choices.is_empty() {
166 return Err(ASK_WITH_CHOICES.to_owned());
167 }
168 if self.choices.len() > MAX_ASK_CHOICES {
169 return Err(format!("choices: at most {MAX_ASK_CHOICES}"));
170 }
171 for choice in &mut self.choices {
172 *choice = choice.trim().to_owned();
173 }
174 if self.choices.iter().any(|choice| {
175 choice.is_empty()
176 || choice.chars().count() > MAX_CHOICE_CHARS
177 || choice.chars().any(char::is_control)
178 }) {
179 return Err(format!(
180 "choices: each 1 to {MAX_CHOICE_CHARS} characters on one line"
181 ));
182 }
183 let mut seen = std::collections::HashSet::new();
184 if !self.choices.iter().all(|choice| seen.insert(choice)) {
185 return Err("choices: each once".to_owned());
186 }
187 Ok(self)
188 }
189
190 /// Whether `reply` answers it: one of its choices.
191 #[must_use]
192 pub fn answered_by(&self, reply: &str) -> bool {
193 let reply = reply.trim();
194 self.choices.iter().any(|choice| choice == reply)
195 }
196}
197
198/// What [`ASK`] succeeds with.
199#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(rename_all = "snake_case")]
201pub enum PersonAnswer {
202 /// The choice the person picked, as the question words it.
203 Answered { choice: String },
204 /// The person chose not to answer.
205 Declined,
206}
207
208/// The answer a provider that cannot ask has for a [`RemoteActionMessage::ConfirmationRequest`].
209#[must_use]
210pub(crate) fn unanswered(
211 correlation: u64,
212 error: super::ActionCallError,
213) -> super::RemoteActionMessage {
214 super::RemoteActionMessage::ConfirmationResponse {
215 correlation,
216 result: Err(error),
217 }
218}