use crate::net::{ NetCommand, WebhookOperation, wire::{WebhookInfo, WebhookRequest}, }; use std::time::{Duration, Instant}; /// A new connection gets a fresh generation, even when reconnecting to the same server. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Scope { pub connection: u64, pub channel_id: String, pub channel_name: String, pub guild_id: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { Incoming, GitHub, Outgoing, } impl Kind { pub fn from_index(index: i32) -> Option { match index { 0 => Some(Self::Incoming), 1 => Some(Self::GitHub), 2 => Some(Self::Outgoing), _ => None, } } } pub struct Form { pub name: String, pub kind: Kind, pub endpoint: String, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { Disconnected, InvalidChannel, Busy, PermissionDenied, InvalidName, InvalidEndpoint, MissingHook, RequestFailed, RateLimited, TimedOut, InvalidResponse, SecretVisible, } impl Error { pub fn message(self) -> &'static str { match self { Self::Disconnected => "Connect to a server before managing webhooks.", Self::InvalidChannel => "Choose a server text channel before managing webhooks.", Self::Busy => "Wait for the current webhook request to finish.", Self::PermissionDenied => { "Only the server owner or members with Manage Webhooks can change integrations." } Self::InvalidName => "Use a webhook name between 1 and 64 characters.", Self::InvalidEndpoint => { "Enter an HTTPS destination without credentials, query parameters or a fragment." } Self::MissingHook => "This webhook is no longer available. Refresh the list.", Self::RequestFailed => { "The server could not complete this webhook request. Refresh before trying again." } Self::RateLimited => { "Too many webhook requests, or this channel has reached its integration limit." } Self::TimedOut => { "The request timed out. Its result is unknown; refresh before making another change." } Self::InvalidResponse => { "The server returned an invalid webhook response. Refresh before trying again." } Self::SecretVisible => "Copy or hide the current secret before making another change.", } } } struct Secret(Vec); impl Drop for Secret { fn drop(&mut self) { self.0.fill(0) } } struct Pending { request_id: String, operation: WebhookOperation, hook_id: String, deadline: Instant, } /// One outstanding request with explicit correlation; late responses are always discarded. #[derive(Default)] pub struct Controller { scope: Option, connected: bool, open: bool, allowed: bool, hooks: Vec, pending: Option, secret: Option, secret_hook: Option, confirmation: Option<(WebhookOperation, String)>, error: Option, } impl Controller { pub fn scope(&self) -> Option<&Scope> { self.scope.as_ref() } pub fn hooks(&self) -> &[WebhookInfo] { &self.hooks } pub fn error(&self) -> Option { self.error } pub fn is_open(&self) -> bool { self.open } pub fn busy(&self) -> bool { self.pending.is_some() } pub fn allowed(&self) -> bool { self.allowed && self.connected } pub fn secret(&self) -> &str { self.secret .as_ref() .and_then(|s| std::str::from_utf8(&s.0).ok()) .unwrap_or_default() } pub fn secret_hook(&self) -> Option<&WebhookInfo> { self.secret_hook.as_ref() } pub fn confirmation(&self) -> Option<(bool, &str)> { self.confirmation .as_ref() .map(|(op, id)| (matches!(op, WebhookOperation::Revoke), id.as_str())) } pub fn show_error(&mut self, error: Error) { self.error = Some(error) } pub fn open(&mut self, scope: Scope, connected: bool) -> Result { self.close(); self.scope = Some(scope); self.connected = connected; self.open = true; self.allowed = false; self.hooks.clear(); self.error = None; if !connected { return self.fail(Error::Disconnected); } if self .scope .as_ref() .is_none_or(|s| s.channel_id.is_empty() || s.guild_id.is_empty()) { return self.fail(Error::InvalidChannel); } self.refresh() } pub fn close(&mut self) { self.open = false; self.pending = None; self.confirmation = None; self.hide_secret(); } pub fn disconnected(&mut self) { self.connected = false; self.allowed = false; self.pending = None; self.confirmation = None; self.hooks.clear(); self.hide_secret(); if self.open { self.error = Some(Error::Disconnected) } } pub fn hide_secret(&mut self) { self.secret = None; self.secret_hook = None; } fn fail(&mut self, error: Error) -> Result { self.error = Some(error); Err(error) } fn ready(&mut self, write: bool) -> Result<(), Error> { if !self.connected || !self.open { return self.fail(Error::Disconnected); } if self.pending.is_some() { return self.fail(Error::Busy); } if write && !self.allowed { return self.fail(Error::PermissionDenied); } if self.secret.is_some() { return self.fail(Error::SecretVisible); } Ok(()) } fn command(&mut self, operation: WebhookOperation, mut request: WebhookRequest) -> NetCommand { let id = uuid::Uuid::new_v4().to_string(); request.request_id = id.clone(); self.pending = Some(Pending { request_id: id, operation, hook_id: request.id.clone(), deadline: Instant::now() + Duration::from_secs(15), }); self.error = None; self.confirmation = None; NetCommand::Webhook { operation, request } } pub fn refresh(&mut self) -> Result { self.ready(false)?; let Some(scope) = &self.scope else { return self.fail(Error::InvalidChannel); }; Ok(self.command( WebhookOperation::List, WebhookRequest { channel_id: scope.channel_id.clone(), ..Default::default() }, )) } pub fn create(&mut self, form: Form) -> Result { self.ready(true)?; let name = form.name.trim(); if name.is_empty() || name.chars().count() > 64 || name.chars().any(char::is_control) { return self.fail(Error::InvalidName); } let endpoint = form.endpoint.trim(); if form.kind == Kind::Outgoing && (!endpoint.starts_with("https://") || endpoint.len() > 2048 || endpoint.contains(['?', '#', '@']) || endpoint.chars().any(char::is_control)) { return self.fail(Error::InvalidEndpoint); } let Some(scope) = &self.scope else { return self.fail(Error::InvalidChannel); }; let (direction, provider) = match form.kind { Kind::Incoming => ("incoming", "generic"), Kind::GitHub => ("incoming", "github"), Kind::Outgoing => ("outgoing", "generic"), }; let req = WebhookRequest { channel_id: scope.channel_id.clone(), name: name.into(), direction: direction.into(), provider: provider.into(), endpoint: if form.kind == Kind::Outgoing { endpoint.into() } else { String::new() }, ..Default::default() }; Ok(self.command(WebhookOperation::Create, req)) } pub fn ask_rotate(&mut self, id: &str) -> Result<(), Error> { self.ask(WebhookOperation::Rotate, id) } pub fn ask_revoke(&mut self, id: &str) -> Result<(), Error> { self.ask(WebhookOperation::Revoke, id) } fn ask(&mut self, operation: WebhookOperation, id: &str) -> Result<(), Error> { self.ready(true)?; if !self.hooks.iter().any(|h| h.id == id && !h.revoked) { return self.fail(Error::MissingHook); } self.confirmation = Some((operation, id.into())); self.error = None; Ok(()) } pub fn cancel_confirmation(&mut self) { self.confirmation = None; } pub fn confirm(&mut self) -> Result { self.ready(true)?; let Some((operation, id)) = self.confirmation.take() else { return self.fail(Error::MissingHook); }; Ok(self.command( operation, WebhookRequest { id, channel_id: self .scope .as_ref() .map(|s| s.channel_id.clone()) .unwrap_or_default(), ..Default::default() }, )) } /// This timeout never claims the mutation failed: the server may already have committed it. pub fn expire(&mut self, now: Instant) -> bool { if self.pending.as_ref().is_some_and(|p| now >= p.deadline) { self.pending = None; self.allowed = false; self.error = Some(Error::TimedOut); true } else { false } } fn take_pending(&mut self, id: &str) -> Option { if self.pending.as_ref().is_some_and(|p| p.request_id == id) { self.pending.take() } else { None } } fn valid_hook(&self, h: &WebhookInfo) -> bool { self.scope .as_ref() .is_some_and(|s| h.channel_id == s.channel_id) && !h.id.is_empty() && h.id.len() <= 128 && h.name.chars().count() <= 64 && h.endpoint.len() <= 2048 && matches!( (h.direction.as_str(), h.provider.as_str()), ("incoming", "generic" | "github") | ("outgoing", "generic") ) } pub fn receive_list(&mut self, request_id: &str, hooks: Vec) -> bool { let Some(pending) = self.take_pending(request_id) else { return false; }; if !matches!(pending.operation, WebhookOperation::List) || hooks.len() > 32 || hooks.iter().any(|h| !self.valid_hook(h) || h.revoked) { self.allowed = false; self.error = Some(Error::InvalidResponse); return true; } let mut ids = std::collections::HashSet::new(); if hooks.iter().any(|h| !ids.insert(&h.id)) { self.allowed = false; self.error = Some(Error::InvalidResponse); return true; } self.hooks = hooks; self.allowed = true; self.error = None; true } pub fn receive_result( &mut self, request_id: &str, hook: Option, secret: String, ) -> bool { let Some(pending) = self.take_pending(request_id) else { return false; }; let Some(hook) = hook else { self.allowed = false; self.error = Some(Error::InvalidResponse); return true; }; let revoke = matches!(pending.operation, WebhookOperation::Revoke); if matches!(pending.operation, WebhookOperation::List) || !self.valid_hook(&hook) || (!matches!(pending.operation, WebhookOperation::Create) && hook.id != pending.hook_id) || hook.revoked != revoke || (revoke && !secret.is_empty()) || (!revoke && (secret.len() != 64 || !secret.bytes().all(|b| b.is_ascii_hexdigit()))) { self.allowed = false; self.error = Some(Error::InvalidResponse); return true; } self.hooks.retain(|h| h.id != hook.id); if !revoke { self.hooks.push(hook.clone()); self.secret = Some(Secret(secret.into_bytes())); self.secret_hook = Some(hook); } self.error = None; true } pub fn receive_error(&mut self, request_id: &str, code: u32) -> bool { if self.take_pending(request_id).is_none() { return false; } self.hide_secret(); self.confirmation = None; self.error = Some(match code { 4 => { self.allowed = false; self.hooks.clear(); Error::PermissionDenied } 6 => Error::RateLimited, _ => Error::RequestFailed, }); true } }