Something went wrong. Try again.
An HTTP Interactions Middleware for Grom
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import gleam/dynamic/decodeimport gleam/http/request.{type Request}import gleam/http/response.{type Response}import gleam/intimport gleam/jsonimport gleam/resultimport gromimport kryptos/eddsaimport status_code
type PingInteraction { PingInteraction}
fn ping_interaction_decoder() -> decode.Decoder(PingInteraction) { use type_ <- decode.field("type", decode.int) case type_ { 1 -> decode.success(PingInteraction) _ -> decode.failure(PingInteraction, "PingInteraction") }}
pub type SecurityError { /// A request was made without a `x-signature-ed25519` header. HttpRequestSignatureNotProvided /// A request was made without a `x-signature-timestamp` header. HttpRequestTimestampNotProvided /// A request was made where the `x-signature-ed25519` was not a valid hexadecimal number. HttpRequestSignatureNotValidHexadecimal /// A request was made with the correct headers, however verifying that the message: /// - was intended for your app /// - was sent from Discord /// has failed. /// /// This could happen for several reasons: /// - an automated test was performed by Discord, verifying whether your app validates security headers (most common) /// - you provided an inappropriate public key (for example, another app's) /// - there was a forgery attempt HttpRequestVerificationFailed}
pub type InteractionError { /// A properly validated request was made, but it couldn't be parsed as an interaction. /// /// This isn't to be expected too often. /// /// Returns a 400 "bad request" response. CouldNotParseInteraction(json.DecodeError) /// An error has happened while trying to verify the request's security headers. /// /// This is to be expected - discord often does "tests", verifying that your webhook validates security headers properly. /// /// Returns a 401 "unauthorized" response. CouldNotValidateSecurityHeaders(SecurityError)}
pub opaque type PublicKey { PublicKey(key: eddsa.PublicKey)}
pub fn handle_interaction_request( request: Request(String), public_key public_key: PublicKey, handler next: fn(Result(grom.Interaction, InteractionError)) -> Nil,) -> Response(String) { case validate_security_headers(request, public_key) { Ok(_) -> handle_validated_request(request, next) Error(unauthorized) -> { next(Error(CouldNotValidateSecurityHeaders(unauthorized)))
response.new(status_code.unauthorized) } }}
pub type PublicKeyValidationError { /// The public key you provided is not a valid hexadecimal number. PublicKeyNotValidHexadecimal /// Your public key's length as a number is not 32 bytes. PublicKeyHasImproperLength}
pub fn public_key_from_string( key: String,) -> Result(PublicKey, PublicKeyValidationError) { use key <- result.try( key |> int.base_parse(16) |> result.replace_error(PublicKeyNotValidHexadecimal), )
use key <- result.try( eddsa.public_key_from_bytes(eddsa.Ed25519, <<key:size(32)-unit(8)>>) |> result.replace_error(PublicKeyHasImproperLength), )
Ok(PublicKey(key:))}
fn handle_validated_request( request: Request(String), next: fn(Result(grom.Interaction, InteractionError)) -> Nil,) -> Response(String) { let ping = json.parse(request.body, ping_interaction_decoder())
case ping { Ok(_) -> handle_ping_interaction() Error(_) -> handle_interaction(request, next) }}
fn handle_interaction( request: Request(String), next: fn(Result(grom.Interaction, InteractionError)) -> Nil,) -> Response(String) { let interaction = json.parse(request.body, grom.interaction_decoder())
case interaction { Ok(interaction) -> { next(Ok(interaction)) response.new(status_code.accepted) } Error(err) -> { next(Error(CouldNotParseInteraction(err))) response.new(status_code.bad_request) } }}
fn validate_security_headers( request: Request(String), public_key: PublicKey,) -> Result(Nil, SecurityError) { use signature <- result.try( request |> request.get_header("x-signature-ed25519") |> result.replace_error(HttpRequestSignatureNotProvided), )
use signature <- result.try( signature |> int.base_parse(16) |> result.replace_error(HttpRequestSignatureNotValidHexadecimal), )
use timestamp <- result.try( request |> request.get_header("x-signature-timestamp") |> result.replace_error(HttpRequestTimestampNotProvided), )
// Ed25519 signatures are 64 bytes let signature = <<signature:size(64)-unit(8)>> let message = <<{ timestamp <> request.body }:utf8>>
let is_verified = eddsa.verify(public_key.key, message, signature)
case is_verified { True -> Ok(Nil) False -> Error(HttpRequestVerificationFailed) }}
fn handle_ping_interaction() -> Response(String) { let body = [#("type", json.int(1))] |> json.object |> json.to_string
response.new(status_code.ok) |> response.set_header("content-type", "application/json") |> response.set_body(body)}