Skip to main content

djs_rs/
http_interactions.rs

1//! HTTP interactions (D-395, D-398–D-403): answering the interactions Discord posts to the
2//! app's **Interactions Endpoint URL** with the same routes and handlers as a gateway bot.
3//!
4//! An app with an Interactions Endpoint URL receives its commands, components, autocomplete
5//! and modals as HTTP `POST` requests instead of gateway events, so it needs no long-lived
6//! connection: it can run in any HTTP server, or on a serverless platform such as Cloudflare
7//! Workers. [`Client::interactions_endpoint`](crate::Client::interactions_endpoint) makes an
8//! [`InteractionsEndpoint`] from a client; its [`handle`](InteractionsEndpoint::handle) takes
9//! a request's `X-Signature-Ed25519` and `X-Signature-Timestamp` headers and its body, and
10//! returns the [`HttpResponse`] to send back. There is no HTTP server in djs-rs: mount
11//! `handle` in the one the bot already uses.
12//!
13//! What `handle` does, in order:
14//!
15//! 1. Verifies the request ([Discord's security
16//!    rules](https://docs.discord.com/developers/interactions/overview#setting-up-an-endpoint-validating-security-request-headers)):
17//!    the Ed25519 signature of the timestamp and body under the app's public key, and a
18//!    timestamp at most 5 minutes from now against replayed requests (D-401). Otherwise
19//!    `401`.
20//! 2. Answers a `PING` (sent when the URL is saved in the Developer Portal) with a `PONG`.
21//! 3. Dispatches the interaction like a gateway `INTERACTION_CREATE`: the cache, the event
22//!    streams and collectors, the [`InteractionCreate`](crate::Events::InteractionCreate)
23//!    handlers, then the routes ([`Client::command`](crate::Client::command) and the rest).
24//! 4. Returns as soon as a handler gives the initial response (`reply`, `defer_reply`,
25//!    `update`, `show_modal`, …): it becomes the HTTP body, with no REST request (D-399).
26//!    The handlers' remaining work (for example the follow-up after a deferral) is the
27//!    returned future, which the server must run: `tokio::spawn` natively,
28//!    `ctx.wait_until` on Cloudflare Workers.
29//!
30//! | Status | When | Body |
31//! |---|---|---|
32//! | `200` | the initial response, or the `PONG` | its JSON (`Content-Type: application/json`) |
33//! | `202` | the initial response had files: it went through REST instead | empty |
34//! | `400` | the body is not an interaction | empty |
35//! | `401` | the signature or the timestamp is invalid | empty |
36//! | `500` | the handlers finished without an initial response | empty |
37//!
38//! Every handler runs one after another for the request, whatever the client's
39//! [`HandlerMode`](crate::HandlerMode). Gateway-only parts stay silent: no other event
40//! reaches the handlers, and [`Context::shard`](crate::Context::shard) is the guild's shard
41//! only if the client is also logged in (else a
42//! [detached](djs_gateway::MessageSender::detached) sender, D-403). Collectors only see
43//! the interactions this same client handles, so on a platform that spreads requests over
44//! many instances they may never see the next one.
45//!
46//! # On Cloudflare Workers (`wasm32-unknown-unknown`)
47//!
48//! Build djs-rs with `default-features = false, features = ["http-interactions"]` and give
49//! the client a [`Rest`] with a [`Transport`](djs_rest::Transport) over `fetch` (the
50//! repository's `examples/cloudflare-workers` is a complete bot). Handlers must be `Send`,
51//! so a JS future awaited in one (a `fetch`, `worker::Delay`) is wrapped in
52//! `worker::send::SendFuture`. tokio's timers do not run there: collectors and the gateway
53//! requests are not available, and a handler waits with the platform's timers instead.
54//!
55//! discord.js counterpart: none (discord.js only receives interactions over the gateway);
56//! the official `discord-interactions` package has the verification (`verifyKey`).
57//!
58//! # Examples
59//!
60//! ```no_run
61//! use djs_rs::prelude::*;
62//!
63//! # async fn run(signature: &str, timestamp: &str, body: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
64//! let client = Client::builder(std::env::var("DISCORD_TOKEN")?).build();
65//! client.command("ping", |ctx, cmd| async move {
66//!     cmd.reply(&ctx, "Pong!").await?;
67//!     Ok(())
68//! });
69//! let endpoint = client.interactions_endpoint(&std::env::var("DISCORD_PUBLIC_KEY")?)?;
70//!
71//! // In the HTTP server's `POST` handler, with the request's headers and body:
72//! let (response, background) = endpoint.handle(signature, timestamp, body).await;
73//! tokio::spawn(background);
74//! // … answer with `response.status` and `response.body`.
75//! # let _ = response;
76//! # Ok(())
77//! # }
78//! ```
79
80use core::{
81    fmt,
82    future::Future,
83    pin::Pin,
84    task::{Context, Poll, Waker},
85};
86use std::{
87    sync::{Arc, Mutex, PoisonError},
88    task::Wake,
89};
90
91use djs_cache::{Backend, DashMapBackend};
92use djs_model::{
93    gateway::payload::InteractionCreate,
94    id::InteractionId,
95    interaction::{InteractionData, InteractionResponse},
96    util::Timestamp,
97};
98use djs_rest::{Error, Rest};
99use ed25519_dalek::{Signature, VerifyingKey};
100use tokio::sync::oneshot;
101
102use crate::Client;
103
104/// How far `X-Signature-Timestamp` may be from now, in seconds (D-401).
105const MAX_AGE_SECS: u64 = 5 * 60;
106
107/// The body of a `PONG`.
108const PONG: &[u8] = br#"{"type":1}"#;
109
110/// The future of a request's remaining work.
111type Background = Pin<Box<dyn Future<Output = ()> + Send>>;
112
113/// What the handlers did with the initial response (D-399).
114pub(crate) enum Initial {
115    /// Its JSON, for the HTTP body.
116    Body(Vec<u8>),
117    /// It had files, so it went through REST.
118    Rest,
119}
120
121/// Sends the initial response of an HTTP interaction to its endpoint.
122pub(crate) type InitialSender = oneshot::Sender<Initial>;
123
124/// Receives the initial response of an HTTP interaction.
125pub(crate) type InitialReceiver = oneshot::Receiver<Initial>;
126
127/// The slot of an HTTP interaction's initial response, in its [`Context`](crate::Context):
128/// the first response of that interaction takes it.
129pub(crate) struct Inline {
130    interaction: InteractionId,
131    slot: Mutex<Option<InitialSender>>,
132}
133
134impl Inline {
135    /// A slot for `interaction`, and the receiver of what goes in it.
136    pub(crate) fn new(interaction: InteractionId) -> (Self, InitialReceiver) {
137        let (sender, receiver) = oneshot::channel();
138        let inline = Self {
139            interaction,
140            slot: Mutex::new(Some(sender)),
141        };
142        (inline, receiver)
143    }
144
145    /// Takes the slot if `interaction` is this one's and it is still empty.
146    pub(crate) fn take(&self, interaction: InteractionId) -> Option<InitialSender> {
147        if interaction != self.interaction {
148            return None;
149        }
150        self.slot
151            .lock()
152            .unwrap_or_else(PoisonError::into_inner)
153            .take()
154    }
155}
156
157/// Gives `response`, an HTTP interaction's initial response, to its endpoint: as JSON for
158/// the HTTP body, or, if it has files, through REST first (C-139).
159pub(crate) async fn respond(
160    rest: &Rest,
161    initial: InitialSender,
162    interaction: InteractionId,
163    token: &str,
164    response: &InteractionResponse,
165) -> Result<(), Error> {
166    if response.files().is_empty()
167        && let Ok(body) = serde_json::to_vec(response)
168    {
169        // A closed receiver means the request is gone; there is no one left to answer.
170        let _ = initial.send(Initial::Body(body));
171        return Ok(());
172    }
173    rest.create_interaction_response(interaction, token, response)
174        .await?;
175    let _ = initial.send(Initial::Rest);
176    Ok(())
177}
178
179/// The response to an HTTP interaction request, returned by
180/// [`InteractionsEndpoint::handle`]: send `status` and `body`, with `Content-Type:
181/// application/json` when `body` is not empty.
182///
183/// discord.js counterpart: none.
184#[derive(Clone, Debug, PartialEq, Eq)]
185#[non_exhaustive]
186pub struct HttpResponse {
187    /// The HTTP status code: `200`, `202`, `400`, `401` or `500` (see [the
188    /// module](self)).
189    pub status: u16,
190    /// The body: an interaction response's JSON, or empty.
191    pub body: Vec<u8>,
192}
193
194impl HttpResponse {
195    const fn empty(status: u16) -> Self {
196        Self {
197            status,
198            body: Vec::new(),
199        }
200    }
201}
202
203/// The error of [`Client::interactions_endpoint`](crate::Client::interactions_endpoint):
204/// the public key is not 64 hexadecimal digits of a valid Ed25519 key.
205///
206/// discord.js counterpart: none.
207#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
208#[error("the public key is not 64 hexadecimal digits of a valid Ed25519 key")]
209pub struct InvalidPublicKey;
210
211/// Answers the interactions Discord posts to the app's Interactions Endpoint URL with a
212/// [`Client`]'s routes and handlers; made by
213/// [`Client::interactions_endpoint`](crate::Client::interactions_endpoint). Cheap to clone.
214///
215/// See [the module](self) for what [`handle`](Self::handle) does.
216///
217/// discord.js counterpart: none.
218pub struct InteractionsEndpoint<B: Backend = DashMapBackend> {
219    client: Client<B>,
220    key: VerifyingKey,
221}
222
223impl<B: Backend> Clone for InteractionsEndpoint<B> {
224    fn clone(&self) -> Self {
225        Self {
226            client: self.client.clone(),
227            key: self.key,
228        }
229    }
230}
231
232impl<B: Backend> fmt::Debug for InteractionsEndpoint<B> {
233    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234        f.debug_struct("InteractionsEndpoint")
235            .field("client", &self.client)
236            .finish_non_exhaustive()
237    }
238}
239
240impl<B: Backend> InteractionsEndpoint<B> {
241    pub(crate) fn new(client: Client<B>, public_key: &str) -> Result<Self, InvalidPublicKey> {
242        let bytes = decode_hex::<32>(public_key).ok_or(InvalidPublicKey)?;
243        let key = VerifyingKey::from_bytes(&bytes).map_err(|_| InvalidPublicKey)?;
244        Ok(Self { client, key })
245    }
246
247    /// Handles one request to the Interactions Endpoint URL: `signature` and `timestamp` are
248    /// its `X-Signature-Ed25519` and `X-Signature-Timestamp` headers (pass `""` for a missing
249    /// one), `body` its raw body. Returns the response to send and the future of the
250    /// handlers' remaining work, which must be run (`tokio::spawn`, or `ctx.wait_until` on
251    /// Cloudflare Workers) for follow-ups to happen.
252    ///
253    /// Returns as soon as a handler gives the initial response: Discord waits at most 3
254    /// seconds for it. See [the module](self) for every status.
255    ///
256    /// discord.js counterpart: none; `verifyKey` of the `discord-interactions` package for
257    /// the verification.
258    pub async fn handle(
259        &self,
260        signature: &str,
261        timestamp: &str,
262        body: &[u8],
263    ) -> (
264        HttpResponse,
265        impl Future<Output = ()> + Send + 'static + use<B>,
266    ) {
267        let idle = || -> Background { Box::pin(core::future::ready(())) };
268        if !verify(
269            &self.key,
270            signature,
271            timestamp,
272            body,
273            Timestamp::now().as_unix_secs(),
274        ) {
275            return (HttpResponse::empty(401), idle());
276        }
277        let event: InteractionCreate = match serde_json::from_slice(body) {
278            Ok(event) => event,
279            Err(error) => {
280                tracing::warn!(%error, "a signed HTTP interaction could not be decoded");
281                return (HttpResponse::empty(400), idle());
282            }
283        };
284        if matches!(event.data, InteractionData::Ping) {
285            let pong = HttpResponse {
286                status: 200,
287                body: PONG.to_vec(),
288            };
289            return (pong, idle());
290        }
291        let (mut initial, work) = self.client.dispatch_http(event);
292        let mut work = Relayed::new(work);
293        tokio::select! {
294            biased;
295            result = &mut initial => (answer(result.ok()), Box::pin(work)),
296            () = &mut work => (answer(initial.try_recv().ok()), idle()),
297        }
298    }
299}
300
301/// The handlers' future, polled first by [`InteractionsEndpoint::handle`] and then by the
302/// task the integration runs it in (`ctx.wait_until`, `tokio::spawn`): inside, it always
303/// sees the same waker, which wakes the task that polled last. A future that keeps the first
304/// waker it was given (Cloudflare's `worker::Delay` does) would otherwise wake `handle`'s
305/// finished task, and the background work would never resume (C-142).
306struct Relayed {
307    future: Background,
308    relay: Arc<Relay>,
309    waker: Waker,
310}
311
312/// The waker of the task that polled a [`Relayed`] last.
313struct Relay(Mutex<Option<Waker>>);
314
315impl Wake for Relay {
316    fn wake(self: Arc<Self>) {
317        self.wake_by_ref();
318    }
319
320    fn wake_by_ref(self: &Arc<Self>) {
321        if let Some(waker) = &*self.0.lock().unwrap_or_else(PoisonError::into_inner) {
322            waker.wake_by_ref();
323        }
324    }
325}
326
327impl Relayed {
328    fn new(future: Background) -> Self {
329        let relay = Arc::new(Relay(Mutex::new(None)));
330        let waker = Waker::from(Arc::clone(&relay));
331        Self {
332            future,
333            relay,
334            waker,
335        }
336    }
337}
338
339impl Future for Relayed {
340    type Output = ();
341
342    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
343        let this = self.get_mut();
344        {
345            let mut last = this.relay.0.lock().unwrap_or_else(PoisonError::into_inner);
346            if !last
347                .as_ref()
348                .is_some_and(|waker| waker.will_wake(cx.waker()))
349            {
350                *last = Some(cx.waker().clone());
351            }
352        }
353        this.future
354            .as_mut()
355            .poll(&mut Context::from_waker(&this.waker))
356    }
357}
358
359/// The HTTP response for what the handlers did with the initial response.
360fn answer(initial: Option<Initial>) -> HttpResponse {
361    match initial {
362        Some(Initial::Body(body)) => HttpResponse { status: 200, body },
363        Some(Initial::Rest) => HttpResponse::empty(202),
364        None => {
365            tracing::warn!("the handlers of an HTTP interaction finished without responding");
366            HttpResponse::empty(500)
367        }
368    }
369}
370
371/// Whether `signature` (hexadecimal) signs `timestamp` followed by `body` under `key`, and
372/// `timestamp` (Unix seconds) is at most [`MAX_AGE_SECS`] from `now`.
373fn verify(key: &VerifyingKey, signature: &str, timestamp: &str, body: &[u8], now: i64) -> bool {
374    let Ok(signed_at) = timestamp.parse::<i64>() else {
375        return false;
376    };
377    if now.abs_diff(signed_at) > MAX_AGE_SECS {
378        return false;
379    }
380    let Some(signature) = decode_hex::<64>(signature) else {
381        return false;
382    };
383    let mut message = Vec::with_capacity(timestamp.len() + body.len());
384    message.extend_from_slice(timestamp.as_bytes());
385    message.extend_from_slice(body);
386    key.verify_strict(&message, &Signature::from_bytes(&signature))
387        .is_ok()
388}
389
390/// Decodes exactly `N` bytes of hexadecimal (either case).
391fn decode_hex<const N: usize>(hex: &str) -> Option<[u8; N]> {
392    const fn digit(c: u8) -> Option<u8> {
393        match c {
394            b'0'..=b'9' => Some(c - b'0'),
395            b'a'..=b'f' => Some(c - b'a' + 10),
396            b'A'..=b'F' => Some(c - b'A' + 10),
397            _ => None,
398        }
399    }
400    let hex = hex.as_bytes();
401    if hex.len() != 2 * N {
402        return None;
403    }
404    let mut out = [0; N];
405    for (byte, pair) in out.iter_mut().zip(hex.as_chunks::<2>().0) {
406        *byte = (digit(pair[0])? << 4) | digit(pair[1])?;
407    }
408    Some(out)
409}
410
411#[cfg(test)]
412mod tests {
413    use core::fmt::Write as _;
414
415    use ed25519_dalek::{Signer, SigningKey};
416
417    use super::*;
418
419    const NOW: i64 = 1_800_000_000;
420
421    fn hex(bytes: &[u8]) -> String {
422        bytes.iter().fold(String::new(), |mut hex, byte| {
423            let _ = write!(hex, "{byte:02x}");
424            hex
425        })
426    }
427
428    fn key() -> SigningKey {
429        SigningKey::from_bytes(&[7; 32])
430    }
431
432    fn sign(timestamp: &str, body: &[u8]) -> String {
433        let mut message = timestamp.as_bytes().to_vec();
434        message.extend_from_slice(body);
435        hex(&key().sign(&message).to_bytes())
436    }
437
438    #[test]
439    fn decodes_hex_of_the_exact_length_only() {
440        assert_eq!(decode_hex::<2>("0aFf"), Some([0x0a, 0xff]));
441        assert_eq!(decode_hex::<2>("0aF"), None);
442        assert_eq!(decode_hex::<2>("0aFf0"), None);
443        assert_eq!(decode_hex::<2>("0aFg"), None);
444        assert_eq!(decode_hex::<1>("é"), None);
445    }
446
447    #[test]
448    fn verifies_the_signature_of_the_timestamp_and_body() {
449        let public = key().verifying_key();
450        let (timestamp, body) = ("1800000000", br#"{"type":1}"#.as_slice());
451        let signature = sign(timestamp, body);
452        assert!(verify(&public, &signature, timestamp, body, NOW));
453        assert!(verify(
454            &public,
455            &signature.to_uppercase(),
456            timestamp,
457            body,
458            NOW
459        ));
460        // Another body, timestamp or key; a malformed signature.
461        assert!(!verify(
462            &public,
463            &signature,
464            timestamp,
465            br#"{"type":2}"#,
466            NOW
467        ));
468        assert!(!verify(&public, &signature, "1800000001", body, NOW));
469        let other = SigningKey::from_bytes(&[8; 32]).verifying_key();
470        assert!(!verify(&other, &signature, timestamp, body, NOW));
471        assert!(!verify(&public, &signature[2..], timestamp, body, NOW));
472        assert!(!verify(&public, "", timestamp, body, NOW));
473    }
474
475    #[test]
476    fn rejects_timestamps_more_than_five_minutes_away() {
477        let public = key().verifying_key();
478        let body = b"{}";
479        for (offset, valid) in [
480            (0, true),
481            (300, true),
482            (-300, true),
483            (301, false),
484            (-301, false),
485        ] {
486            let timestamp = (NOW + offset).to_string();
487            let signature = sign(&timestamp, body);
488            assert_eq!(
489                verify(&public, &signature, &timestamp, body, NOW),
490                valid,
491                "{offset}"
492            );
493        }
494        let signature = sign("soon", body);
495        assert!(!verify(&public, &signature, "soon", body, NOW));
496    }
497
498    /// A future like `worker::Delay`: it keeps the first waker it is polled with.
499    #[derive(Clone, Default)]
500    struct FirstWaker(Arc<Mutex<(bool, Option<Waker>)>>);
501
502    impl FirstWaker {
503        fn complete(&self) {
504            let mut state = self.0.lock().unwrap();
505            state.0 = true;
506            if let Some(waker) = state.1.take() {
507                waker.wake();
508            }
509        }
510    }
511
512    impl Future for FirstWaker {
513        type Output = ();
514
515        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
516            let mut state = self.0.lock().unwrap();
517            if state.0 {
518                return Poll::Ready(());
519            }
520            state.1.get_or_insert_with(|| cx.waker().clone());
521            Poll::Pending
522        }
523    }
524
525    #[tokio::test]
526    async fn background_work_resumes_in_the_task_it_moves_to() {
527        let leaf = FirstWaker::default();
528        let inner = leaf.clone();
529        let mut work = Relayed::new(Box::pin(inner));
530        // `handle` polls it first, with its own waker…
531        let first = Waker::noop();
532        assert!(
533            Pin::new(&mut work)
534                .poll(&mut Context::from_waker(first))
535                .is_pending()
536        );
537        // … then the integration runs it in another task.
538        let task = tokio::spawn(work);
539        tokio::task::yield_now().await;
540        leaf.complete();
541        tokio::time::timeout(core::time::Duration::from_secs(5), task)
542            .await
543            .expect("the moved task was woken")
544            .unwrap();
545    }
546
547    #[test]
548    fn the_endpoint_needs_a_valid_public_key() {
549        let client = Client::builder("token").build();
550        let hex = hex(&key().verifying_key().to_bytes());
551        assert!(client.interactions_endpoint(&hex).is_ok());
552        assert_eq!(
553            client.interactions_endpoint(&hex[1..]).unwrap_err(),
554            InvalidPublicKey
555        );
556        assert_eq!(
557            client.interactions_endpoint("zz").unwrap_err(),
558            InvalidPublicKey
559        );
560    }
561}