From 7c7060b1c7745619916240a42db2d2cddac4ab1f Mon Sep 17 00:00:00 2001 From: Musiker15 Date: Thu, 5 Nov 2026 18:21:12 +0100 Subject: [PATCH 1/3] feat: upload panel logo and banner in the dashboard, sanitised with sharp and scanned by ClamAV --- .env.example | 15 + CHANGELOG.md | 20 + assets/README.md | 7 +- docs/configuration-de.md | 4 + docs/configuration-en.md | 4 + docs/dashboard-de.md | 62 ++- docs/dashboard-en.md | 61 ++- package-lock.json | 632 +++++++++++++++++++++++++- package.json | 3 +- src/dashboard/clamav.js | 153 +++++++ src/dashboard/imageSanitizer.js | 256 +++++++++++ src/dashboard/jsoncPatch.js | 127 ++++++ src/dashboard/panelAssets.js | 381 ++++++++++++++++ src/dashboard/routes.js | 13 + src/utils/assetResolver.js | 35 ++ src/utils/panel.js | 29 +- tests/panel-asset-upload.test.js | 570 +++++++++++++++++++++++ web/dist/assets/index-C2LfAsks.css | 1 + web/dist/assets/index-COamnHj3.css | 1 - web/dist/assets/index-CuzH3aKN.js | 70 +++ web/dist/assets/index-chtVO3J7.js | 70 --- web/dist/index.html | 4 +- web/src/api.js | 40 +- web/src/botconfig/ConfigForm.jsx | 4 +- web/src/botconfig/FormRenderer.jsx | 11 +- web/src/botconfig/PanelAssetField.jsx | 146 ++++++ web/src/botconfig/schema.js | 23 +- web/src/locales/de.json | 16 +- web/src/locales/en.json | 16 +- web/src/locales/es.json | 16 +- web/src/locales/fr.json | 16 +- web/src/locales/hu.json | 16 +- web/src/locales/pl.json | 16 +- web/src/locales/pt.json | 16 +- web/src/views/Config.jsx | 13 +- 35 files changed, 2729 insertions(+), 138 deletions(-) create mode 100644 src/dashboard/clamav.js create mode 100644 src/dashboard/imageSanitizer.js create mode 100644 src/dashboard/jsoncPatch.js create mode 100644 src/dashboard/panelAssets.js create mode 100644 src/utils/assetResolver.js create mode 100644 tests/panel-asset-upload.test.js create mode 100644 web/dist/assets/index-C2LfAsks.css delete mode 100644 web/dist/assets/index-COamnHj3.css create mode 100644 web/dist/assets/index-CuzH3aKN.js delete mode 100644 web/dist/assets/index-chtVO3J7.js create mode 100644 web/src/botconfig/PanelAssetField.jsx diff --git a/.env.example b/.env.example index 42c8ced..06d286d 100644 --- a/.env.example +++ b/.env.example @@ -84,3 +84,18 @@ DASHBOARD_PUBLIC_PORTAL="false" # Only meaningful with a loopback bind (DASHBOARD_HOST=127.0.0.1); the secret is # the only thing standing between the port and full owner access. # DASHBOARD_TRUST_PROXY_SECRET="" + +# ── Panel image uploads (dashboard) ─────────────────────────────────────────── +# Logo and banner can be uploaded in the dashboard (Configuration → Ticket Panel). +# Every image is re-encoded (metadata removed, SVG converted to PNG). +# +# Size limit per upload in MB. Default 5, allowed 1 to 10. +# ASSET_UPLOAD_MAX_MB="5" +# +# Optional virus scan with ClamAV (clamd). Set the local socket, OR host + port. +# When set, an upload is refused if clamd does not answer (fail closed). When +# neither is set, uploads are not virus scanned (logged once at start). +# Debian/Ubuntu: CLAMAV_SOCKET="/var/run/clamav/clamd.ctl" +# CLAMAV_SOCKET="" +# CLAMAV_HOST="127.0.0.1" +# CLAMAV_PORT="3310" diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f166ce..d58b025 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **`npm run update`** runs the same update routine as the dashboard's Update button, without the dashboard, for self-hosters and for updating many installations in a loop. It does not restart the bot. +- **Upload the panel logo and banner in the dashboard.** Configuration, section + *Ticket Panel*, has an upload, a preview and **Reset to default** for each + image, so a hosted bot can change them without access to the server's files + (`POST`/`DELETE /api/panel-assets/:slot`, permission `config.edit`, audited + as `panel.asset.upload` and `panel.asset.reset`). PNG, JPEG, GIF, WebP and + SVG are accepted, the type is read from the content. Every image is decoded + and encoded again with sharp, which removes metadata (EXIF, GPS, XMP, ICC) + and anything appended to the file, scales the logo to at most 1024 px and + the banner to at most 2048 px, and turns SVG into PNG. Images over 30 + megapixels are refused before decoding. The file is stored in `assets/` + under a generated name and `panel..file` in `config.jsonc` is set to + it, comments kept; it takes effect after a restart of the bot. +- **New `.env` keys for uploads.** `ASSET_UPLOAD_MAX_MB` (default 5, 1 to 10) + limits the upload size. `CLAMAV_SOCKET`, or `CLAMAV_HOST` and `CLAMAV_PORT`, + turn on a virus scan with clamd before an image is processed; a flagged file + is refused and audited as `panel.asset.infected`, and an unreachable scanner + refuses the upload. Without them uploads are not virus scanned, which the + dashboard logs once at start. +- New production dependency **sharp** for the image conversion. It installs + from prebuilt binaries on Linux, Windows and macOS, no build tools needed. ### Changed diff --git a/assets/README.md b/assets/README.md index b90aece..fad5756 100644 --- a/assets/README.md +++ b/assets/README.md @@ -1,7 +1,7 @@ # Panel images Put your own panel images here, for example `logo.png` or `banner.png`. -Supported formats: PNG, JPG, GIF, WEBP +Supported formats: PNG, JPG, GIF, WEBP (the dashboard upload also takes SVG and converts it to PNG) The bot looks for the file named in the config in this folder first and then in `default/`, which holds the MSK logo. So `"file": "logo.png"` shows the MSK logo @@ -23,5 +23,10 @@ Configure them in `config/config.jsonc`: }, ``` +Without access to this folder (a hosted bot), upload the images in the web +dashboard under Configuration, section "Ticket Panel". They are stored here as +`custom-logo-.` and `custom-banner-.`, and the config is +updated for you. Reset to default deletes them again. + The other images in this folder (`msk-ticket-bot-banner.png`, `bot-hosting-*.png`) belong to the documentation. diff --git a/docs/configuration-de.md b/docs/configuration-de.md index 4bee81c..2195850 100644 --- a/docs/configuration-de.md +++ b/docs/configuration-de.md @@ -122,6 +122,10 @@ Tokens, der MSK-API-Key, Datenbank-Zugangsdaten und Dashboard-Secrets gehören i `panel.logo.file` und `panel.banner.file` nennen eine Datei in `assets/`. Dein eigenes Logo oder Banner legst du dort ab, etwa als `assets/logo.png` oder `assets/banner.png`. Liegt die Datei nicht in `assets/`, sucht der Bot in `assets/default/`. Dort liegt das MSK-Logo, `"file": "logo.png"` zeigt also das MSK-Logo, bis du ein eigenes ablegst. Bilder, die du in `assets/` ablegst, ignoriert git, und die Update-Routine legt ein ersetztes `assets/logo.png` beiseite und stellt es danach zurück. Deine Bilder blockieren also kein Update. +Ohne Zugriff auf die Dateien des Servers (ein gehosteter Bot) lädst du Logo oder Banner stattdessen im Dashboard hoch: **Konfiguration**, Abschnitt *Ticket Panel*. Das Dashboard prüft und wandelt das Bild um, legt es unter einem erzeugten Namen wie `custom-logo-3f2a9c1e5b7d4a60.png` in `assets/` ab und trägt diesen Namen in `panel.logo.file` beziehungsweise `panel.banner.file` ein. Aus SVG wird PNG. Das Größenlimit (`ASSET_UPLOAD_MAX_MB`, Vorgabe 5 MB) und der optionale Virenscan mit ClamAV (`CLAMAV_SOCKET` oder `CLAMAV_HOST`/`CLAMAV_PORT`) stehen in der `.env`, siehe [Panel-Bilder im Dashboard](dashboard-de.md#panel-bilder). + +Ein Dateiname muss innerhalb von `assets/` bleiben: ein Name wie `../.env` wird ignoriert. + ## Texte anpassen Einen Text des Bots änderst du im Dashboard (Konfiguration, Reiter der Locale-Datei) oder trägst ihn selbst in `locales/custom/.json` ein. Diese Datei enthält nur die Texte, die du änderst, im selben Aufbau wie `locales/.json`: diff --git a/docs/configuration-en.md b/docs/configuration-en.md index d74e3a9..906144b 100644 --- a/docs/configuration-en.md +++ b/docs/configuration-en.md @@ -122,6 +122,10 @@ Tokens, the MSK API key, database credentials and dashboard secrets go into `.en `panel.logo.file` and `panel.banner.file` name a file in `assets/`. Put your own logo or banner there, for example `assets/logo.png` or `assets/banner.png`. When the file is not in `assets/`, the bot looks in `assets/default/`, which holds the MSK logo, so `"file": "logo.png"` shows the MSK logo until you add your own. Images you add to `assets/` are ignored by git, and the update routine sets a replaced `assets/logo.png` aside and puts it back, so your images never block an update. +Without access to the server's files (a hosted bot), upload the logo or banner in the dashboard instead: **Configuration**, section *Ticket Panel*. The dashboard checks and converts the image, stores it in `assets/` under a generated name like `custom-logo-3f2a9c1e5b7d4a60.png` and sets `panel.logo.file` or `panel.banner.file` to it. SVG is converted to PNG. The size limit (`ASSET_UPLOAD_MAX_MB`, default 5 MB) and the optional ClamAV virus scan (`CLAMAV_SOCKET` or `CLAMAV_HOST`/`CLAMAV_PORT`) are set in `.env`, see [Panel images in the dashboard](dashboard-en.md#panel-images). + +A file name must stay inside `assets/`: a name like `../.env` is ignored. + ## Changing texts Change a bot text in the dashboard (Configuration, tab of the locale file) or write it into `locales/custom/.json` yourself. That file holds only the texts you change, in the same structure as `locales/.json`: diff --git a/docs/dashboard-de.md b/docs/dashboard-de.md index 6880591..f25a9ce 100644 --- a/docs/dashboard-de.md +++ b/docs/dashboard-de.md @@ -17,7 +17,7 @@ aktivierst, ändert sich an deinem Bot nichts. | **Meine Tickets** | Jedes Mitglied sieht die selbst geöffneten Tickets und kann in offenen antworten. Die Antwort erscheint im Discord-Kanal unter dem eigenen Namen. Geschlossene Tickets bieten einen Transcript-Download und, mit Premium, einen "Transcript öffnen"-Link. | | **Tickets** | Vollständige Liste mit Filtern, Ticket-Detail mit dem Live-Verlauf, Claim / Schließen / Wieder öffnen / Verschieben / Sperren / Priorität. | | **Statistiken** | Gesamtzahlen, Durchschnittsbewertung, durchschnittliche Bearbeitungszeit und ein Team-Ranking nach geschlossenen Tickets. | -| **Konfiguration** | Bearbeite `config.jsonc`, `snippets.jsonc`, `.env` und die Locale-Dateien wahlweise in einer strukturierten **Formular**-Ansicht oder einer rohen **Datei**-Ansicht (mit Zeilennummern und Syntax-Highlighting). Formular-Änderungen erhalten die `//`-Kommentare, und ein Seitenpanel löst Discord-Rollen-/Kanal-/Kategorie-**Namen** auf, sodass du nie nach rohen IDs suchen musst. Änderungen an einer Locale-Datei landen als Unterschied zu den mitgelieferten Texten in `locales/custom/`, Updates behalten sie also; **Auf Standard zurücksetzen** entfernt sie wieder (siehe [Texte anpassen](configuration-de.md#texte-anpassen)). | +| **Konfiguration** | Bearbeite `config.jsonc`, `snippets.jsonc`, `.env` und die Locale-Dateien wahlweise in einer strukturierten **Formular**-Ansicht oder einer rohen **Datei**-Ansicht (mit Zeilennummern und Syntax-Highlighting). Formular-Änderungen erhalten die `//`-Kommentare, und ein Seitenpanel löst Discord-Rollen-/Kanal-/Kategorie-**Namen** auf, sodass du nie nach rohen IDs suchen musst. Änderungen an einer Locale-Datei landen als Unterschied zu den mitgelieferten Texten in `locales/custom/`, Updates behalten sie also; **Auf Standard zurücksetzen** entfernt sie wieder (siehe [Texte anpassen](configuration-de.md#texte-anpassen)). Logo und Banner des Panels lädst du direkt dort hoch (siehe [Panel-Bilder](#panel-bilder)). | | **Bot-Steuerung** | Starten, stoppen, neu starten und aktualisieren des Bots, plus eine Live-Konsole. **Update** führt dieselbe Routine aus wie `npm run update` (siehe [Aktualisieren](installation-de.md#aktualisieren)). | | **Berechtigungen** | Lege fest, welche Rollen und Nutzer das Dashboard verwenden dürfen und was sie tun dürfen. | | **Dashboard-Einstellungen** | Akzentfarbe und Favicon, abgesichert über eigene Ansehen-/Bearbeiten-Rechte. Die Akzentfarbe wird an die helle und die dunkle Darstellung angepasst. | @@ -85,6 +85,63 @@ reduzierte Bewegung, mehr Kontrast und die Windows-Kontrastdesigns. --- +## Panel-Bilder + +Unter **Konfiguration**, Abschnitt *Ticket Panel*, haben Logo und Banner je einen +Upload, eine Vorschau des aktuellen Bildes und **Auf Standard zurücksetzen**. So +änderst du sie bei einem gehosteten Bot, bei dem du keinen Zugriff auf die +Dateien des Servers hast. Dafür braucht es das Recht `config.edit`, und jeder +Upload und jedes Zurücksetzen steht im Audit-Log. + +Angenommen werden **PNG, JPEG, GIF, WebP und SVG** bis **5 MB** je Datei (siehe +`ASSET_UPLOAD_MAX_MB` unten). Der Typ wird aus dem Inhalt der Datei gelesen, +nicht aus ihrem Namen. Danach wird jedes Bild umgewandelt: + +* Es wird dekodiert und als neue Datei gespeichert. Metadaten wie Standort, + Kameradaten oder Kommentare überstehen das nicht, und auch nichts, was hinter + den Bilddaten versteckt ist. +* Das Logo wird auf höchstens 1024 px verkleinert, das Banner auf höchstens + 2048 px. Kleinere Bilder behalten ihre Größe. +* PNG bleibt PNG, JPEG bleibt JPEG, WebP bleibt WebP, ein animiertes GIF bleibt + animiert. Ein unbewegtes GIF wird zu PNG. +* **SVG wird immer zu PNG.** Discord kann SVG im Panel nicht anzeigen, und eine + SVG-Datei kann Skripte enthalten. SVGs mit Skripten, Verweisen auf andere + Dateien oder Webadressen oder mit Entity-Deklarationen werden abgelehnt. +* Bilder mit sehr vielen Pixeln (mehr als 30 Megapixel, etwa eine + "Dekompressionsbombe", die als Datei winzig und im Speicher riesig ist) werden + abgelehnt, bevor sie dekodiert werden. + +Gespeichert wird das Bild in `assets/` unter einem erzeugten Namen wie +`custom-logo-3f2a9c1e5b7d4a60.png`, und `panel.logo.file` beziehungsweise +`panel.banner.file` in `config.jsonc` wird auf diesen Namen gesetzt, alle +Kommentare bleiben erhalten. Das zuvor hochgeladene Bild desselben Platzes wird +gelöscht; Bilder, die du selbst in `assets/` gelegt hast, und das mitgelieferte +Standardbild bleiben unangetastet. **Auf Standard zurücksetzen** setzt den Namen +zurück auf `logo.png` beziehungsweise `banner.png` und löscht die hochgeladene +Datei. Wie jede andere Änderung an der Konfiguration verwendet das Panel das neue +Bild nach dem nächsten Neustart des Bots. + +### Virenscan (optional) + +Läuft [ClamAV](https://www.clamav.net/) auf dem Server, kann das Dashboard jeden +Upload von `clamd` prüfen lassen, bevor es ihn verarbeitet. Setze entweder +`CLAMAV_SOCKET` (den Pfad des lokalen Sockets von clamd, unter Debian meist +`/var/run/clamav/clamd.ctl`) oder `CLAMAV_HOST` und `CLAMAV_PORT`. Der Benutzer, +unter dem das Dashboard läuft, muss den Socket benutzen dürfen. + +* Eine Datei, die clamd meldet, wird abgelehnt und mit dem Namen des Fundes ins + Audit-Log geschrieben. +* Ist ClamAV eingetragen, antwortet aber nicht (gestoppt, falscher Pfad, + Zeitüberschreitung), werden Uploads **abgelehnt**, bis es wieder antwortet. Ein + eingetragener Scanner lässt nie eine Datei ungeprüft durch. +* Ohne diese Variablen meldet das Dashboard beim Start einmal im Log, dass + Uploads nicht auf Viren geprüft werden. Umgewandelt werden die Bilder trotzdem + wie oben beschrieben. + +`StreamMaxLength` von clamd (Vorgabe 25 MB) muss größer sein als das Upload-Limit. + +--- + ## Schnellstart ```bash @@ -242,6 +299,9 @@ Ticket ist, bevor irgendetwas Discord erreicht. | `DASHBOARD_ALLOW_INSECURE` | `false` | Nur, wenn du TLS an einer Stelle terminierst, die der Bot nicht sieht | | `SESSION_SECRET` | *erzeugt* | Schlüssel für die Cookie-Signatur. Niemals teilen oder wiederverwenden. | | `CLIENT_SECRET` | (keins) | Discord-OAuth2-Client-Secret | +| `ASSET_UPLOAD_MAX_MB` | `5` | Größenlimit für den Upload eines Panel-Bildes in MB, zwischen 1 und 10 | +| `CLAMAV_SOCKET` | (keiner) | Socket von clamd für den Virenscan der Uploads, z. B. `/var/run/clamav/clamd.ctl` | +| `CLAMAV_HOST` / `CLAMAV_PORT` | (keiner) / `3310` | clamd über TCP statt über einen Socket. Sind beide gesetzt, gilt `CLAMAV_SOCKET`. | --- diff --git a/docs/dashboard-en.md b/docs/dashboard-en.md index 2789ed2..e04af41 100644 --- a/docs/dashboard-en.md +++ b/docs/dashboard-en.md @@ -17,7 +17,7 @@ nothing about your bot changes. | **My tickets** | Every member sees the tickets they opened and can reply to the open ones. Their reply is posted in the Discord channel under their own name. Closed tickets offer a transcript download and, on premium, an "Open transcript" link. | | **Tickets** | Full list with filters, ticket detail with the live conversation, claim / close / reopen / move / lock / priority. | | **Statistics** | Totals, average rating, average handling time, and a team ranking by tickets closed. | -| **Configuration** | Edit `config.jsonc`, `snippets.jsonc`, `.env` and the locale files in either a structured **form** view or a raw **file** view (with line numbers and syntax highlighting). Form edits preserve the `//` comments, and a side panel resolves Discord role/channel/category **names** so you never have to hunt for raw IDs. Changes to a locale file are stored in `locales/custom/` as the difference to the shipped texts, so updates keep them; **Reset to default** removes them again (see [Changing texts](configuration-en.md#changing-texts)). | +| **Configuration** | Edit `config.jsonc`, `snippets.jsonc`, `.env` and the locale files in either a structured **form** view or a raw **file** view (with line numbers and syntax highlighting). Form edits preserve the `//` comments, and a side panel resolves Discord role/channel/category **names** so you never have to hunt for raw IDs. Changes to a locale file are stored in `locales/custom/` as the difference to the shipped texts, so updates keep them; **Reset to default** removes them again (see [Changing texts](configuration-en.md#changing-texts)). The panel logo and banner can be uploaded right there (see [Panel images](#panel-images)). | | **Bot control** | Start, stop, restart and update the bot, plus a live console. **Update** runs the same routine as `npm run update` (see [Updating](installation-en.md#updating)). | | **Permissions** | Decide which roles and users may use the dashboard, and what they may do. | | **Dashboard settings** | Accent colour and favicon, gated by their own view / edit permissions. The accent is fitted to the light and the dark theme. | @@ -79,6 +79,62 @@ and the Windows contrast themes. --- +## Panel images + +In **Configuration**, section *Ticket Panel*, the logo and the banner each have +an upload, a preview of the current image and **Reset to default**. This is the +way to change them on a hosted bot, where you have no access to the server's +files. It needs the `config.edit` permission, and every upload and reset is in +the audit log. + +Accepted are **PNG, JPEG, GIF, WebP and SVG**, up to **5 MB** per file (see +`ASSET_UPLOAD_MAX_MB` below). The type is read from the file's content, not from +its name. Every image is then converted: + +* It is decoded and saved again as a new file. Metadata such as the location, + camera data or comments does not survive, and neither does anything hidden + behind the image data. +* The logo is scaled down to at most 1024 px, the banner to at most 2048 px. + Smaller images keep their size. +* PNG stays PNG, JPEG stays JPEG, WebP stays WebP, an animated GIF stays + animated. A still GIF becomes PNG. +* **SVG is always converted to PNG.** Discord cannot show SVG in the panel, and + an SVG file can contain scripts. SVGs with scripts, links to other files or + web addresses, or entity declarations are refused. +* Images with very many pixels (more than 30 megapixels, for example a + "decompression bomb" that is tiny as a file and huge in memory) are refused + before they are decoded. + +The image is stored in `assets/` under a generated name such as +`custom-logo-3f2a9c1e5b7d4a60.png`, and `panel.logo.file` or `panel.banner.file` +in `config.jsonc` is set to that name, with all comments kept. The previously +uploaded image of the same slot is deleted; images you put into `assets/` +yourself and the shipped default are never touched. **Reset to default** sets +the name back to `logo.png` or `banner.png` and deletes the uploaded file. Like +any other config change, the panel uses the new image after the next restart of +the bot. + +### Virus scan (optional) + +If [ClamAV](https://www.clamav.net/) runs on the server, the dashboard can have +every upload scanned by `clamd` before it is processed. Set either +`CLAMAV_SOCKET` (the path of clamd's local socket, on Debian usually +`/var/run/clamav/clamd.ctl`) or `CLAMAV_HOST` and `CLAMAV_PORT`. The user the +dashboard runs as must be allowed to use the socket. + +* A file clamd flags is refused and written to the audit log with the name of + the finding. +* If ClamAV is configured but does not answer (stopped, wrong path, timeout), + uploads are **refused** until it answers again. A configured scanner never + lets a file through unscanned. +* Without these variables the dashboard logs once at start that uploads are not + virus scanned. Images are still converted as described above. + +clamd's `StreamMaxLength` (25 MB by default) has to be larger than the upload +limit. + +--- + ## Quick start ```bash @@ -231,6 +287,9 @@ reaches Discord. | `DASHBOARD_ALLOW_INSECURE` | `false` | Only if you terminate TLS somewhere the bot cannot see | | `SESSION_SECRET` | *generated* | Cookie signing key. Never share or reuse it. | | `CLIENT_SECRET` | (none) | Discord OAuth2 client secret | +| `ASSET_UPLOAD_MAX_MB` | `5` | Size limit for a panel image upload in MB, between 1 and 10 | +| `CLAMAV_SOCKET` | (none) | clamd socket for the virus scan of uploads, e.g. `/var/run/clamav/clamd.ctl` | +| `CLAMAV_HOST` / `CLAMAV_PORT` | (none) / `3310` | clamd over TCP instead of a socket. `CLAMAV_SOCKET` wins when both are set. | --- diff --git a/package-lock.json b/package-lock.json index e098578..0dbfef9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,9 +12,9 @@ "better-sqlite3": "^13.0.3", "discord.js": "^14.27.0", "dotenv": "^18.0.9", - "express-rate-limit": "8.7.2", "mysql2": "^3.24.6", - "pg": "^8.23.1" + "pg": "^8.23.1", + "sharp": "^0.35.5" }, "engines": { "node": ">=24.0.0" @@ -155,6 +155,564 @@ "url": "https://github.com/discordjs/discord.js?sponsor" } }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@img/colour": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz", + "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-freebsd-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", + "cpu": [ + "riscv64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.3.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.11.3" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-webcontainers-wasm32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/sharp-wasm32": "0.35.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, "node_modules/@sapphire/async-queue": { "version": "1.5.5", "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz", @@ -393,6 +951,15 @@ "node": ">= 0.8" } }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, "node_modules/discord-api-types": { "version": "0.38.50", "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.50.tgz", @@ -1256,6 +1823,18 @@ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, + "node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/send": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", @@ -1310,6 +1889,55 @@ "license": "ISC", "optional": true }, + "node_modules/sharp": { + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.1.0", + "detect-libc": "^2.1.2", + "semver": "^7.8.5" + }, + "engines": { + "node": ">=20.9.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, "node_modules/side-channel": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", diff --git a/package.json b/package.json index 972b6a0..0e113f3 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,8 @@ "discord.js": "^14.27.0", "dotenv": "^18.0.9", "mysql2": "^3.24.6", - "pg": "^8.23.1" + "pg": "^8.23.1", + "sharp": "^0.35.5" }, "optionalDependencies": { "express": "^5.3.0", diff --git a/src/dashboard/clamav.js b/src/dashboard/clamav.js new file mode 100644 index 0000000..188bb23 --- /dev/null +++ b/src/dashboard/clamav.js @@ -0,0 +1,153 @@ +/** + * Minimal clamd client: the zINSTREAM command over a UNIX or TCP socket. + * + * Written against node's net module instead of a package, because the protocol + * is four lines long: + * + * send "zINSTREAM\0" + * send (repeated) + * send (end of stream) + * read "stream: OK\0" | "stream: FOUND\0" | " ERROR\0" + * + * Every failure that is not a clean answer (refused connection, timeout, an + * ERROR reply such as "INSTREAM size limit exceeded", a reply we do not + * understand) rejects with ClamavUnavailableError. The caller treats that as + * "not scanned" and refuses the upload: a configured scanner fails closed. + */ + +const net = require('net'); + +const CHUNK_SIZE = 64 * 1024; +const DEFAULT_TIMEOUT_MS = 15_000; + +class ClamavUnavailableError extends Error { + constructor(message) { + super(message); + this.name = 'ClamavUnavailableError'; + } +} + +/** + * Scanner settings from the environment. CLAMAV_SOCKET wins over + * CLAMAV_HOST/CLAMAV_PORT. Returns null when neither is set (scanning off). + * An unusable value is returned as { invalid } so the scanner fails closed + * instead of silently not scanning. + * @param {NodeJS.ProcessEnv} [env] + * @returns {null|{socketPath: string}|{host: string, port: number}|{invalid: string}} + */ +function clamavConfigFromEnv(env = process.env) { + const socketPath = String(env.CLAMAV_SOCKET ?? '').trim(); + if (socketPath) return { socketPath }; + + const host = String(env.CLAMAV_HOST ?? '').trim(); + if (!host) return null; + + const rawPort = String(env.CLAMAV_PORT ?? '').trim(); + const port = rawPort === '' ? 3310 : Number(rawPort); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + return { invalid: `CLAMAV_PORT "${rawPort}" is not a valid port.` }; + } + return { host, port }; +} + +/** Human-readable target for log lines. */ +function describeTarget(cfg) { + if (!cfg) return 'not configured'; + if (cfg.invalid) return `invalid (${cfg.invalid})`; + return cfg.socketPath ? `socket ${cfg.socketPath}` : `${cfg.host}:${cfg.port}`; +} + +/** + * Send one clamd command, optionally followed by a body, and resolve with the + * NUL-terminated reply as a trimmed string. + */ +function clamdRequest(cfg, command, body, timeoutMs) { + return new Promise((resolve, reject) => { + if (!cfg || cfg.invalid) { + reject(new ClamavUnavailableError(cfg?.invalid ?? 'ClamAV is not configured.')); + return; + } + + const socket = cfg.socketPath + ? net.createConnection({ path: cfg.socketPath }) + : net.createConnection({ host: cfg.host, port: cfg.port }); + + const chunks = []; + let settled = false; + const finish = (err, value) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + if (err) reject(err); else resolve(value); + }; + const reply = () => Buffer.concat(chunks).toString('utf-8').replace(/\0+$/, '').trim(); + + const timer = setTimeout( + () => finish(new ClamavUnavailableError(`ClamAV did not answer within ${Math.round(timeoutMs / 1000)}s.`)), + timeoutMs, + ); + + socket.on('data', (data) => { + chunks.push(data); + if (data.includes(0)) finish(null, reply()); + }); + socket.on('end', () => { + if (chunks.length) finish(null, reply()); + else finish(new ClamavUnavailableError('ClamAV closed the connection without an answer.')); + }); + // clamd may close the socket while we are still writing (for example once + // StreamMaxLength is exceeded). Whatever it answered before that wins. + socket.on('error', (err) => { + if (chunks.length) finish(null, reply()); + else finish(new ClamavUnavailableError(`ClamAV is not reachable (${err.code || err.message}).`)); + }); + + socket.on('connect', () => { + socket.write(`z${command}\0`); + if (body) { + for (let offset = 0; offset < body.length; offset += CHUNK_SIZE) { + const chunk = body.subarray(offset, offset + CHUNK_SIZE); + const size = Buffer.alloc(4); + size.writeUInt32BE(chunk.length, 0); + socket.write(size); + socket.write(chunk); + } + socket.write(Buffer.alloc(4)); // zero-length chunk ends the stream + } + }); + }); +} + +/** + * Scan a buffer with clamd. + * @param {Buffer} buf + * @param {object} cfg from clamavConfigFromEnv + * @param {{timeoutMs?: number}} [opts] + * @returns {Promise<{clean: true}|{clean: false, signature: string}>} + * @throws {ClamavUnavailableError} on every outcome that is not a verdict + */ +async function scanBuffer(buf, cfg, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) { + const answer = await clamdRequest(cfg, 'INSTREAM', buf, timeoutMs); + if (/^stream:\s*OK$/i.test(answer)) return { clean: true }; + const found = answer.match(/^stream:\s*(.+?)\s+FOUND$/i); + if (found) return { clean: false, signature: found[1] }; + throw new ClamavUnavailableError(`ClamAV could not scan the file (${answer.slice(0, 200) || 'empty reply'}).`); +} + +/** Resolves true when clamd answers PING with PONG, false otherwise. Never throws. */ +async function pingClamd(cfg, { timeoutMs = 5_000 } = {}) { + try { + return (await clamdRequest(cfg, 'PING', null, timeoutMs)) === 'PONG'; + } catch { + return false; + } +} + +module.exports = { + ClamavUnavailableError, + clamavConfigFromEnv, + describeTarget, + scanBuffer, + pingClamd, +}; diff --git a/src/dashboard/imageSanitizer.js b/src/dashboard/imageSanitizer.js new file mode 100644 index 0000000..485cbd0 --- /dev/null +++ b/src/dashboard/imageSanitizer.js @@ -0,0 +1,256 @@ +/** + * Panel image intake: type detection and sanitising re-encode. + * + * Everything here works on the uploaded BYTES. The client's file name and MIME + * type never reach a decision: the type comes from the magic bytes (or, for SVG, + * from a strict text check), and the stored file is a fresh encode of the + * decoded pixels. Re-encoding is what strips EXIF, GPS, ICC comments, XMP and + * anything appended after the image data (polyglot payloads), because none of + * it survives the trip through a pixel buffer. + * + * sharp is required lazily: only the dashboard process needs it, and a platform + * without a prebuilt binary should lose the upload feature, not the dashboard. + */ + +// Decompression-bomb guard: the decoder refuses anything larger than this many +// pixels before it allocates the pixel buffer. 30 MP covers a 24 MP camera photo +// and short animated GIFs (sharp counts every frame), and caps the RGBA buffer +// at roughly 120 MB. +const MAX_INPUT_PIXELS = 30_000_000; + +// Discord rejects attachments above 10 MiB, and the panel posts the image as an +// attachment. A re-encode (an animated GIF in particular) can grow, so the +// result is checked as well. +const MAX_OUTPUT_BYTES = 10 * 1024 * 1024; + +// A slow decode must not hold the single upload slot forever. +const PROCESS_TIMEOUT_SECONDS = 20; + +// An SVG icon with a 24px viewBox would otherwise be rasterised at 24px. It is +// rendered at a higher density instead (vector, so no upscaling of pixels), up +// to this factor. +const MAX_SVG_SCALE = 16; + +const ALLOWED_TYPES = ['png', 'jpeg', 'gif', 'webp', 'svg']; + +class ImageRejectedError extends Error { + /** @param {number} status HTTP status the route should answer with */ + constructor(status, message) { + super(message); + this.name = 'ImageRejectedError'; + this.status = status; + } +} + +const startsWith = (buf, bytes, offset = 0) => + buf.length >= offset + bytes.length && bytes.every((b, i) => buf[offset + i] === b); + +const ascii = (s) => [...s].map(c => c.charCodeAt(0)); + +/** + * The image type, taken from the content. Raster formats by magic bytes; SVG by + * a text check (UTF-8, optional XML prolog, then an root element). + * @param {Buffer} buf + * @returns {'png'|'jpeg'|'gif'|'webp'|'svg'|null} + */ +function detectImageType(buf) { + if (!Buffer.isBuffer(buf) || buf.length === 0) return null; + if (startsWith(buf, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return 'png'; + if (startsWith(buf, [0xff, 0xd8, 0xff])) return 'jpeg'; + if (startsWith(buf, ascii('GIF87a')) || startsWith(buf, ascii('GIF89a'))) return 'gif'; + if (startsWith(buf, ascii('RIFF')) && startsWith(buf, ascii('WEBP'), 8)) return 'webp'; + if (decodeSvgText(buf) !== null) return 'svg'; + return null; +} + +/** + * The SVG document as text, or null when the bytes are not an SVG document: + * strict UTF-8, no NUL bytes, and after an optional BOM, XML declaration, + * comments and a DOCTYPE the first element is . + * @param {Buffer} buf + * @returns {string|null} + */ +function decodeSvgText(buf) { + let text; + try { + text = new TextDecoder('utf-8', { fatal: true }).decode(buf); + } catch { + return null; + } + if (text.includes('\0')) return null; + if (text.charCodeAt(0) === 0xfeff) text = text.slice(1); + + let rest = text; + for (;;) { + rest = rest.replace(/^\s+/, ''); + const m = rest.match(/^<\?xml[\s\S]*?\?>/) || rest.match(/^/) || rest.match(/^]*>/i); + if (!m) break; + rest = rest.slice(m[0].length); + } + return /^/]/.test(rest) && /<\/svg\s*>\s*$|\/>\s*$/.test(text.trim()) ? text : null; +} + +// Rules an SVG must pass before it is handed to the renderer. Deliberately a +// deny-by-default on anything that can reach outside the document: there is no +// legitimate need for scripts, external references or entities in a logo. +const SVG_RULES = [ + [/]*\[/i, 'an internal DTD'], + [/<\?xml-stylesheet/i, 'an external stylesheet'], + [/<\s*script/i, 'a script'], + [/<\s*foreignObject/i, 'embedded HTML (foreignObject)'], + [/<\s*(?:iframe|embed|object|audio|video|canvas)\b/i, 'embedded content'], + [/<\s*[a-z0-9_-]*:?include\b/i, 'an XInclude'], + [/\son[a-z]+\s*=/i, 'an event handler attribute'], + [/javascript\s*:/i, 'a javascript: URL'], + [/@import/i, 'a CSS import'], + [/url\(\s*(?![\s'"]*#)/i, 'a CSS url() that is not a local reference'], +]; + +/** + * Strict safety check of an SVG document. Only local references (href="#id") + * are allowed; any external href/src, including data: URIs, is refused so the + * renderer never loads anything but the document itself. + * @param {Buffer} buf + * @returns {{ok: true}|{ok: false, reason: string}} + */ +function checkSvgSafety(buf) { + const text = decodeSvgText(buf); + if (text === null) return { ok: false, reason: 'The file is not a valid SVG document.' }; + + for (const [re, what] of SVG_RULES) { + if (re.test(text)) return { ok: false, reason: `SVG files with ${what} are not allowed. Export the logo as PNG instead.` }; + } + const refRe = /\b(?:xlink:)?(?:href|src)\s*=\s*(["'])([\s\S]*?)\1/gi; + for (const m of text.matchAll(refRe)) { + if (!m[2].trim().startsWith('#')) { + return { ok: false, reason: 'SVG files that reference other files or URLs are not allowed. Export the logo as PNG instead.' }; + } + } + return { ok: true }; +} + +let sharpModule; +function loadSharp() { + if (sharpModule === undefined) { + try { + sharpModule = require('sharp'); + // No libvips operation cache: the dashboard processes a few uploads a day, + // keeping decoded images around only costs memory. + sharpModule.cache(false); + } catch { + sharpModule = null; + } + } + if (!sharpModule) { + throw new ImageRejectedError(503, 'Image processing is not available on this installation (the sharp module could not be loaded). Run npm install and restart the dashboard.'); + } + return sharpModule; +} + +/** + * Decode the image and encode it fresh. Nothing of the input but its pixels + * reaches the output. + * + * png, svg, static gif → PNG + * jpeg → JPEG (photos stay small) + * webp → WebP (animation kept) + * animated gif → GIF (animation kept) + * + * SVG is always rasterised: Discord does not render SVG in embeds, and an SVG + * file can carry script. + * + * @param {Buffer} input raw upload + * @param {'png'|'jpeg'|'gif'|'webp'|'svg'} type from detectImageType + * @param {{maxWidth: number, maxHeight: number}} bounds + * @returns {Promise<{buffer: Buffer, ext: string, mime: string, format: string, width: number, height: number, animated: boolean}>} + */ +async function sanitizeImage(input, type, { maxWidth, maxHeight }) { + if (!ALLOWED_TYPES.includes(type)) throw new ImageRejectedError(415, 'Unsupported image type.'); + const sharp = loadSharp(); + + // failOn 'error' rejects corrupt and truncated input; 'warning' would also + // refuse many real camera JPEGs over harmless libjpeg warnings. + const base = { limitInputPixels: MAX_INPUT_PIXELS, failOn: 'error' }; + const animatable = type === 'gif' || type === 'webp'; + const opts = animatable ? { ...base, animated: true } : { ...base }; + + let meta; + try { + meta = await sharp(input, opts).metadata(); + } catch (err) { + throw mapSharpError(err); + } + if (!meta.width || !meta.height) throw new ImageRejectedError(422, 'The image has no readable dimensions.'); + + if (type === 'svg') { + const scale = Math.min(maxWidth / meta.width, maxHeight / meta.height, MAX_SVG_SCALE); + if (scale > 1) opts.density = Math.round(72 * scale); + } + + const animated = animatable && (meta.pages ?? 1) > 1; + let pipeline = sharp(input, opts); + if (!animated) pipeline = pipeline.autoOrient(); // apply EXIF rotation before it is dropped + pipeline = pipeline + .resize({ width: maxWidth, height: maxHeight, fit: 'inside', withoutEnlargement: true }) + .timeout({ seconds: PROCESS_TIMEOUT_SECONDS }); + + let format; + if (type === 'jpeg') { + format = 'jpeg'; + pipeline = pipeline.jpeg({ quality: 90, mozjpeg: true }); + } else if (type === 'webp') { + format = 'webp'; + pipeline = pipeline.webp({ quality: 90 }); + } else if (animated) { + format = 'gif'; + pipeline = pipeline.gif(); + } else { + format = 'png'; + pipeline = pipeline.png({ compressionLevel: 9 }); + } + + let result; + try { + result = await pipeline.toBuffer({ resolveWithObject: true }); + } catch (err) { + throw mapSharpError(err); + } + if (result.info.format !== format) throw new ImageRejectedError(500, 'The image could not be converted.'); + if (result.data.length > MAX_OUTPUT_BYTES) { + throw new ImageRejectedError(413, 'The processed image is larger than the 10 MB Discord allows for an attachment. Use a smaller image.'); + } + + const out = { jpeg: ['jpg', 'image/jpeg'], webp: ['webp', 'image/webp'], gif: ['gif', 'image/gif'], png: ['png', 'image/png'] }[format]; + return { + buffer: result.data, + ext: out[0], + mime: out[1], + format, + width: result.info.width, + height: result.info.pageHeight ?? result.info.height, + animated, + }; +} + +function mapSharpError(err) { + if (err instanceof ImageRejectedError) return err; + const msg = String(err?.message ?? ''); + if (/pixel limit/i.test(msg)) { + return new ImageRejectedError(413, 'The image dimensions are too large. Use an image with fewer pixels.'); + } + if (/timeout/i.test(msg)) { + return new ImageRejectedError(422, 'The image took too long to process.'); + } + return new ImageRejectedError(422, 'The image could not be read. It may be corrupt or not a real image.'); +} + +module.exports = { + ALLOWED_TYPES, + MAX_INPUT_PIXELS, + MAX_OUTPUT_BYTES, + ImageRejectedError, + detectImageType, + checkSvgSafety, + sanitizeImage, +}; diff --git a/src/dashboard/jsoncPatch.js b/src/dashboard/jsoncPatch.js new file mode 100644 index 0000000..c62937b --- /dev/null +++ b/src/dashboard/jsoncPatch.js @@ -0,0 +1,127 @@ +/** + * Replace one string value inside a JSONC document without touching anything + * else: comments, key order, indentation and every other value stay + * byte-for-byte the same. + * + * The config editor in the browser does the same with jsonc-parser; the server + * side has no such dependency and needs exactly one operation, so this walks the + * document itself. It runs on the output of stripJsonComments, which blanks + * comments out with spaces and keeps every offset, so a position found in the + * stripped text is the same position in the original. + */ + +const { stripJsonComments } = require('../config'); + +/** + * Offsets [start, end) of the string literal at `target` in a comment-free + * JSON text, or null when the path does not exist or is not a string. With + * duplicate keys the last one wins, as in JSON.parse. + * @param {string} json + * @param {string[]} target + * @returns {{start: number, end: number}|null} + */ +function locateString(json, target) { + let i = 0; + let found = null; + + const ws = () => { while (i < json.length && /\s/.test(json[i])) i++; }; + + const readString = () => { + const start = i; + i++; // opening quote + while (i < json.length) { + if (json[i] === '\\') { i += 2; continue; } + if (json[i] === '"') { i++; return { start, end: i }; } + i++; + } + throw new Error('Unterminated string.'); + }; + + const isPrefix = (path) => path.length <= target.length && path.every((k, idx) => k === target[idx]); + + const value = (path) => { + ws(); + const ch = json[i]; + // Last key wins, as in JSON.parse: a later non-string value at the target + // cancels an earlier string. + if (path && path.length === target.length && ch !== '"') found = null; + if (ch === '{') { + i++; + ws(); + if (json[i] === '}') { i++; return; } + for (;;) { + ws(); + const keySpan = readString(); + const key = JSON.parse(json.slice(keySpan.start, keySpan.end)); + ws(); + i++; // colon + // Only the branch towards the target needs its offsets; the rest is + // walked (path null) to keep the cursor right. + const childPath = path ? [...path, key] : null; + value(childPath && isPrefix(childPath) ? childPath : null); + ws(); + if (json[i] === ',') { i++; continue; } + i++; // closing brace + return; + } + } + if (ch === '[') { + i++; + ws(); + if (json[i] === ']') { i++; return; } + for (;;) { + value(null); + ws(); + if (json[i] === ',') { i++; continue; } + i++; // closing bracket + return; + } + } + if (ch === '"') { + const span = readString(); + if (path && path.length === target.length) found = span; + return; + } + // number, true, false, null + while (i < json.length && !/[\s,}\]]/.test(json[i])) i++; + }; + + value([]); + return found; +} + +/** + * Set the string at `path` in a JSONC document. + * @param {string} text the original document (comments included) + * @param {string[]} path e.g. ['panel', 'logo', 'file'] + * @param {string} newValue + * @returns {{ok: true, text: string, previous: string}|{ok: false, reason: 'syntax'|'missing'}} + */ +function setJsoncString(text, path, newValue) { + const stripped = stripJsonComments(text); + try { + JSON.parse(stripped); + } catch { + return { ok: false, reason: 'syntax' }; + } + + const span = locateString(stripped, path); + if (!span) return { ok: false, reason: 'missing' }; + + const previous = JSON.parse(stripped.slice(span.start, span.end)); + const next = text.slice(0, span.start) + JSON.stringify(newValue) + text.slice(span.end); + + // Belt and braces: the patched document must parse and carry the new value. + let check; + try { + check = JSON.parse(stripJsonComments(next)); + } catch { + return { ok: false, reason: 'syntax' }; + } + const actual = path.reduce((node, key) => (node == null ? undefined : node[key]), check); + if (actual !== newValue) return { ok: false, reason: 'missing' }; + + return { ok: true, text: next, previous }; +} + +module.exports = { setJsoncString, locateString }; diff --git a/src/dashboard/panelAssets.js b/src/dashboard/panelAssets.js new file mode 100644 index 0000000..eb6082f --- /dev/null +++ b/src/dashboard/panelAssets.js @@ -0,0 +1,381 @@ +/** + * Panel logo and banner upload for the dashboard. + * + * Hosted customers have no shell on the server, so they cannot drop their own + * image into assets/. These routes take the image over the dashboard instead: + * + * size limit (route body parser) → type from content (magic bytes, strict + * SVG check) → ClamAV scan of the raw bytes (when configured) → sharp + * re-encode (metadata and appended data dropped, SVG rasterised) → atomic + * write under a generated name → panel..file in config.jsonc → + * previous custom file of that slot removed → audit + * + * The routes are mounted on the /api router, so they run behind the same chain + * as every other route (auth, origin check, CSRF, write rate limit). On top of + * that each declares its permission, and only one upload is processed at a time. + * + * The bot reads config.jsonc at start, so the new image is picked up after the + * next restart, exactly like a change saved in the config editor. + */ + +const crypto = require('crypto'); +const fs = require('fs/promises'); +const path = require('path'); +const express = require('express'); + +const { inspectConfig, stripJsonComments } = require('../config'); +const { resolvePanelAsset } = require('../utils/assetResolver'); +const { setJsoncString } = require('./jsoncPatch'); +const { detectImageType, checkSvgSafety, sanitizeImage, ImageRejectedError } = require('./imageSanitizer'); +const { clamavConfigFromEnv, describeTarget, scanBuffer, pingClamd, ClamavUnavailableError } = require('./clamav'); + +const DEFAULT_MAX_MB = 5; +const MIN_MAX_MB = 1; +// The hosted dashboard sits behind msk-shop, whose proxy buffers at most 10 MB of +// a request body, and Discord takes at most 10 MB per attachment. +const MAX_MAX_MB = 10; + +// Only names this module generates. Cleanup matches on this, so a shipped file or +// one the customer put there by hand is never deleted. +const CUSTOM_FILE_RE = /^custom-(logo|banner)-[0-9a-f]{16}\.(png|jpg|webp|gif)$/; + +// Previews are served for raster files only. An SVG is never sent to the browser. +const PREVIEW_TYPES = { png: 'image/png', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' }; +const MAX_PREVIEW_BYTES = 25 * 1024 * 1024; + +/** + * The slot from the URL mapped to constants. The URL value is only ever compared, + * it never becomes part of a path or a config key. + * @param {string} slot + */ +function slotSpec(slot) { + switch (slot) { + case 'logo': + return { slot: 'logo', configPath: ['panel', 'logo', 'file'], defaultFile: 'logo.png', maxWidth: 1024, maxHeight: 1024 }; + case 'banner': + return { slot: 'banner', configPath: ['panel', 'banner', 'file'], defaultFile: 'banner.png', maxWidth: 2048, maxHeight: 2048 }; + default: + return null; + } +} + +/** + * Upload limit in bytes from ASSET_UPLOAD_MAX_MB (default 5, clamped to 1..10). + * @returns {{bytes: number, mb: number, warning: string|null}} + */ +function uploadLimitFromEnv(env = process.env) { + const raw = String(env.ASSET_UPLOAD_MAX_MB ?? '').trim(); + if (raw === '') return { bytes: DEFAULT_MAX_MB * 1024 * 1024, mb: DEFAULT_MAX_MB, warning: null }; + const n = Number(raw); + if (!Number.isFinite(n) || n <= 0) { + return { + bytes: DEFAULT_MAX_MB * 1024 * 1024, + mb: DEFAULT_MAX_MB, + warning: `ASSET_UPLOAD_MAX_MB "${raw}" is not a number, using ${DEFAULT_MAX_MB} MB.`, + }; + } + const mb = Math.min(MAX_MAX_MB, Math.max(MIN_MAX_MB, n)); + return { + bytes: Math.floor(mb * 1024 * 1024), + mb, + warning: mb !== n ? `ASSET_UPLOAD_MAX_MB ${raw} is outside ${MIN_MAX_MB}..${MAX_MAX_MB}, using ${mb} MB.` : null, + }; +} + +/** Generated, content-addressed name: custom--<16 hex>.. */ +function customFileName(slot, ext, buffer) { + const hash = crypto.createHash('sha256').update(buffer).digest('hex').slice(0, 16); + return `custom-${slot}-${hash}.${ext}`; +} + +/** Temp file in the same directory, then rename: readers never see half a file. */ +async function writeFileAtomic(dir, name, buffer) { + const final = path.join(dir, name); + const tmp = path.join(dir, `.${name}.${crypto.randomBytes(6).toString('hex')}.tmp`); + await fs.mkdir(dir, { recursive: true }); + try { + await fs.writeFile(tmp, buffer, { flag: 'wx' }); + await fs.rename(tmp, final); + } catch (err) { + await fs.unlink(tmp).catch(() => {}); + throw err; + } +} + +/** + * Remove the generated files of one slot, except `keep`. Names come from the + * directory listing and must match CUSTOM_FILE_RE. + * @returns {Promise} removed names + */ +async function removeCustomFiles(dir, slot, keep = null) { + const entries = await fs.readdir(dir).catch(() => []); + const removed = []; + for (const name of entries) { + const m = CUSTOM_FILE_RE.exec(name); + if (!m || m[1] !== slot || name === keep) continue; + await fs.unlink(path.join(dir, name)).then(() => removed.push(name), () => {}); + } + return removed; +} + +/** panel..file from the config on disk, or the default when unset. */ +async function configuredFile(configFile, spec) { + const text = await fs.readFile(configFile, 'utf-8').catch(() => null); + if (text === null) return spec.defaultFile; + try { + const cfg = JSON.parse(stripJsonComments(text)); + const value = spec.configPath.reduce((node, key) => (node == null ? undefined : node[key]), cfg); + return typeof value === 'string' && value !== '' ? value : spec.defaultFile; + } catch { + return spec.defaultFile; + } +} + +/** + * Prepare (but do not write) the config change. Uses the bot's own parser and + * refuses a document the bot would not boot with, as the config editor does. + * Pending items (a panel channel not filled in yet, …) do not block: those do not + * stop the bot, and a fresh install should be able to set its logo first. + * @returns {Promise<{status: 'patch', text: string, previous: string}|{status: 'missing'}|{status: 'error', error: string}>} + */ +async function prepareConfigPatch(configFile, spec, fileName) { + const text = await fs.readFile(configFile, 'utf-8').catch(() => null); + if (text === null) return { status: 'missing' }; + + const patched = setJsoncString(text, spec.configPath, fileName); + if (!patched.ok && patched.reason === 'syntax') { + return { status: 'error', error: 'config.jsonc has a syntax error. Fix it in the config editor first, then upload again.' }; + } + if (!patched.ok) return { status: 'missing' }; + + const fatal = inspectConfig(JSON.parse(stripJsonComments(patched.text))).fatal + .filter(e => !e.startsWith('Environment variable')); + if (fatal.length > 0) { + return { status: 'error', error: `config.jsonc has errors that stop the bot from starting. Fix them first:\n${fatal.join('\n')}` }; + } + return { status: 'patch', text: patched.text, previous: patched.previous }; +} + +/** Same as the config editor's save: keep a .bak, then write. */ +async function writeConfig(configFile, text) { + await fs.copyFile(configFile, `${configFile}.bak`).catch(() => {}); + await fs.writeFile(configFile, text, 'utf-8'); +} + +/** + * Mount the panel asset routes on the (already secured) API router. + * + * @param {import('express').Router} api + * @param {object} deps + * @param {Function} deps.requirePermission + * @param {(req, action: string, target?: string, detail?: object) => void} deps.audit + * @param {string} deps.configFile absolute path of config.jsonc + * @param {string} deps.assetsDir absolute path of assets/ + * @param {NodeJS.ProcessEnv} [deps.env] + * @param {(buf: Buffer) => Promise<{clean: boolean, signature?: string}>} [deps.scan] + * override for tests; by default built from CLAMAV_* in env, or none + * @param {Pick} [deps.logger] + */ +function registerPanelAssetRoutes(api, { requirePermission, audit, configFile, assetsDir, env = process.env, scan, logger = console }) { + const limit = uploadLimitFromEnv(env); + if (limit.warning) logger.warn(`[Dashboard] ${limit.warning}`); + + // Scanner: injected (tests), configured via env, or none at all. + let scanner = scan ?? null; + if (!scanner) { + const clamCfg = clamavConfigFromEnv(env); + if (clamCfg) { + scanner = (buf) => scanBuffer(buf, clamCfg); + if (clamCfg.invalid) { + logger.error(`[Dashboard] ClamAV is misconfigured (${clamCfg.invalid}). Image uploads are refused until this is fixed.`); + } else { + pingClamd(clamCfg).then((ok) => { + if (ok) logger.log(`[Dashboard] Image uploads are virus scanned with ClamAV (${describeTarget(clamCfg)}).`); + else logger.warn(`[Dashboard] ClamAV (${describeTarget(clamCfg)}) does not answer. Image uploads are refused until it does.`); + }); + } + } else { + logger.log('[Dashboard] Image uploads are not virus scanned (no CLAMAV_SOCKET or CLAMAV_HOST set). They are still re-encoded.'); + } + } + + // One upload at a time. Decoding is the expensive part, and nobody needs to + // replace logo and banner in the same second. + let busy = false; + const oneAtATime = (req, res, next) => { + if (busy) return res.status(429).json({ error: 'Another image is being processed. Try again in a moment.' }); + busy = true; + res.once('close', () => { busy = false; }); + next(); + }; + + // Raw body for this route only, with its own limit. The global JSON limit stays + // as it is. inflate: false refuses compressed bodies (no gzip bomb). + const rawParser = express.raw({ type: 'application/octet-stream', limit: limit.bytes, inflate: false }); + const readUpload = (req, res, next) => rawParser(req, res, (err) => { + if (!err) return next(); + if (err.type === 'entity.too.large') { + return res.status(413).json({ error: `The image is larger than ${limit.mb} MB.` }); + } + if (err.type === 'encoding.unsupported') { + return res.status(415).json({ error: 'Compressed uploads are not accepted.' }); + } + return res.status(400).json({ error: 'The upload could not be read.' }); + }); + + const asyncRoute = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next); + + const slotOr404 = (req, res) => { + const spec = slotSpec(req.params.slot); + if (!spec) res.status(404).json({ error: 'Unknown image slot.' }); + return spec; + }; + + // ── State for the config form ───────────────────────────────────────────── + api.get('/panel-assets', requirePermission(['config.view', 'config.edit']), asyncRoute(async (req, res) => { + const slots = {}; + for (const slot of ['logo', 'banner']) { + const spec = slotSpec(slot); + const file = await configuredFile(configFile, spec); + slots[slot] = { + file, + custom: CUSTOM_FILE_RE.test(file), + exists: resolvePanelAsset(file, assetsDir) !== null, + defaultFile: spec.defaultFile, + }; + } + res.json({ maxBytes: limit.bytes, maxMb: limit.mb, scanned: scanner !== null, slots }); + })); + + // ── Preview of the image the bot would use ──────────────────────────────── + // Same resolution as the bot (assets/, then assets/default/). + // The bytes are served only when they are one of the raster types, with the + // Content-Type taken from the bytes, never from the file name. + api.get('/panel-assets/:slot/preview', requirePermission(['config.view', 'config.edit']), asyncRoute(async (req, res) => { + const spec = slotOr404(req, res); + if (!spec) return; + const resolved = resolvePanelAsset(await configuredFile(configFile, spec), assetsDir); + if (!resolved) return res.status(404).json({ error: 'No image found.' }); + + const stat = await fs.stat(resolved).catch(() => null); + if (!stat || stat.size > MAX_PREVIEW_BYTES) return res.status(404).json({ error: 'No image found.' }); + + const buf = await fs.readFile(resolved); + const type = detectImageType(buf); + const mime = PREVIEW_TYPES[type]; + if (!mime) return res.status(415).json({ error: 'This file cannot be previewed.' }); + + res.setHeader('Content-Type', mime); + res.setHeader('X-Content-Type-Options', 'nosniff'); + res.setHeader('Cache-Control', 'private, no-store'); + res.setHeader('Content-Disposition', 'inline'); + res.send(buf); + })); + + // ── Upload ──────────────────────────────────────────────────────────────── + api.post('/panel-assets/:slot', + requirePermission('config.edit'), + oneAtATime, + readUpload, + asyncRoute(async (req, res) => { + const spec = slotOr404(req, res); + if (!spec) return; + + if (!Buffer.isBuffer(req.body)) { + return res.status(415).json({ error: 'Send the image as application/octet-stream.' }); + } + const input = req.body; + if (input.length === 0) return res.status(400).json({ error: 'Empty upload.' }); + if (input.length > limit.bytes) return res.status(413).json({ error: `The image is larger than ${limit.mb} MB.` }); + + // 1. Type from the content. + const type = detectImageType(input); + if (!type) { + return res.status(415).json({ error: 'Only PNG, JPEG, GIF, WebP and SVG images are allowed.' }); + } + if (type === 'svg') { + const svg = checkSvgSafety(input); + if (!svg.ok) return res.status(422).json({ error: svg.reason }); + } + + // 2. Virus scan of the raw bytes. A configured scanner that cannot answer + // means the file is refused (fail closed). + if (scanner) { + let verdict; + try { + verdict = await scanner(input); + } catch (err) { + const reason = err instanceof ClamavUnavailableError ? err.message : 'ClamAV failed.'; + logger.error(`[Dashboard] Upload refused, virus scan failed: ${reason}`); + return res.status(503).json({ error: 'The virus scanner is not available, so the image was not accepted. Try again later.' }); + } + if (!verdict.clean) { + audit(req, 'panel.asset.infected', spec.slot, { signature: verdict.signature, type, bytes: input.length }); + logger.warn(`[Dashboard] Upload refused, ClamAV found ${verdict.signature} (slot ${spec.slot}, user ${req.auth?.userId}).`); + return res.status(422).json({ error: `The virus scanner flagged this file (${verdict.signature}). It was not stored.` }); + } + } + + // 3. Re-encode. + let image; + try { + image = await sanitizeImage(input, type, spec); + } catch (err) { + if (err instanceof ImageRejectedError) return res.status(err.status).json({ error: err.message }); + throw err; + } + + // 4. Prepare the config change before anything is written, so a config the + // bot could not boot with leaves no orphaned file behind. + const fileName = customFileName(spec.slot, image.ext, image.buffer); + const patch = await prepareConfigPatch(configFile, spec, fileName); + if (patch.status === 'error') return res.status(409).json({ error: patch.error }); + + // 5. Store, point the config at it, drop the previous upload of this slot. + await writeFileAtomic(assetsDir, fileName, image.buffer); + if (patch.status === 'patch') await writeConfig(configFile, patch.text); + await removeCustomFiles(assetsDir, spec.slot, fileName); + + audit(req, 'panel.asset.upload', spec.slot, { + file: fileName, + type, + format: image.format, + bytes: input.length, + stored: image.buffer.length, + scanned: scanner !== null, + }); + res.json({ + ok: true, + file: fileName, + configUpdated: patch.status === 'patch', + width: image.width, + height: image.height, + }); + }), + ); + + // ── Back to the default image ───────────────────────────────────────────── + api.delete('/panel-assets/:slot', requirePermission('config.edit'), asyncRoute(async (req, res) => { + const spec = slotOr404(req, res); + if (!spec) return; + + const patch = await prepareConfigPatch(configFile, spec, spec.defaultFile); + if (patch.status === 'error') return res.status(409).json({ error: patch.error }); + if (patch.status === 'patch') await writeConfig(configFile, patch.text); + const removed = await removeCustomFiles(assetsDir, spec.slot); + + audit(req, 'panel.asset.reset', spec.slot, { file: spec.defaultFile, removed }); + res.json({ ok: true, file: spec.defaultFile, configUpdated: patch.status === 'patch' }); + })); +} + +module.exports = { + CUSTOM_FILE_RE, + slotSpec, + uploadLimitFromEnv, + customFileName, + writeFileAtomic, + removeCustomFiles, + prepareConfigPatch, + registerPanelAssetRoutes, +}; diff --git a/src/dashboard/routes.js b/src/dashboard/routes.js index ae6b2df..4aa67e7 100644 --- a/src/dashboard/routes.js +++ b/src/dashboard/routes.js @@ -23,6 +23,8 @@ const { getGuildLookups, getChannelMessages, resolveUsers } = require('./discord const { getTranscriptUrl } = require('../utils/mskApi'); const localeStore = require('../utils/locales'); const { PERMISSIONS, PERMISSION_LABELS, isPermission, isSubjectType, parsePermissions, checkSelfEdit } = require('./permissions'); +const { registerPanelAssetRoutes } = require('./panelAssets'); +const { ASSETS_DIR } = require('../utils/assetResolver'); const ROOT = path.resolve(__dirname, '../..'); @@ -460,6 +462,17 @@ function registerRoutes(api, { config, supervisor, requirePermission, invalidate res.json({ ok: true }); })); + // ── Panel logo and banner ─────────────────────────────────────────────────── + // Upload, preview and reset of the panel images. Same permissions as the + // config editor, since an upload changes panel..file in config.jsonc. + // Pipeline and storage rules: ./panelAssets.js. + registerPanelAssetRoutes(api, { + requirePermission, + audit, + configFile: configPath('config'), + assetsDir: ASSETS_DIR, + }); + // ── Bot control ──────────────────────────────────────────────────────────── api.get('/bot/status', requirePermission(['bot.control', 'tickets.view']), (req, res) => { diff --git a/src/utils/assetResolver.js b/src/utils/assetResolver.js new file mode 100644 index 0000000..a9f0573 --- /dev/null +++ b/src/utils/assetResolver.js @@ -0,0 +1,35 @@ +const path = require('path'); +const fs = require('fs'); + +const ASSETS_DIR = path.resolve(__dirname, '../../assets'); + +/** + * Resolves a panel image named in the config. The customer's own file in + * assets/ wins; without one, the shipped default in assets/default/ + * is used (that is where the MSK logo lives, so `panel.logo.file: "logo.png"` + * works out of the box). Customer images in assets/ are gitignored, so replacing + * the logo never blocks an update. Returns null when neither file exists. + * + * The name comes from config.jsonc, which staff with "Edit configuration" can + * change in the dashboard. A name that leaves the assets folder ("../.env") is + * refused, otherwise the panel would post any readable file to Discord. + * + * Kept out of panel.js so the dashboard can use it without loading discord.js. + * @param {string} file + * @param {string} [assetsDir] + * @returns {string|null} + */ +function resolvePanelAsset(file, assetsDir = ASSETS_DIR) { + if (typeof file !== 'string' || file === '') return null; + // Only a plain file name, no folders: the config never needs more. + if (file !== path.basename(file) || file === '.' || file === '..' || file.includes('/') || file.includes('\\')) return null; + const root = path.resolve(assetsDir); + for (const candidate of [path.resolve(root, file), path.resolve(root, 'default', file)]) { + const rel = path.relative(root, candidate); + if (rel === '' || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) continue; + if (fs.statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate; + } + return null; +} + +module.exports = { ASSETS_DIR, resolvePanelAsset }; diff --git a/src/utils/panel.js b/src/utils/panel.js index f675201..b09f71f 100644 --- a/src/utils/panel.js +++ b/src/utils/panel.js @@ -7,35 +7,8 @@ const { } = require('discord.js'); const { typeOption } = require('./typeOption'); const path = require('path'); -const fs = require('fs'); const { panelEmbed } = require('./embeds'); - -const ASSETS_DIR = path.resolve(__dirname, '../../assets'); - -/** - * Resolves a panel image named in the config. The customer's own file in - * assets/ wins; without one, the shipped default in assets/default/ - * is used (that is where the MSK logo lives, so `panel.logo.file: "logo.png"` - * works out of the box). Customer images in assets/ are gitignored, so replacing - * the logo never blocks an update. Returns null when neither file exists. - * @param {string} file - * @param {string} [assetsDir] - * @returns {string|null} - */ -function resolvePanelAsset(file, assetsDir = ASSETS_DIR) { - if (typeof file !== 'string' || file === '') return null; - // Only a plain file name inside assets/ is allowed. Without this, a config - // value like "../.env" made the panel post the bot's .env (token included) - // to Discord as an attachment. - if (file !== path.basename(file) || file === '.' || file === '..' || file.includes('\\') || file.includes('/')) return null; - const root = path.resolve(assetsDir); - for (const candidate of [path.resolve(root, file), path.resolve(root, 'default', file)]) { - const rel = path.relative(root, candidate); - if (rel.startsWith('..') || path.isAbsolute(rel)) continue; - if (fs.statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate; - } - return null; -} +const { ASSETS_DIR, resolvePanelAsset } = require('./assetResolver'); /** * Builds the full ticket-panel payload (embed + interaction row + file attachments). diff --git a/tests/panel-asset-upload.test.js b/tests/panel-asset-upload.test.js new file mode 100644 index 0000000..93bb938 --- /dev/null +++ b/tests/panel-asset-upload.test.js @@ -0,0 +1,570 @@ +/** + * Panel logo/banner upload: type detection, sanitising re-encode, the clamd + * client and the dashboard routes (src/dashboard/{imageSanitizer,clamav, + * jsoncPatch,panelAssets}.js). + * + * This is a security path: an uploaded file ends up on disk and in a Discord + * message. The tests pin down what must never get through (a non-image, an SVG + * with script, metadata, an appended payload, a decompression bomb, a file the + * scanner flags) and that a configured but broken scanner refuses the upload. + */ + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const net = require('node:net'); +const path = require('node:path'); + +const sharp = require('sharp'); +const express = require('express'); + +const { + detectImageType, checkSvgSafety, sanitizeImage, ImageRejectedError, +} = require('../src/dashboard/imageSanitizer'); +const { scanBuffer, clamavConfigFromEnv, pingClamd, ClamavUnavailableError } = require('../src/dashboard/clamav'); +const { setJsoncString } = require('../src/dashboard/jsoncPatch'); +const { registerPanelAssetRoutes, uploadLimitFromEnv, removeCustomFiles, CUSTOM_FILE_RE } = require('../src/dashboard/panelAssets'); +const { hasPermission } = require('../src/dashboard/permissions'); +const { resolvePanelAsset } = require('../src/utils/assetResolver'); + +const BOUNDS = { maxWidth: 1024, maxHeight: 1024 }; +const solid = (width, height, background = '#3366cc', channels = 3) => + sharp({ create: { width, height, channels, background } }); + +const SVG_OK = Buffer.from( + '\n' + + '\n' + + '' + + '' + + '\n', +); + +// ── Type detection ────────────────────────────────────────────────────────── + +test('every allowed type is detected from its content', async () => { + const img = solid(16, 16); + assert.equal(detectImageType(await img.clone().png().toBuffer()), 'png'); + assert.equal(detectImageType(await img.clone().jpeg().toBuffer()), 'jpeg'); + assert.equal(detectImageType(await img.clone().gif().toBuffer()), 'gif'); + assert.equal(detectImageType(await img.clone().webp().toBuffer()), 'webp'); + assert.equal(detectImageType(SVG_OK), 'svg'); +}); + +test('a renamed non-image is not an image, whatever its name says', () => { + // What a "logo.png" that is really a script or an archive looks like. + assert.equal(detectImageType(Buffer.from('#!/bin/sh\nrm -rf /\n')), null); + assert.equal(detectImageType(Buffer.from('PK\x03\x04 zip archive')), null); + assert.equal(detectImageType(Buffer.from('hi')), null); + assert.equal(detectImageType(Buffer.from('RIFF\0\0\0\0AVI LIST')), null); // RIFF but not WebP + assert.equal(detectImageType(Buffer.from([0x89, 0x50, 0x4e, 0x47])), null); // truncated PNG magic + assert.equal(detectImageType(Buffer.alloc(0)), null); + assert.equal(detectImageType('not a buffer'), null); + // Not UTF-8 → not an SVG either. + assert.equal(detectImageType(Buffer.from([0x3c, 0x73, 0x76, 0x67, 0xff, 0xfe, 0x3e])), null); +}); + +test('a clean SVG passes the strict check', () => { + assert.deepEqual(checkSvgSafety(SVG_OK), { ok: true }); +}); + +test('SVGs with script, handlers, external references or entities are refused', () => { + const svg = (inner, head = '') => Buffer.from(`${head}${inner}`); + const bad = [ + svg(''), + svg(''), + svg(''), + svg(''), + svg('