use std::collections::BTreeMap;
use std::time::Duration;
use anyhow::{Result, bail};
use zeroize::Zeroizing;
pub type Credential = Zeroizing<String>;
pub type Secrets = BTreeMap<String, Credential>;
pub type Options = BTreeMap<String, String>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capabilities {
pub buttons: bool,
pub button_bytes: usize,
pub max_text: usize,
pub poll_wait: std::time::Duration,
}
impl Capabilities {
pub fn uses_buttons(&self) -> bool {
self.buttons && self.button_bytes >= super::answer::BUTTON_LEN
}
}
pub const MIN_TEXT: usize = 1024;
#[derive(Debug, Clone, Copy)]
pub struct Field {
pub key: &'static str,
pub ask: &'static str,
pub secret: bool,
pub valid: fn(&str) -> bool,
}
pub struct Spec {
pub name: &'static str,
pub title: &'static str,
pub capabilities: Capabilities,
pub fields: &'static [Field],
pub user_id: &'static str,
pub valid_user: fn(&str) -> bool,
pub open: fn(&Secrets, &Options) -> Result<Box<dyn Channel>>,
pub next_steps: fn(&str) -> String,
pub revoke: &'static str,
}
impl std::fmt::Debug for Spec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Spec")
.field("name", &self.name)
.field("capabilities", &self.capabilities)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Choice {
pub label: &'static str,
pub data: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Prompt {
pub text: String,
pub choices: Vec<Choice>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Reply {
pub from: String,
pub name: String,
pub button: Option<String>,
pub text: Option<String>,
pub handle: String,
}
pub trait Channel: Send {
fn account(&mut self) -> Result<String>;
fn send(&mut self, to: &str, prompt: &Prompt) -> Result<()>;
fn notify(&mut self, to: &str, text: &str) -> Result<()>;
fn poll(&mut self, wait: Duration) -> Result<Vec<Reply>>;
fn handled(&mut self) {}
fn settle(&mut self, reply: &Reply, text: &str) -> Result<()>;
}
const RESERVED: &[&str] = &["requests", "answers", "used"];
#[derive(Debug, Clone, Copy)]
pub struct Registry(pub &'static [&'static Spec]);
impl Registry {
pub fn find(&self, name: &str) -> Result<&'static Spec> {
self.check()?;
match self.0.iter().find(|spec| spec.name == name) {
Some(spec) => Ok(spec),
None => bail!(
"this release does not know the channel `{}`; it knows: {}",
crate::render::clean(name),
self.names().join(", ")
),
}
}
pub fn names(&self) -> Vec<&'static str> {
self.0.iter().map(|spec| spec.name).collect()
}
pub fn check(&self) -> Result<()> {
let mut seen = std::collections::BTreeSet::new();
for spec in self.0 {
let name = spec.name;
if name.is_empty()
|| name.len() > 32
|| !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|| RESERVED.contains(&name)
{
bail!("`{name}` cannot name a channel");
}
if !seen.insert(name) {
bail!("`{name}` is listed twice");
}
if spec.capabilities.max_text < MIN_TEXT {
bail!("{name}: messages under {MIN_TEXT} characters cannot hold a prompt");
}
let keys: std::collections::BTreeSet<_> = spec.fields.iter().map(|f| f.key).collect();
if keys.len() != spec.fields.len() {
bail!("{name}: two fields share a key");
}
if let Some(field) = spec.fields.iter().find(|f| {
f.key.is_empty()
|| !f
.key
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
}) {
bail!("{name}: `{}` cannot name a field", field.key);
}
}
Ok(())
}
pub fn approver(&self, connected: &'static Spec, given: &str) -> Result<String> {
let (spec, local) = match given.split_once(':') {
Some((prefix, local)) if self.0.iter().any(|s| s.name == prefix) => {
(self.find(prefix)?, local)
}
_ => (connected, given),
};
if spec.name != connected.name {
bail!(
"`{}` is a {} id, but the connected channel is {}",
crate::render::clean(given),
spec.title,
connected.title
);
}
if !(spec.valid_user)(local) {
bail!("`{}` is not {}", crate::render::clean(local), spec.user_id);
}
Ok(approver_id(spec.name, local))
}
}
pub fn approver_id(name: &str, local: &str) -> String {
format!("{name}:{local}")
}
pub fn local_id<'a>(name: &str, approver: &'a str) -> Option<&'a str> {
approver
.strip_prefix(name)
.and_then(|rest| rest.strip_prefix(':'))
}