summary refs log tree commit diff
path: root/src/api/util/handlers/Webhook.ts
blob: 1f4f60a738960c819f1f44ff48ac588ab0adf7a8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
/*
	Spacebar: A FOSS re-implementation and extension of the Discord.com backend.
	Copyright (C) 2026 Spacebar and Spacebar Contributors

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published
	by the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/

import { Request, Response } from "express";
import { HTTPError } from "lambert-server/HTTPError";
import { MoreThan } from "typeorm";
import { handleMessage, postHandleMessage } from "./Message";
import { Attachment, Channel, Message, Webhook } from "@spacebar/database";
import { Config, DiscordApiErrors, emitEvent, FieldErrors, MessageCreateEvent, Snowflake, uploadFile, ValidateName } from "@spacebar/util";
import { WebhookExecuteSchema } from "@spacebar/schemas";

export const executeWebhook = async (req: Request, res: Response) => {
    const body = req.body as WebhookExecuteSchema;
    const messageId = Snowflake.generate();

    const { webhook_id, token } = req.params as { [key: string]: string };

    const webhook = await Webhook.findOne({
        where: {
            id: webhook_id,
        },
        relations: { channel: true, guild: true, application: true },
    });

    if (!webhook) {
        throw DiscordApiErrors.UNKNOWN_WEBHOOK;
    }

    if (webhook.token !== token) {
        throw DiscordApiErrors.INVALID_WEBHOOK_TOKEN_PROVIDED;
    }

    if (body.username) {
        ValidateName(body.username);
    }

    // ensure one of content, embeds, components, or file is present
    if (!body.content && !body.embeds && !body.components && !body.file && !body.attachments) {
        throw DiscordApiErrors.CANNOT_SEND_EMPTY_MESSAGE;
    }

    const wait = req.query.wait === "true";
    const thread_id = typeof req.query.thread_id === "string" ? req.query.thread_id : undefined;

    if (!wait) {
        res.status(204).send();
    }

    const attachments: Attachment[] = [];

    if (!webhook.channel.isWritable()) {
        if (wait) {
            throw new HTTPError(`Cannot send messages to channel of type ${webhook.channel.type}`, 400);
        } else {
            return;
        }
    }

    // TODO: creating messages by users checks if the user can bypass rate limits, we cant do that on webhooks, but maybe we could check the application if there is one?
    const limits = Config.get().limits;
    if (limits.absoluteRate.sendMessage.enabled) {
        const count = await Message.count({
            where: {
                channel_id: webhook.channel_id,
                timestamp: MoreThan(new Date(Date.now() - limits.absoluteRate.sendMessage.window)),
            },
        });

        if (count >= limits.absoluteRate.sendMessage.limit)
            if (wait) {
                throw FieldErrors({
                    channel_id: {
                        code: "TOO_MANY_MESSAGES",
                        message: req.t("common:toomany.MESSAGE"),
                    },
                });
            } else {
                return;
            }
    }

    let sendChannel = webhook.channel;
    if (thread_id) {
        sendChannel = await Channel.findOneOrFail({
            where: {
                id: thread_id,
                parent_id: webhook.channel.id,
            },
        });
    }

    const files = (req.files as Express.Multer.File[]) ?? [];
    for (const currFile of files) {
        try {
            const file = await uploadFile(`/attachments/${sendChannel.id}/${messageId}`, currFile);
            attachments.push(Attachment.create(file));
        } catch (error) {
            if (wait) res.status(400).json({ message: error?.toString() });
            console.error("[webhookExecute] Failed to handle attachment:", error);
            return;
        }
    }

    const embeds = body.embeds || [];
    const bodyMsg = {
        ...body,
        allowed_mentions: body.allowed_mentions
            ? {
                  ...body.allowed_mentions,
                  parse: body.allowed_mentions.parse as ("users" | "roles" | "everyone")[],
              }
            : undefined,
    } as Parameters<typeof handleMessage>[0];
    const message = await handleMessage({
        id: messageId,
        ...bodyMsg,
        username: body.username || webhook.name,
        avatar_url: body.avatar_url || webhook.avatar,
        type: 0,
        pinned: false,
        webhook_id: webhook.id,
        application_id: webhook.application?.id,
        embeds,
        // TODO: Support thread_id/thread_name once threads are implemented
        channel_id: sendChannel.id,
        attachments,
        timestamp: new Date(),
    });

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-ignore dont care2
    message.edited_timestamp = null;

    sendChannel.last_message_id = message.id;

    await Promise.all([
        message.save(),
        sendChannel.save(),
        emitEvent({
            event: "MESSAGE_CREATE",
            channel_id: sendChannel.id,
            data: message.toJSON(),
        } satisfies MessageCreateEvent),
    ]);

    // no await as it shouldnt block the message send function and silently catch error
    postHandleMessage(message).catch((e) => console.error("[Message] post-message handler failed", e));
    if (wait) res.json(message);
    return;
};