Skip to content

Commit

Permalink
add extract_interaction()
Browse files Browse the repository at this point in the history
  • Loading branch information
Monadic-Cat committed Jul 25, 2023
1 parent 36587c6 commit e7286b8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
3 changes: 2 additions & 1 deletion twilight-util/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ version = "0.15.2"
[dependencies]
twilight-model = { default-features = false, optional = true, path = "../twilight-model", version = "0.15.2" }
twilight-validate = { default-features = false, optional = true, path = "../twilight-validate", version = "0.15.1" }
serde_json = { default-features = false, optional = true, version = "1.0.96" }

# Signature validation
ed25519-dalek = { version = "2.0.0-rc.2", optional = true, default-features = false}
Expand All @@ -30,7 +31,7 @@ builder = ["dep:twilight-model", "dep:twilight-validate"]
link = ["dep:twilight-model"]
permission-calculator = ["dep:twilight-model"]
snowflake = ["dep:twilight-model"]
signature-validation = ["dep:ed25519-dalek", "dep:hex"]
signature-validation = ["dep:ed25519-dalek", "dep:hex", "dep:serde_json"]
full = ["builder", "link", "permission-calculator", "snowflake", "signature-validation"]

[package.metadata.docs.rs]
Expand Down
26 changes: 26 additions & 0 deletions twilight-util/src/signature_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! an HTTPS endpoint to send Interactions to.

use ed25519_dalek::{Signature, SignatureError, VerifyingKey};
use twilight_model::application::interaction::Interaction;

#[derive(Debug)]
pub struct FromHexError(hex::FromHexError);
Expand Down Expand Up @@ -66,3 +67,28 @@ pub fn check_signature(
Err(e) => Err(SignatureValidationFailure::InvalidSignature(SigError(e))),
}
}

pub enum ExtractFailure {
Signature(SignatureValidationFailure),
Deserialize(serde_json::Error),
}
impl From<SignatureValidationFailure> for ExtractFailure {
fn from(value: SignatureValidationFailure) -> Self {
Self::Signature(value)
}
}
impl From<serde_json::Error> for ExtractFailure {
fn from(value: serde_json::Error) -> Self {
Self::Deserialize(value)
}
}

pub fn extract_interaction(
sig: &[u8],
timestamp: &[u8],
body: &[u8],
key: &Key,
) -> Result<Interaction, ExtractFailure> {
check_signature(sig, timestamp, body, key)?;
Ok(serde_json::from_slice(body)?)
}

0 comments on commit e7286b8

Please sign in to comment.