# HTTP interactions

> Get your bot’s interactions as signed HTTP requests instead of gateway events, for bots that run on serverless platforms. The endpoint URL, verifying the Ed25519 signature, the check Klang runs when you save the URL, and a minimal Cloudflare Worker.

## When to use it

A bot that only answers commands doesn’t need a gateway connection open all day. With an
**interactions endpoint URL**, Klang sends each interaction to your URL as a `POST`, and your
server answers in the body of its response. It suits serverless platforms, such as Cloudflare
Workers or AWS Lambda, that wake up for a request and go back to sleep.

It’s one or the other, per app: while the app has a URL, its interactions go only there, and
`INTERACTION_CREATE` doesn’t arrive on the gateway. The rest of the gateway works as usual, so a
bot can keep a connection for messages and other events and still take its interactions by HTTP.
Registering commands is the same either way: see [Slash commands](https://docs.klang.gg/bots/commands/).

## Set the URL

1. Open your app in the developer portal and go to **General**.
2. Copy the **Public key**. It’s 64 hexadecimal characters, and your server needs it to check
   that requests come from Klang. It isn’t a secret. Klang makes your app’s key pair the first
   time it’s needed, and it doesn’t change.
3. Deploy your server with that key (the example below reads it from `KLANG_PUBLIC_KEY`).
4. Paste its address in **Interactions endpoint URL** and select **Save URL**. The button says
   **Checking…** while Klang runs [the check](https://docs.klang.gg/bots/http-interactions/#the-check-when-you-save), and the URL is saved
   only if it passes.

To go back to the gateway, select **Stop using it** next to the button (or empty the field and
save).

Your bot can also set it itself with
[`PATCH /applications/@me`](https://docs.klang.gg/bots/reference/users/#set-the-interactions-url), with the same
check. Your bot reads the public key in the `verify_key` field of
[its app](https://docs.klang.gg/bots/reference/objects/#application).

### Which URLs work

- **`https` only**, with no username or password in it, on the default port (leave the port out).
- A real domain name, or a public IP address. A name with no dot, such as `localhost`, doesn’t
  work.
- Up to 512 characters.
- **On the internet.** Every address the name points to has to be public: Klang doesn’t send
  requests to private networks (such as `10.x.x.x` or `192.168.x.x`), to the machine itself, to
  link-local addresses or to a cloud’s metadata service. It checks where the name points each time
  it sends a request, not only when you save, and connects to the address it checked.
- **No redirects.** Klang doesn’t follow them: an answer with a `3xx` status counts as a wrong
  answer. Give the final address.

To try a server on your own computer, put a tunnel in front of it and use the tunnel’s public
`https` address.

## The check when you save

Before it keeps a URL, Klang sends it two requests, both of type `1` (`PING`):

1. one correctly signed, which has to answer `200` with `{"type": 1}` (`PONG`);
2. one with a wrong signature, which has to answer `401`.

The URL is saved only if both answers are right. The second request is there to make sure your
server really checks signatures: one that answers everything would let anyone send it fake
commands.

Each of the two requests has **5 seconds** to get an answer, a bit more than an interaction gets,
in case your server has to wake up first. An app can run the check **10 times every 10 minutes**
(the `interactions-url-check` bucket, shared by the portal and `PATCH /applications/@me`). A URL
that breaks the rules above is turned down before any request goes out, and doesn’t spend a
check.

When the check fails, the portal says under the field which part failed:

| What failed             | What to look at                                                                                    |
| ----------------------- | -------------------------------------------------------------------------------------------------- |
| The URL itself          | It has to be `https`, without a username or password, on the default port.                         |
| A private address       | The name points to an address that isn’t on the internet.                                          |
| Klang couldn’t reach it | The name doesn’t resolve, or the connection failed. Check the address and that your server is up.  |
| It took too long        | No answer within 5 seconds.                                                                        |
| The signed `PING`       | It didn’t get `200` with `{"type": 1}`. The portal shows the status your server answered.          |
| The badly signed `PING` | It didn’t get `401`: your server accepts requests it should refuse. The portal shows what it gave. |

From `PATCH /applications/@me`, a URL that fails is a `400` with code `50035`, with the error on
the `interactions_endpoint_url` field and a message that says which part failed.

A `PING` looks like this:

```json
{
  "id": "1575120625984638976",
  "application_id": "1575120256797806592",
  "type": 1,
  "token": "7EKiMFtwZV8xtN7yy9M7M8YOuum5cUbgCgV79Iz8tCwW_P8XGEVCU6B7rAZ5SpOJqS0p9THuy3ugQZZSsu6eGnDCDQT3LuR1",
  "version": 1
}
```

Its `token` opens nothing: there’s no person and no channel behind a `PING`, so there’s nothing
to answer except the `PONG`.

## Verify every request

Every request Klang sends to your URL is a `POST` with these headers:

| Header                  | What it holds                                                |
| ----------------------- | ------------------------------------------------------------ |
| `X-Signature-Ed25519`   | The signature, as 128 hexadecimal characters.                |
| `X-Signature-Timestamp` | When Klang signed it, in Unix seconds, as text.              |
| `Content-Type`          | `application/json`.                                          |
| `User-Agent`            | `Klang-Interactions/1.0 (+https://klang.gg)`, for your logs. |

The signature is Ed25519, made with your app’s private key over the timestamp followed by the
body, exactly as sent. To check it:

1. read the body as **raw text**, before parsing it: parsing and serializing the JSON again
   changes the bytes;
2. verify the signature over `timestamp + body` with the public key;
3. if it doesn’t match, or a header is missing, answer `401` and stop.

Only Klang has the private key, so a request that passes came from Klang and wasn’t changed on
the way. It’s also wise to refuse a timestamp that’s more than a few minutes old.

## Answer in the response

After the check, the body is the same [interaction](https://docs.klang.gg/bots/reference/objects/#interaction) a
gateway bot gets. Answer it **in your HTTP response**, with any `2xx` status and a callback as
the body, the same object a gateway bot sends to the callback route:

```json
{ "type": 4, "data": { "content": "North Pier: high tide at 06:42." } }
```

The types are the same: `4` for a message, `5` to defer, `6` and `7` for the message of a
component, `8` for autocomplete suggestions, `9` for a modal, and `1` only for a `PING`. See
[Responding to interactions](https://docs.klang.gg/bots/interactions/), [Buttons, menus and layouts](https://docs.klang.gg/bots/components/)
and [Modals](https://docs.klang.gg/bots/modals/). Button presses and submitted modals reach this URL too. Klang reads the body
as JSON whatever its `Content-Type`, but sending `application/json` is good manners.

You have **3 seconds**, counted from the moment the person used the command, not from when your
server got the request. The answer can be up to **256 KiB**.

**Answering through the callback route instead.** If your response is a `2xx` with an empty body
(a `202`, say), Klang takes it as “I’ll answer separately” and waits for your bot to call
[`POST /interactions/{interaction.id}/{interaction.token}/callback`](https://docs.klang.gg/bots/reference/interactions/#answer-an-interaction),
which works for interactions delivered by HTTP too. The same 3 seconds apply: if no callback comes
in time, the person sees that the application didn’t respond. Only the first answer counts, by
either way.

The person sees **The application didn’t respond.** when your server:

- answers with a status that isn’t `2xx`, a redirect included;
- answers with a body that isn’t JSON, or isn’t a callback this interaction takes;
- answers with more than 256 KiB;
- can’t be reached, or doesn’t answer within the 3 seconds.

Klang sends each interaction **once** and doesn’t retry. It also doesn’t keep more than 50 of an
app’s interactions waiting on its URL at once: past that, the next ones fail straight away.

Everything after the first answer works as for gateway bots: the interaction’s `token` edits
`@original` and sends follow-ups through
[the webhook routes](https://docs.klang.gg/bots/reference/interactions/#messages-with-the-interactions-token), for 15
minutes.

## A minimal Cloudflare Worker

This Worker answers `/tide` with a message. It reads your public key from the
`KLANG_PUBLIC_KEY` variable.

**With `discord-interactions`**, an MIT-licensed package from npm that verifies the signature
for you (version 4, where `verifyKey` is asynchronous):

```js
import { InteractionResponseType, InteractionType, verifyKey } from 'discord-interactions';

export default {
  async fetch(request, env) {
    if (request.method !== 'POST') return new Response('Not found', { status: 404 });

    const signature = request.headers.get('X-Signature-Ed25519');
    const timestamp = request.headers.get('X-Signature-Timestamp');
    const body = await request.text();
    const valid =
      signature !== null &&
      timestamp !== null &&
      (await verifyKey(body, signature, timestamp, env.KLANG_PUBLIC_KEY));
    if (!valid) return new Response('Bad signature', { status: 401 });

    const interaction = JSON.parse(body);
    if (interaction.type === InteractionType.PING) {
      return Response.json({ type: InteractionResponseType.PONG });
    }
    if (
      interaction.type === InteractionType.APPLICATION_COMMAND &&
      interaction.data.name === 'tide'
    ) {
      const harbor = interaction.data.options?.find((option) => option.name === 'harbor')?.value;
      return Response.json({
        type: InteractionResponseType.CHANNEL_MESSAGE_WITH_SOURCE,
        data: { content: `${harbor}: high tide at 06:42.` },
      });
    }
    return new Response('Unknown interaction', { status: 400 });
  },
};
```

**With no package**, using the Ed25519 support built into Workers’ Web Crypto (Node.js 22 has it
too):

```js
function fromHex(hex) {
  if (!/^(?:[0-9a-f]{2})+$/i.test(hex)) return null;
  return Uint8Array.from(hex.match(/../g), (byte) => parseInt(byte, 16));
}

async function isSigned(request, body, publicKey) {
  const signature = fromHex(request.headers.get('X-Signature-Ed25519') ?? '');
  const timestamp = request.headers.get('X-Signature-Timestamp');
  const key = fromHex(publicKey);
  if (signature === null || timestamp === null || key === null) return false;
  try {
    const verifier = await crypto.subtle.importKey('raw', key, 'Ed25519', false, ['verify']);
    return await crypto.subtle.verify(
      'Ed25519',
      verifier,
      signature,
      new TextEncoder().encode(timestamp + body),
    );
  } catch {
    return false;
  }
}

export default {
  async fetch(request, env) {
    if (request.method !== 'POST') return new Response('Not found', { status: 404 });
    const body = await request.text();
    if (!(await isSigned(request, body, env.KLANG_PUBLIC_KEY))) {
      return new Response('Bad signature', { status: 401 });
    }

    const interaction = JSON.parse(body);
    if (interaction.type === 1) return Response.json({ type: 1 });
    if (interaction.type === 2 && interaction.data.name === 'tide') {
      const harbor = interaction.data.options?.find((option) => option.name === 'harbor')?.value;
      return Response.json({ type: 4, data: { content: `${harbor}: high tide at 06:42.` } });
    }
    return new Response('Unknown interaction', { status: 400 });
  },
};
```

Deploy it with `wrangler deploy`, set the variable with `wrangler secret put KLANG_PUBLIC_KEY`
(or as a plain variable: the key is public), and paste the Worker’s address in the portal. The
check runs when you save, so you know right away if the signature code works.

Register the commands from somewhere else, such as a script you run when they change: a Worker
only wakes up for requests, so it has no “ready” moment to register them in.
