From 46c085955b6ff3c8366518354386cfe6350d4c15 Mon Sep 17 00:00:00 2001 From: "Kkermit." <132657029+Kkkermit@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:29:54 +0000 Subject: [PATCH 1/7] feat: Let hosts make the bot their own with testify.config.json, and greet whoever adds it --- .env.development.example | 8 + .env.example | 8 + .gitignore | 3 + AGENTS.md | 54 +++++ README.md | 19 ++ dashboard/src/features/docs/docs.pages.ts | 10 + dashboard/src/features/help/HelpPage.tsx | 12 +- .../src/features/legal/LegalPage.test.tsx | 2 +- dashboard/src/features/legal/LegalPage.tsx | 34 +++ dashboard/src/features/legal/legal.content.ts | 11 +- dashboard/src/features/site/LandingPage.tsx | 4 +- .../src/features/site/components/Composer.tsx | 6 +- dashboard/src/i18n/locales/de.json | 8 +- dashboard/src/i18n/locales/en.json | 8 +- dashboard/src/i18n/locales/es.json | 8 +- dashboard/src/i18n/locales/fr.json | 8 +- dashboard/src/i18n/locales/it.json | 8 +- dashboard/src/i18n/locales/ja.json | 8 +- dashboard/src/i18n/locales/nl.json | 8 +- dashboard/src/i18n/locales/ru.json | 8 +- dashboard/src/test/fixtures/site.ts | 2 + docker-compose.yml | 9 +- docs/README.md | 1 + docs/customising.md | 138 +++++++++++++ docs/hosting.md | 8 +- package.json | 1 + scripts/generateConfigSchema.ts | 25 +++ scripts/setupEnv.ts | 113 ++++++++++ shared/src/api.ts | 3 +- shared/src/settings.ts | 11 +- shared/src/site.ts | 18 ++ src/api/routes/commandRunner.ts | 7 +- src/api/routes/commands.ts | 4 +- src/api/routes/settings.ts | 6 +- src/api/routes/site.ts | 6 +- src/api/routes/support.ts | 10 +- src/api/server.ts | 4 +- src/buttons/help.ts | 4 +- src/buttons/prefixSetup.ts | 9 +- src/buttons/support.ts | 7 +- src/commands/info/ask.command.ts | 9 +- src/commands/info/bot.command.ts | 9 +- src/commands/info/help.command.ts | 4 +- src/config/constants.ts | 2 +- src/config/env.ts | 3 + src/config/instance.ts | 181 ++++++++++++++++ src/config/theme.ts | 4 - src/database/models/prefix.schema.ts | 6 +- src/database/repositories/prefixRepository.ts | 13 +- src/events/create/guildCreate.event.ts | 5 +- src/events/message/mentionReply.event.ts | 10 +- src/events/message/prefixCommands.event.ts | 6 +- src/events/ready/ready.event.ts | 5 +- src/index.ts | 5 +- src/lib/bot/banner.util.ts | 4 +- src/lib/bot/botIdentity.util.ts | 10 +- src/lib/bot/index.ts | 2 + src/lib/bot/inviterGreeting.util.ts | 154 ++++++++++++++ src/lib/bot/projectLinks.util.ts | 11 + src/lib/bot/runtime.util.ts | 4 +- src/lib/bot/startup.util.ts | 22 ++ src/lib/info/helpPages.util.ts | 5 +- src/lib/settings/prefixPanel.util.ts | 8 +- src/lib/support/supportDesk.util.ts | 4 +- src/lib/support/supportFacts.util.ts | 18 +- testify.config.example.json | 9 + testify.config.schema.json | 44 ++++ tests/api/site.test.ts | 16 +- tests/config/instance.test.ts | 144 +++++++++++++ tests/database/guildRepository.test.ts | 2 +- tests/lib/bot/botIdentity.test.ts | 16 +- tests/lib/bot/inviterGreeting.test.ts | 194 ++++++++++++++++++ tests/lib/settingsScreens.test.ts | 2 +- tests/scripts/setupEnv.test.ts | 46 ++++- tests/setup.ts | 1 + 75 files changed, 1476 insertions(+), 123 deletions(-) create mode 100644 docs/customising.md create mode 100644 scripts/generateConfigSchema.ts create mode 100644 src/config/instance.ts create mode 100644 src/lib/bot/inviterGreeting.util.ts create mode 100644 src/lib/bot/projectLinks.util.ts create mode 100644 testify.config.example.json create mode 100644 testify.config.schema.json create mode 100644 tests/config/instance.test.ts create mode 100644 tests/lib/bot/inviterGreeting.test.ts diff --git a/.env.development.example b/.env.development.example index 22795063d..197b1797d 100644 --- a/.env.development.example +++ b/.env.development.example @@ -3,6 +3,9 @@ # # The point of the split is that `npm run dev` must never start the production # bot. Use a SECOND Discord application here, not the one your users invite. +# +# Links, who runs it and the default prefix go in `testify.config.development.json` +# beside this file, which `npm run dev` reads. See docs/customising.md. # Your development bot's token — a different application from production. DISCORD_TOKEN= @@ -113,5 +116,10 @@ SUPPORT_AI_API_KEY= # Defaults to claude-opus-5. Any Claude model that supports structured outputs works. SUPPORT_AI_MODEL= +# Where `testify.config.json` is, when it is not beside this file. Blank looks beside it, which is what you want +# almost always; docker-compose.yml sets this itself. The file holds your links, who runs your copy and the +# default prefix — see docs/customising.md. +TESTIFY_CONFIG= + # NODE_ENV is deliberately not here. `npm run dev` sets it with cross-env, which is what makes the bot read # `.env.development` instead of `.env` — setting it in a file would fight that and could start the wrong bot. diff --git a/.env.example b/.env.example index 149a151aa..486b48c16 100644 --- a/.env.example +++ b/.env.example @@ -3,6 +3,9 @@ # # For a separate development bot, copy `.env.development.example` to # `.env.development` instead — `npm run dev` reads that one. +# +# Your links, who runs your copy and the default prefix are not here: they go in +# `testify.config.json` beside this file. See docs/customising.md. # Discord Developer Portal → Bot → Token. # MUST be a different bot from your development one. @@ -118,5 +121,10 @@ SUPPORT_AI_API_KEY= # Defaults to claude-opus-5. Any Claude model that supports structured outputs works. SUPPORT_AI_MODEL= +# Where `testify.config.json` is, when it is not beside this file. Blank looks beside it, which is what you want +# almost always; docker-compose.yml sets this itself. The file holds your links, who runs your copy and the +# default prefix — see docs/customising.md. +TESTIFY_CONFIG= + # NODE_ENV is deliberately not here. `npm run dev` sets it with cross-env, which is what makes the bot read # `.env.development` instead of `.env` — setting it in a file would fight that and could start the wrong bot. diff --git a/.gitignore b/.gitignore index 1d4687700..bce1a005f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,9 @@ coverage/ .env.* !.env.example !.env.development.example +# Per copy, like .env; a fork that wants its own committed removes these two lines. +testify.config.json +testify.config.development.json # Logs logs/ diff --git a/AGENTS.md b/AGENTS.md index 496f87186..f4fe2e82b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -832,6 +832,41 @@ IDs) and its default. Adding a variable: add it to the zod schema, to **both** `.env.example` and `.env.development.example` with a comment explaining it, and to `scripts/setupEnv.ts` if it should be prompted for. +### What makes a copy someone's own is `testify.config.json`, not code and not `.env` + +`.env` holds secrets and switches. Everything else that differs between copies and that a reader sees — the +repository the Source code buttons open, the support server, who `/bot info` names, who runs the copy, the default +prefix and whether the bot greets whoever adds it — is `testify.config.json`, read by `src/config/instance.ts`. +[`docs/customising.md`](docs/customising.md) is the reader's guide to it. Six things about it are load-bearing: + +- **Every key is optional and the defaults are the original's** (`INSTANCE_DEFAULTS`), so a copy with no file behaves + as it always did. It sits beside `.env` and is found the same way, `testify.config.development.json` under + `npm run dev`, and it is gitignored like `.env`; a fork that wants it committed removes those two lines. +- **It is read once, in `main()` straight after `loadEnv`, and fails start-up with a list**, unknown keys included + (`z.strictObject`), so a misspelt setting never silently does nothing. `explainStartupFailure` turns an + `InstanceError` into the same kind of box as a bad `.env`. Everything else reads `instanceConfig()`, which is the + defaults until then — what the tests and the scripts see. **Never read it at import time:** `index.ts` imports + every module before `main()` runs, so a module-level constant built from it holds the defaults for ever. `FACTS`'s + `prefix.default` is a getter for exactly that reason. +- **Docker mounts the folder, not the file.** `docker-compose.yml` mounts the folder it runs from at `/app/instance`, + read-only, and sets `TESTIFY_CONFIG` to the file there. Mounting a file that does not exist makes Docker create a + folder in its place, and `instanceFile` reads a folder as no file, so the defaults apply either way. +- **The links live nowhere else.** `theme.ts` no longer holds `author`, `repository` or `supportServer`, and + `tests/config/instance.test.ts` fails on the original's repository, its support invite or `DEFAULT_PREFIX` written + anywhere in `src` but `instance.ts`. `projectLinkButtons` draws Source code and Support, leaving Support out when the + host set `supportServer` to `null`, so nobody is sent to somebody else's. +- **`testify.config.schema.json` is generated** by `npm run config:schema` from the same zod schema, so an editor + completes and checks the file as it is typed; the suite fails when the two drift. The setup wizard asks its + questions with the schema's own rules (`instanceFields`) and writes only what was answered. +- **The operator is shown, never assumed.** With `operator` set, the privacy notice and the terms open with a card + naming them; `contactHref` in `@testify/shared` turns the contact into a link only for an email address or an + `https` page, which is also all the schema accepts. + +**A server's prefix is stored only when it is not the default.** `prefix.schema.ts` has no default, and `setPrefix` +unsets the field when it is given the default, so changing `defaultPrefix` reaches every server that never chose one. +A record written before this kept `t?` even for a server that only switched prefix commands off; it keeps that until +the prefix panel's Reset, and the guide says so. + --- ## 15. Logging @@ -2261,6 +2296,25 @@ under it, switching each feature off removes exactly its parts and nothing else, when something creates it, and only `/giveaway` and its route did, so a giveaway running across a restart never ended until somebody touched one. The `giveaways` job creates it five seconds after start-up. +### Whoever adds the bot gets one message, and nothing about it can fail the join + +`guildCreate` runs `greetInviter` beside the log post, and neither waits on the other. Four things about it are +load-bearing: + +- **The adder is read, never guessed, whichever way they added it.** An invite link, the Add App button on the bot's + profile and the App Directory all write the same `BotAdd` audit entry, so `findInviter` reads that first, asking once + more after `AUDIT_RETRY_MS` because Discord writes it a moment after the join arrives; `pickBotAdd` takes only the + newest entry for this bot that is under ten minutes old, since a bot added before has older ones. Without View Audit + Log it reads the bot's own integration, whose `user` is the adder, and without Manage Server either it writes to the + owner. The entry can carry a partial user, so the person written to is fetched whole. +- **Closed direct messages are the person's choice.** `CannotSendMessagesToThisUser` is a `debug` line and anything + else a `warn` saying the bot joined normally; nothing is thrown into the event. +- **Bots, blacklisted accounts and a host who set `greetInviter: false` get nothing.** Nothing about the greeting is + stored, and the privacy notice says so (`legal.messagesP6`). +- **The message is built by `inviterGreeting`, a pure function**: `/help` and the server's prefix, the dashboard's + setup checklist when the dashboard is on and every feature's setup command when it is not, `/prefix`, and the + project's links from `projectLinkButtons`. + ### Global by design The blacklist, the user profile, reminders and the notifications' read state are intentionally not guild-scoped. See diff --git a/README.md b/README.md index 7c707e265..433bff5c0 100644 --- a/README.md +++ b/README.md @@ -546,6 +546,25 @@ Each feature is declared once, in [`shared/src/botFeatures.ts`](shared/src/botFe button, event, job, route, screen and help article it owns. The test suite checks that declaration against the bot, so a new part that belongs to a feature has to be listed there. +## 🎨 Making it your own + +The bot takes its name and picture from your Discord application, so renaming it is done in the Developer Portal. +Your links, who runs your copy and the default prefix go in `testify.config.json`, beside `.env` — copy +`testify.config.example.json`, or answer "Make it your own?" at the end of `npm run setup`: + +```json +{ + "$schema": "./testify.config.schema.json", + "repository": "https://github.com/you/your-fork", + "supportServer": null, + "operator": { "name": "Your name", "contact": "privacy@example.com" }, + "defaultPrefix": "!" +} +``` + +Every key is optional, and nothing in it is secret. [Make it your own](docs/customising.md) covers each setting, +what takes code, the message the bot sends whoever adds it to a server, and how to keep a fork up to date. + ## 🛠️ Adding your own command Create one file. The loader finds it, `/help` lists it, and it works as a slash **and** a prefix command diff --git a/dashboard/src/features/docs/docs.pages.ts b/dashboard/src/features/docs/docs.pages.ts index 01897d51d..534064aee 100644 --- a/dashboard/src/features/docs/docs.pages.ts +++ b/dashboard/src/features/docs/docs.pages.ts @@ -5,6 +5,7 @@ export const DOC_FILES = [ "README.md", "AGENTS.md", "docs/hosting.md", + "docs/customising.md", "docs/commands.md", "docs/contributing.md", "docs/security.md", @@ -22,6 +23,7 @@ export const LOADERS: Record Promise> = { "README.md": async () => (await import("@repo/README.md?raw")).default, "AGENTS.md": async () => (await import("@repo/AGENTS.md?raw")).default, "docs/hosting.md": async () => (await import("@repo/docs/hosting.md?raw")).default, + "docs/customising.md": async () => (await import("@repo/docs/customising.md?raw")).default, "docs/commands.md": async () => (await import("@repo/docs/commands.md?raw")).default, "docs/contributing.md": async () => (await import("@repo/docs/contributing.md?raw")).default, "docs/security.md": async () => (await import("@repo/docs/security.md?raw")).default, @@ -109,6 +111,14 @@ export const DOC_PAGES: readonly DocPage[] = [ summaryKey: "docs.pages.featuresSummary", sources: [{ file: "README.md", sections: ["Switching features off"] }], }, + { + slug: "make-it-yours", + group: "run", + kind: "markdown", + titleKey: "docs.pages.customising", + summaryKey: "docs.pages.customisingSummary", + sources: [{ file: "docs/customising.md" }], + }, { slug: "docker", group: "run", diff --git a/dashboard/src/features/help/HelpPage.tsx b/dashboard/src/features/help/HelpPage.tsx index 91235fcb6..39d48a838 100644 --- a/dashboard/src/features/help/HelpPage.tsx +++ b/dashboard/src/features/help/HelpPage.tsx @@ -102,11 +102,13 @@ export function HelpPage(): React.JSX.Element {
{bot.data !== undefined && ( <> - - + {bot.data.supportUrl !== null && ( + + + )}
- +
diff --git a/dashboard/src/features/site/components/Composer.tsx b/dashboard/src/features/site/components/Composer.tsx index 73930f4b8..e4cefc9d7 100644 --- a/dashboard/src/features/site/components/Composer.tsx +++ b/dashboard/src/features/site/components/Composer.tsx @@ -1,4 +1,4 @@ -import { type BotFeature, commandIsOff, DEFAULT_PREFIX } from "@testify/shared"; +import { type BotFeature, commandIsOff } from "@testify/shared"; import { Hash, PlusCircle } from "lucide-react"; import { useEffect, useMemo, useState } from "react"; import { useTranslation } from "react-i18next"; @@ -18,9 +18,11 @@ import { cn } from "@/lib/cn"; export function Composer({ palette, featuresOff, + prefix, }: { palette: readonly PaletteCommand[]; featuresOff: ReadonlySet; + prefix: string; }): React.JSX.Element | null { const { t } = useTranslation(); const reduced = usePrefersReducedMotion(); @@ -80,7 +82,7 @@ export function Composer({ {t("landing.composer.example", { command: slashLine(scene) })} {t("landing.composer.twin")} - {prefixLine(scene, DEFAULT_PREFIX)} + {prefixLine(scene, prefix)} diff --git a/dashboard/src/i18n/locales/de.json b/dashboard/src/i18n/locales/de.json index 70afa8941..6bc5321bd 100644 --- a/dashboard/src/i18n/locales/de.json +++ b/dashboard/src/i18n/locales/de.json @@ -2009,6 +2009,9 @@ "termsTitle": "Nutzungsbedingungen", "termsSummary": "Die Regeln für die Nutzung von {{bot}} und diesem Dashboard, und was passiert, wenn sie gebrochen werden. Bitte lies sie, bevor du eines davon nutzt.", "whoRuns": "Wer das betreibt", + "operatorTitle": "Wer diese Kopie betreibt", + "operatorName": "Betrieben von", + "operatorContact": "Kontakt", "whoRunsP1": "{{bot}} wird selbst gehostet. Wer diese Instanz aufgesetzt hat — die Betreiberin — entscheidet, was sie tut, was sie speichert und wer sie erreicht. Verantwortlich ist sie, nicht die Autoren des Projekts.", "whoRunsP2": "Die Software wird wie besehen bereitgestellt, ohne jede Gewährleistung. Niemand verspricht Verfügbarkeit, Richtigkeit oder Fehlerfreiheit.", "whoRunsP3": "Der Code ist unter der MIT-Lizenz veröffentlicht. Alle dürfen ihn nutzen, ändern, weitergeben und verkaufen, solange der Urheberrechtshinweis mit dem ursprünglichen Autor und die Lizenz selbst in jeder Kopie erhalten bleiben.", @@ -2208,7 +2211,8 @@ "retentionL20": "Einladungs-Tracking: 365 Tage nach jedem Beitritt, dann automatisch gelöscht, und alles, wenn der Bot vom Server entfernt wird.", "retentionL21": "Dashboard-Zugang: bis ein Admin ihn entzieht, du den Server verlässt oder der Bot vom Server entfernt wird.", "retentionL22": "Log-Zeilen: die letzten 6 Starts des Bots, höchstens 2.000 Zeilen je Start. Der nächste Start löscht den ältesten, und die Betreiberin kann sie früher löschen.", - "messagesP5": "Das Melden einer Nachricht ist das Letzte. Wenn du mit Rechtsklick auf eine Nachricht „Report message“ wählst, postet {{bot}} sie im Modmail-Kanal dieses Servers für dessen Team: den Text der Nachricht, wer sie geschrieben hat, wer sie gemeldet hat und was du dazu gesagt hast. Dieser Beitrag liegt in Discord, nicht in der Datenbank des Bots. Der Bot merkt sich eine Stunde lang, nur im Arbeitsspeicher, welche Nachrichten du gemeldet hast, damit dieselbe nicht zweimal gemeldet wird; ein Neustart vergisst es." + "messagesP5": "Das Melden einer Nachricht ist das Letzte. Wenn du mit Rechtsklick auf eine Nachricht „Report message“ wählst, postet {{bot}} sie im Modmail-Kanal dieses Servers für dessen Team: den Text der Nachricht, wer sie geschrieben hat, wer sie gemeldet hat und was du dazu gesagt hast. Dieser Beitrag liegt in Discord, nicht in der Datenbank des Bots. Der Bot merkt sich eine Stunde lang, nur im Arbeitsspeicher, welche Nachrichten du gemeldet hast, damit dieselbe nicht zweimal gemeldet wird; ein Neustart vergisst es.", + "messagesP6": "Wenn {{bot}} einem Server hinzugefügt wird, schickt es außerdem eine Direktnachricht: einen Hinweis für den Einstieg an die Person, die es hinzugefügt hat. Um sie zu finden, liest der Bot den Eintrag zu seiner eigenen Aufnahme im Audit-Log des Servers, sonst seinen eigenen Eintrag bei den Integrationen des Servers, und schreibt der Person, der der Server gehört, wenn keins von beidem es verrät. Davon wird nichts gespeichert. Wer Direktnachrichten geschlossen hat, bekommt nichts, und die Betreiberin kann die Nachricht abschalten." }, "problem": { "automodMentionLimit": "Wähle, wie viele Erwähnungen erlaubt sind.", @@ -2636,6 +2640,8 @@ "featuresSummary": "Betreibe den Bot ohne Musik, Casino oder anderes, das du nicht brauchst.", "docker": "Docker", "dockerSummary": "Bot und Datenbank mit Docker Compose, und wo sie sonst laufen können.", + "customising": "Zu deiner eigenen machen", + "customisingSummary": "Deine Links, wer sie betreibt und das Standardpräfix in einer Datei neben .env, und wie ein Fork aktuell bleibt.", "dashboard": "Website und Dashboard", "dashboardSummary": "Diese Website, das Dashboard hinter der Anmeldung, wer was sieht und beides ins Internet stellen.", "scripts": "Skripte", diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json index 50360342a..a2ed3b133 100644 --- a/dashboard/src/i18n/locales/en.json +++ b/dashboard/src/i18n/locales/en.json @@ -2009,6 +2009,9 @@ "termsTitle": "Terms of use", "termsSummary": "The rules for using {{bot}} and this dashboard, and what happens when they are broken. Please read them before you use either.", "whoRuns": "Who runs this", + "operatorTitle": "Who runs this copy", + "operatorName": "Run by", + "operatorContact": "Contact", "whoRunsP1": "{{bot}} is self-hosted. Whoever deployed this instance — the operator — decides what it does, what it stores and who can reach it. They are responsible for it, not the project’s authors.", "whoRunsP2": "The software is provided as-is, without warranty of any kind. Nobody promises it will be available, correct, or free of defects.", "whoRunsP3": "The code is published under the MIT licence. Anyone may use, change, share and sell it, as long as the copyright notice naming its original author and the licence itself are kept in every copy.", @@ -2208,7 +2211,8 @@ "retentionL20": "Invite tracking: 365 days after each join, then deleted automatically, and all of it when the bot is removed from the server.", "retentionL21": "Dashboard access: until an admin takes it away, you leave the server, or the bot is removed from it.", "retentionL22": "Log lines: the bot’s last 6 starts, at most 2,000 lines each. The next start deletes the oldest, and the operator can delete them sooner.", - "messagesP5": "Reporting a message is the last. When you right-click a message and choose Report message, {{bot}} posts it in that server’s mod mail channel for its staff: the message’s text, who wrote it, who reported it and what you said about it. That post lives in Discord, not in the bot’s database. The bot remembers which messages you reported for an hour, in memory only, so the same one cannot be reported twice; a restart forgets it." + "messagesP5": "Reporting a message is the last. When you right-click a message and choose Report message, {{bot}} posts it in that server’s mod mail channel for its staff: the message’s text, who wrote it, who reported it and what you said about it. That post lives in Discord, not in the bot’s database. The bot remembers which messages you reported for an hour, in memory only, so the same one cannot be reported twice; a restart forgets it.", + "messagesP6": "Adding {{bot}} to a server sends one direct message too: a note on getting started, to whoever added it. To find them, the bot reads the entry for its own arrival in that server’s audit log, or failing that its own entry in the server’s integrations, and writes to the server’s owner if neither says. It keeps none of this. Nothing is sent to somebody whose direct messages are closed, and the operator can turn the message off." }, "problem": { "automodMentionLimit": "Choose how many mentions to allow.", @@ -2636,6 +2640,8 @@ "featuresSummary": "Run the bot without music, the casino or anything else you do not want.", "docker": "Docker", "dockerSummary": "The bot and its database with Docker Compose, and where else it can run.", + "customising": "Make it your own", + "customisingSummary": "Your links, who runs it and the default prefix, in one file beside .env, and how to keep a fork up to date.", "dashboard": "The website and dashboard", "dashboardSummary": "This site, the dashboard behind its sign-in, who can see what, and putting them on the internet.", "scripts": "Scripts", diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json index c5931125b..b5631e16f 100644 --- a/dashboard/src/i18n/locales/es.json +++ b/dashboard/src/i18n/locales/es.json @@ -2075,6 +2075,9 @@ "termsTitle": "Condiciones de uso", "termsSummary": "Las reglas para usar {{bot}} y este panel, y qué pasa cuando se incumplen. Léelas antes de usar cualquiera de los dos.", "whoRuns": "Quién lo gestiona", + "operatorTitle": "Quién gestiona esta copia", + "operatorName": "Gestionada por", + "operatorContact": "Contacto", "whoRunsP1": "{{bot}} es autoalojado. Quien haya desplegado esta instancia —el operador— decide qué hace, qué almacena y quién puede acceder. La responsabilidad es suya, no de los autores del proyecto.", "whoRunsP2": "El software se entrega tal cual, sin garantía de ningún tipo. Nadie promete que esté disponible, que sea correcto ni que carezca de defectos.", "whoRunsP3": "El código se publica bajo la licencia MIT. Cualquiera puede usarlo, modificarlo, compartirlo y venderlo, siempre que se conserven en cada copia el aviso de copyright que nombra a su autor original y la propia licencia.", @@ -2274,7 +2277,8 @@ "retentionL20": "Seguimiento de invitaciones: 365 días después de cada entrada, y luego se borra automáticamente; todo se borra cuando el bot se quita del servidor.", "retentionL21": "Acceso al panel: hasta que un administrador te lo quite, salgas del servidor o el bot sea retirado de él.", "retentionL22": "Líneas del registro: los últimos 6 arranques del bot, como mucho 2000 líneas cada uno. El siguiente arranque borra el más antiguo, y el operador puede borrarlas antes.", - "messagesP5": "Denunciar un mensaje es lo último. Cuando haces clic derecho en un mensaje y eliges Report message, {{bot}} lo publica en el canal de correo al equipo de ese servidor: el texto del mensaje, quién lo escribió, quién lo denunció y lo que dijiste sobre él. Esa publicación vive en Discord, no en la base de datos del bot. El bot recuerda durante una hora, solo en memoria, qué mensajes denunciaste, para que el mismo no se denuncie dos veces; un reinicio lo olvida." + "messagesP5": "Denunciar un mensaje es lo último. Cuando haces clic derecho en un mensaje y eliges Report message, {{bot}} lo publica en el canal de correo al equipo de ese servidor: el texto del mensaje, quién lo escribió, quién lo denunció y lo que dijiste sobre él. Esa publicación vive en Discord, no en la base de datos del bot. El bot recuerda durante una hora, solo en memoria, qué mensajes denunciaste, para que el mismo no se denuncie dos veces; un reinicio lo olvida.", + "messagesP6": "Al añadir {{bot}} a un servidor también se envía un mensaje directo: una nota para empezar, a quien lo añadió. Para saber quién fue, el bot lee la entrada de su propia llegada en el registro de auditoría del servidor o, si no, su propia entrada en las integraciones del servidor, y escribe al propietario del servidor si ninguna de las dos lo indica. No guarda nada de esto. A quien tenga cerrados los mensajes directos no se le envía nada, y el operador puede desactivar el mensaje." }, "problem": { "automodMentionLimit": "Elige cuántas menciones permitir.", @@ -2710,6 +2714,8 @@ "featuresSummary": "Ejecuta el bot sin música, sin casino o sin cualquier otra cosa que no quieras.", "docker": "Docker", "dockerSummary": "El bot y su base de datos con Docker Compose, y dónde más puede ejecutarse.", + "customising": "Hazlo tuyo", + "customisingSummary": "Tus enlaces, quién lo gestiona y el prefijo por defecto, en un archivo junto a .env, y cómo mantener un fork al día.", "dashboard": "El sitio web y el panel", "dashboardSummary": "Este sitio, el panel tras el inicio de sesión, quién ve qué y publicarlos en internet.", "scripts": "Scripts", diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json index a96275680..1ef776ab2 100644 --- a/dashboard/src/i18n/locales/fr.json +++ b/dashboard/src/i18n/locales/fr.json @@ -2075,6 +2075,9 @@ "termsTitle": "Conditions d’utilisation", "termsSummary": "Les règles d’utilisation de {{bot}} et de ce tableau de bord, et ce qui se passe quand elles ne sont pas respectées. Lisez-les avant d’utiliser l’un ou l’autre.", "whoRuns": "Qui gère ceci", + "operatorTitle": "Qui gère cette copie", + "operatorName": "Gérée par", + "operatorContact": "Contact", "whoRunsP1": "{{bot}} est auto-hébergé. Qui a déployé cette instance — l’exploitant — décide de ce qu’elle fait, de ce qu’elle stocke et de qui peut l’atteindre. La responsabilité lui incombe, pas aux auteurs du projet.", "whoRunsP2": "Le logiciel est fourni tel quel, sans garantie d’aucune sorte. Personne ne promet qu’il sera disponible, correct ou exempt de défauts.", "whoRunsP3": "Le code est publié sous licence MIT. Chacun peut l’utiliser, le modifier, le partager et le vendre, à condition de conserver dans chaque copie la mention de droit d’auteur qui nomme son auteur d’origine, ainsi que la licence elle-même.", @@ -2274,7 +2277,8 @@ "retentionL20": "Suivi des invitations : 365 jours après chaque arrivée, puis supprimé automatiquement, et entièrement quand le bot est retiré du serveur.", "retentionL21": "Accès au tableau de bord : jusqu’à ce qu’un administrateur le retire, que vous quittiez le serveur, ou que le bot en soit retiré.", "retentionL22": "Lignes du journal : les 6 derniers démarrages du bot, 2 000 lignes au plus chacun. Le prochain démarrage supprime le plus ancien, et l’exploitant peut les supprimer plus tôt.", - "messagesP5": "Signaler un message est la dernière. Quand vous faites un clic droit sur un message et choisissez Report message, {{bot}} le publie dans le salon de messagerie modération de ce serveur pour son équipe : le texte du message, qui l’a écrit, qui l’a signalé et ce que vous en avez dit. Cette publication est dans Discord, pas dans la base de données du bot. Le bot retient pendant une heure, en mémoire seulement, les messages que vous avez signalés, pour qu’un même message ne soit pas signalé deux fois ; un redémarrage l’oublie." + "messagesP5": "Signaler un message est la dernière. Quand vous faites un clic droit sur un message et choisissez Report message, {{bot}} le publie dans le salon de messagerie modération de ce serveur pour son équipe : le texte du message, qui l’a écrit, qui l’a signalé et ce que vous en avez dit. Cette publication est dans Discord, pas dans la base de données du bot. Le bot retient pendant une heure, en mémoire seulement, les messages que vous avez signalés, pour qu’un même message ne soit pas signalé deux fois ; un redémarrage l’oublie.", + "messagesP6": "Ajouter {{bot}} à un serveur envoie aussi un message privé : une note pour bien démarrer, à la personne qui l’a ajouté. Pour la trouver, le bot lit l’entrée de sa propre arrivée dans le journal d’audit du serveur, ou à défaut sa propre entrée dans les intégrations du serveur, et écrit au propriétaire du serveur si aucune des deux ne le dit. Il n’en garde rien. Rien n’est envoyé à quelqu’un dont les messages privés sont fermés, et l’exploitant peut désactiver ce message." }, "problem": { "automodMentionLimit": "Choisis le nombre de mentions autorisées.", @@ -2710,6 +2714,8 @@ "featuresSummary": "Faites tourner le bot sans musique, sans casino ou sans tout ce dont vous ne voulez pas.", "docker": "Docker", "dockerSummary": "Le bot et sa base de données avec Docker Compose, et où il peut tourner ailleurs.", + "customising": "À votre image", + "customisingSummary": "Vos liens, qui l’exploite et le préfixe par défaut, dans un fichier à côté de .env, et comment garder un fork à jour.", "dashboard": "Le site et le tableau de bord", "dashboardSummary": "Ce site, le tableau de bord derrière la connexion, qui voit quoi, et les mettre sur Internet.", "scripts": "Scripts", diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json index b388ae077..53df4c8cd 100644 --- a/dashboard/src/i18n/locales/it.json +++ b/dashboard/src/i18n/locales/it.json @@ -2075,6 +2075,9 @@ "termsTitle": "Termini d’uso", "termsSummary": "Le regole per usare {{bot}} e questa dashboard, e cosa succede quando vengono violate. Leggile prima di usare l’uno o l’altra.", "whoRuns": "Chi lo gestisce", + "operatorTitle": "Chi gestisce questa copia", + "operatorName": "Gestita da", + "operatorContact": "Contatto", "whoRunsP1": "{{bot}} è self-hosted. Chi ha messo in piedi questa istanza — l’operatore — decide cosa fa, cosa conserva e chi può raggiungerla. La responsabilità è sua, non degli autori del progetto.", "whoRunsP2": "Il software è fornito così com’è, senza garanzie di alcun tipo. Nessuno promette che sarà disponibile, corretto o privo di difetti.", "whoRunsP3": "Il codice è pubblicato con licenza MIT. Chiunque può usarlo, modificarlo, condividerlo e venderlo, purché in ogni copia restino l’avviso di copyright che nomina l’autore originale e la licenza stessa.", @@ -2274,7 +2277,8 @@ "retentionL20": "Tracciamento degli inviti: 365 giorni dopo ogni ingresso, poi eliminato automaticamente, e tutto quando il bot viene rimosso dal server.", "retentionL21": "Accesso al pannello: finché un amministratore non lo toglie, non lasci il server, o il bot non viene rimosso dal server.", "retentionL22": "Righe di log: gli ultimi 6 avvii del bot, al massimo 2.000 righe ciascuno. Il prossimo avvio elimina il più vecchio, e l’operatore può eliminarle prima.", - "messagesP5": "Segnalare un messaggio è l’ultima. Quando fai clic destro su un messaggio e scegli Report message, {{bot}} lo pubblica nel canale della posta allo staff di quel server: il testo del messaggio, chi l’ha scritto, chi l’ha segnalato e ciò che hai detto. Quella pubblicazione resta su Discord, non nel database del bot. Il bot ricorda per un’ora, solo in memoria, quali messaggi hai segnalato, perché lo stesso non venga segnalato due volte; un riavvio lo dimentica." + "messagesP5": "Segnalare un messaggio è l’ultima. Quando fai clic destro su un messaggio e scegli Report message, {{bot}} lo pubblica nel canale della posta allo staff di quel server: il testo del messaggio, chi l’ha scritto, chi l’ha segnalato e ciò che hai detto. Quella pubblicazione resta su Discord, non nel database del bot. Il bot ricorda per un’ora, solo in memoria, quali messaggi hai segnalato, perché lo stesso non venga segnalato due volte; un riavvio lo dimentica.", + "messagesP6": "Aggiungere {{bot}} a un server invia anche un messaggio diretto: una nota per iniziare, a chi l’ha aggiunto. Per saperlo, il bot legge la voce del proprio arrivo nel registro di controllo del server o, in mancanza, la propria voce tra le integrazioni del server, e scrive al proprietario del server se nessuna delle due lo indica. Non ne conserva nulla. Non viene inviato nulla a chi ha i messaggi diretti chiusi, e l’operatore può disattivare il messaggio." }, "problem": { "automodMentionLimit": "Scegli quante menzioni consentire.", @@ -2710,6 +2714,8 @@ "featuresSummary": "Esegui il bot senza musica, senza casinò o senza qualsiasi altra cosa che non vuoi.", "docker": "Docker", "dockerSummary": "Il bot e il suo database con Docker Compose, e dove altro può girare.", + "customising": "Rendilo tuo", + "customisingSummary": "I tuoi link, chi lo gestisce e il prefisso predefinito, in un file accanto a .env, e come tenere aggiornato un fork.", "dashboard": "Il sito e la dashboard", "dashboardSummary": "Questo sito, la dashboard dietro l’accesso, chi vede cosa e metterli su internet.", "scripts": "Script", diff --git a/dashboard/src/i18n/locales/ja.json b/dashboard/src/i18n/locales/ja.json index 33c2df4bb..b68c3c121 100644 --- a/dashboard/src/i18n/locales/ja.json +++ b/dashboard/src/i18n/locales/ja.json @@ -1943,6 +1943,9 @@ "termsTitle": "利用規約", "termsSummary": "{{bot}} とこのダッシュボードを使うためのルールと、違反した場合の対応です。どちらかを使う前にお読みください。", "whoRuns": "運営者", + "operatorTitle": "このコピーの運営者", + "operatorName": "運営者", + "operatorContact": "連絡先", "whoRunsP1": "{{bot}} はセルフホスト型です。このインスタンスを導入した人(運営者)が、何をするか、何を保存するか、誰が使えるかを決めます。責任を負うのは運営者であり、プロジェクトの作者ではありません。", "whoRunsP2": "このソフトウェアは現状のまま提供され、いかなる保証もありません。利用できること、正しいこと、不具合がないことは誰も約束しません。", "whoRunsP3": "コードは MIT ライセンスで公開されています。誰でも使用・変更・共有・販売できますが、原作者を記した著作権表示とライセンス本文を、すべての複製に残す必要があります。", @@ -2142,7 +2145,8 @@ "retentionL20": "招待の追跡:各参加から 365 日後に自動的に削除し、ボットがサーバーから削除されるとすべて削除します。", "retentionL21": "ダッシュボードのアクセス:管理者が取り消すか、あなたがサーバーを抜けるか、ボットがサーバーから外されるまで。", "retentionL22": "ログ:ボットの直近 6 回の起動分、1 回につき最大 2,000 行。次に起動すると最も古いものが削除され、運営者はそれより早く削除できます。", - "messagesP5": "最後はメッセージの報告です。メッセージを右クリックして Report message を選ぶと、{{bot}} はそのサーバーのモッドメールチャンネルにスタッフ向けに投稿します。内容は、メッセージの本文、書いた人、報告した人、あなたが書いた理由です。この投稿は Discord に残り、ボットのデータベースには保存されません。同じメッセージが二度報告されないよう、ボットはあなたが報告したメッセージを 1 時間だけメモリ上で覚えています。再起動すると忘れます。" + "messagesP5": "最後はメッセージの報告です。メッセージを右クリックして Report message を選ぶと、{{bot}} はそのサーバーのモッドメールチャンネルにスタッフ向けに投稿します。内容は、メッセージの本文、書いた人、報告した人、あなたが書いた理由です。この投稿は Discord に残り、ボットのデータベースには保存されません。同じメッセージが二度報告されないよう、ボットはあなたが報告したメッセージを 1 時間だけメモリ上で覚えています。再起動すると忘れます。", + "messagesP6": "{{bot}}をサーバーに追加すると、追加した人に使い始めの案内をDMで1通送ります。誰が追加したかは、サーバーの監査ログにある自身の追加の記録、それがなければサーバーの連携にある自身の項目から読み取り、どちらにも記録がなければサーバーの所有者に送ります。これについては何も保存しません。DMを閉じている人には送られず、運営者はこのメッセージをオフにできます。" }, "problem": { "automodMentionLimit": "許可するメンション数を選んでください。", @@ -2562,6 +2566,8 @@ "featuresSummary": "音楽やカジノなど、使わない機能を外してボットを動かします。", "docker": "Docker", "dockerSummary": "Docker Compose でボットとデータベースを動かす方法と、その他の実行場所。", + "customising": "自分好みにする", + "customisingSummary": "リンク、運営者、既定のプレフィックスを .env の隣の1つのファイルで設定。フォークを最新に保つ方法も。", "dashboard": "ウェブサイトとダッシュボード", "dashboardSummary": "このサイト、ログインの先にあるダッシュボード、誰が何を見られるか、インターネットへの公開。", "scripts": "スクリプト", diff --git a/dashboard/src/i18n/locales/nl.json b/dashboard/src/i18n/locales/nl.json index cbffb7514..24b94900e 100644 --- a/dashboard/src/i18n/locales/nl.json +++ b/dashboard/src/i18n/locales/nl.json @@ -2009,6 +2009,9 @@ "termsTitle": "Gebruiksvoorwaarden", "termsSummary": "De regels voor het gebruik van {{bot}} en dit dashboard, en wat er gebeurt als ze worden overtreden. Lees ze voordat je een van beide gebruikt.", "whoRuns": "Wie dit draait", + "operatorTitle": "Wie deze kopie beheert", + "operatorName": "Beheerd door", + "operatorContact": "Contact", "whoRunsP1": "{{bot}} wordt zelf gehost. Wie deze instantie heeft opgezet — de beheerder — bepaalt wat hij doet, wat hij bewaart en wie hem kan bereiken. Die is ervoor verantwoordelijk, niet de makers van het project.", "whoRunsP2": "De software wordt geleverd zoals hij is, zonder enige garantie. Niemand belooft dat hij beschikbaar, correct of foutloos zal zijn.", "whoRunsP3": "De code is gepubliceerd onder de MIT-licentie. Iedereen mag hem gebruiken, wijzigen, delen en verkopen, zolang de copyrightvermelding met de oorspronkelijke maker en de licentie zelf in elke kopie blijven staan.", @@ -2208,7 +2211,8 @@ "retentionL20": "Uitnodigingen volgen: 365 dagen na elke binnenkomst, daarna automatisch verwijderd, en alles wanneer de bot van de server wordt verwijderd.", "retentionL21": "Toegang tot het dashboard: tot een beheerder die afneemt, je de server verlaat, of de bot uit de server wordt verwijderd.", "retentionL22": "Logregels: de laatste 6 starts van de bot, hooguit 2.000 regels per start. De volgende start verwijdert de oudste, en de beheerder kan ze eerder verwijderen.", - "messagesP5": "Een bericht melden is de laatste. Als je met de rechtermuisknop op een bericht Report message kiest, plaatst {{bot}} het in het modmailkanaal van die server voor het team: de tekst van het bericht, wie het schreef, wie het meldde en wat je erover zei. Dat bericht staat in Discord, niet in de database van de bot. De bot onthoudt een uur lang, alleen in het geheugen, welke berichten je meldde, zodat hetzelfde niet twee keer gemeld kan worden; een herstart vergeet het." + "messagesP5": "Een bericht melden is de laatste. Als je met de rechtermuisknop op een bericht Report message kiest, plaatst {{bot}} het in het modmailkanaal van die server voor het team: de tekst van het bericht, wie het schreef, wie het meldde en wat je erover zei. Dat bericht staat in Discord, niet in de database van de bot. De bot onthoudt een uur lang, alleen in het geheugen, welke berichten je meldde, zodat hetzelfde niet twee keer gemeld kan worden; een herstart vergeet het.", + "messagesP6": "Als {{bot}} aan een server wordt toegevoegd, stuurt het ook één privébericht: een korte uitleg om te beginnen, aan wie het toevoegde. Om die te vinden leest de bot het item over zijn eigen komst in het auditlogboek van de server, of anders zijn eigen item bij de integraties van de server, en schrijft hij de eigenaar van de server als geen van beide het zegt. Hiervan wordt niets bewaard. Wie privéberichten heeft uitgezet, krijgt niets, en de beheerder kan het bericht uitzetten." }, "problem": { "automodMentionLimit": "Kies hoeveel mentions je toestaat.", @@ -2636,6 +2640,8 @@ "featuresSummary": "Draai de bot zonder muziek, casino of iets anders dat je niet wilt.", "docker": "Docker", "dockerSummary": "De bot en zijn database met Docker Compose, en waar hij verder kan draaien.", + "customising": "Maak het je eigen", + "customisingSummary": "Je links, wie het beheert en het standaardvoorvoegsel, in één bestand naast .env, en hoe je een fork bijhoudt.", "dashboard": "De website en het dashboard", "dashboardSummary": "Deze site, het dashboard achter de inlog, wie wat kan zien, en ze op internet zetten.", "scripts": "Scripts", diff --git a/dashboard/src/i18n/locales/ru.json b/dashboard/src/i18n/locales/ru.json index 1d009b44c..9e6a658c8 100644 --- a/dashboard/src/i18n/locales/ru.json +++ b/dashboard/src/i18n/locales/ru.json @@ -2141,6 +2141,9 @@ "termsTitle": "Условия использования", "termsSummary": "Правила пользования {{bot}} и этой панелью и что бывает при их нарушении. Прочитайте их, прежде чем пользоваться чем-либо из этого.", "whoRuns": "Кто им управляет", + "operatorTitle": "Кто управляет этой копией", + "operatorName": "Управляет", + "operatorContact": "Контакт", "whoRunsP1": "{{bot}} размещается самостоятельно. Тот, кто развернул этот экземпляр, — оператор — решает, что он делает, что хранит и кто до него достучится. Ответственность на нём, а не на авторах проекта.", "whoRunsP2": "Программа поставляется как есть, без каких-либо гарантий. Никто не обещает доступности, правильности или отсутствия дефектов.", "whoRunsP3": "Код опубликован под лицензией MIT. Любой может использовать, изменять, распространять и продавать его, если в каждой копии сохраняются уведомление об авторском праве с именем автора и сам текст лицензии.", @@ -2340,7 +2343,8 @@ "retentionL20": "Отслеживание приглашений: 365 дней после каждого входа, затем удаляется автоматически, а целиком — когда бота убирают с сервера.", "retentionL21": "Доступ к панели: пока администратор его не заберёт, вы не покинете сервер или бот не будет удалён с него.", "retentionL22": "Строки журнала: последние 6 запусков бота, не больше 2000 строк на каждый. Следующий запуск удаляет самый старый, и оператор может удалить их раньше.", - "messagesP5": "Жалоба на сообщение — последнее. Когда вы нажимаете на сообщение правой кнопкой и выбираете Report message, {{bot}} публикует его в канале почты модераторам этого сервера: текст сообщения, кто его написал, кто пожаловался и что вы о нём сказали. Эта публикация хранится в Discord, а не в базе данных бота. Бот помнит час, только в памяти, на какие сообщения вы пожаловались, чтобы на одно и то же нельзя было пожаловаться дважды; перезапуск это забывает." + "messagesP5": "Жалоба на сообщение — последнее. Когда вы нажимаете на сообщение правой кнопкой и выбираете Report message, {{bot}} публикует его в канале почты модераторам этого сервера: текст сообщения, кто его написал, кто пожаловался и что вы о нём сказали. Эта публикация хранится в Discord, а не в базе данных бота. Бот помнит час, только в памяти, на какие сообщения вы пожаловались, чтобы на одно и то же нельзя было пожаловаться дважды; перезапуск это забывает.", + "messagesP6": "При добавлении {{bot}} на сервер отправляется ещё одно личное сообщение — подсказка, с чего начать, тому, кто добавил бота. Чтобы узнать, кто это, бот читает запись о своём добавлении в журнале аудита сервера, а если её нет — свою запись в интеграциях сервера; если не помогает ни то, ни другое, он пишет владельцу сервера. Ничего из этого не сохраняется. Тем, у кого закрыты личные сообщения, ничего не отправляется, а оператор может отключить это сообщение." }, "problem": { "automodMentionLimit": "Выберите, сколько упоминаний разрешить.", @@ -2784,6 +2788,8 @@ "featuresSummary": "Запускайте бота без музыки, казино или чего-либо ещё, что вам не нужно.", "docker": "Docker", "dockerSummary": "Бот и его база данных в Docker Compose, и где ещё его можно запустить.", + "customising": "Сделайте его своим", + "customisingSummary": "Ваши ссылки, кто им управляет и префикс по умолчанию — в одном файле рядом с .env, и как держать форк в актуальном состоянии.", "dashboard": "Сайт и панель управления", "dashboardSummary": "Этот сайт, панель управления за входом, кто что видит и как открыть их в интернете.", "scripts": "Скрипты", diff --git a/dashboard/src/test/fixtures/site.ts b/dashboard/src/test/fixtures/site.ts index d091e3e4b..a1a4574e3 100644 --- a/dashboard/src/test/fixtures/site.ts +++ b/dashboard/src/test/fixtures/site.ts @@ -11,6 +11,8 @@ export const siteInfo: SiteInfo = { repository: "https://github.com/Kkkermit/Testify", version: "2.0.9", featuresOff: [], + defaultPrefix: "t?", + operator: null, }; export const standing: RepositoryStanding = { diff --git a/docker-compose.yml b/docker-compose.yml index 309a92933..a03596726 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,10 +1,12 @@ # Testify and a MongoDB to keep its data in. # # cp .env.example .env # fill it in, or run `npm run setup` +# cp testify.config.example.json testify.config.json # optional: your links, who runs it, the prefix # docker compose up -d # docker compose logs -f bot # -# Everything below reads from .env. Nothing is hardcoded, and no secret is baked into the image. +# Everything below reads from .env, and testify.config.json beside it. Nothing is hardcoded, and no secret is +# baked into the image. services: bot: @@ -19,7 +21,12 @@ services: depends_on: mongo: condition: service_healthy + volumes: + # This folder, read-only, so testify.config.json is read from beside .env. A missing file means the defaults; + # mounting the file itself would make Docker create an empty folder in its place when there is none. + - .:/app/instance:ro environment: + TESTIFY_CONFIG: /app/instance/testify.config.json # `mongo` is this compose network's hostname for the database below. MONGODB_URI: ${MONGODB_URI:-mongodb://mongo:27017/testify} DISCORD_TOKEN: ${DISCORD_TOKEN:?set DISCORD_TOKEN in .env} diff --git a/docs/README.md b/docs/README.md index 08499553c..35894abc2 100644 --- a/docs/README.md +++ b/docs/README.md @@ -40,6 +40,7 @@ | --------------------------------------------- | -------------------------------------------------------------------------------- | | 📋 [`commands.md`](commands.md) | Every command, subcommand and alias. **Generated** — run `npm run docs:commands` | | 🤝 [`contributing.md`](contributing.md) | Branches, commit format, house style and what CI will check | +| 🎨 [`customising.md`](customising.md) | Your links, who runs it and the prefix in `testify.config.json`, and forks | | 🐳 [`hosting.md`](hosting.md) | Running the bot and dashboard in Docker, and what is deliberately not there | | 🔒 [`security.md`](security.md) | Reporting a vulnerability, the data model, and every dependency exception | | 🌱 [`code-of-conduct.md`](code-of-conduct.md) | The standard everybody here is held to, and how to report a problem | diff --git a/docs/customising.md b/docs/customising.md new file mode 100644 index 000000000..ad092cc34 --- /dev/null +++ b/docs/customising.md @@ -0,0 +1,138 @@ +
+ +# 🎨 Make it your own + +**Your copy of Testify, with your name, your links and your prefix, and still easy to update.** + +[What follows by itself](#-what-follows-the-bot-by-itself) · [`testify.config.json`](#️-testifyconfigjson) · +[What takes code](#️-what-takes-code) · [Keeping a fork up to date](#-keeping-a-fork-up-to-date) + +
+ +Testify is meant to be copied. Most of what makes a copy yours needs no code at all: the bot's name and picture come +from Discord, `.env` holds the secrets and the switches, and `testify.config.json` holds everything else that a +person reading your bot sees, from the link to your source code to who people should ask about their data. + +--- + +## ✨ What follows the bot by itself + +- **The name and the picture.** Everything the bot shows — its embeds, the website, the dashboard, link previews in + Discord — uses the bot's own Discord username, avatar, banner and accent colour. Change them in the + [Developer Portal](https://discord.com/developers/applications) and every surface follows on its next read. There + is no name setting to keep in step. +- **The invite and the commands.** The invite link and every command's registration come from your own + application ID, so nothing points at the original bot. + +## ⚙️ `testify.config.json` + +The file sits beside `.env` and holds nothing secret. Every key is optional, and anything you leave out keeps the +original's value, so a copy without the file behaves exactly as it always did. Two ways to make one: + +```bash +npm run setup # answer "Make it your own?" at the end +cp testify.config.example.json testify.config.json # or copy the example and edit it +``` + +| Key | What it does | When you leave it out | +| --------------- | --------------------------------------------------------------------------------------- | ----------------------------- | +| `repository` | Your fork on GitHub. The website's source browser shows it; Source code buttons open it | The original repository | +| `supportServer` | Where Support buttons lead. `null` hides them, so nobody is sent to somebody else's | The original's support server | +| `developer` | Who `/bot info` names as the developer | The original author | +| `operator` | Who runs this copy and how to reach them, shown on the privacy notice and the terms | Nobody is named | +| `defaultPrefix` | The prefix a server starts with until it picks its own | `t?` | +| `greetInviter` | Whether whoever adds the bot to a server gets a getting-started message | `true` | + +A filled-in one looks like this: + +```json +{ + "$schema": "./testify.config.schema.json", + "repository": "https://github.com/you/your-fork", + "supportServer": "https://discord.gg/your-invite", + "developer": "You", + "operator": { "name": "Your name or organisation", "contact": "privacy@example.com" }, + "defaultPrefix": "!" +} +``` + +A few things worth knowing: + +- **Your editor checks it as you type.** The `$schema` line points at `testify.config.schema.json`, so VS Code and + most other editors complete the keys and underline a mistake. +- **It is read once, at start-up.** Restart the bot after changing it. A mistake stops the start with a list of + every problem, and an unknown key is one of them, so a misspelt setting never quietly does nothing. +- **`npm run dev` reads `testify.config.development.json`**, the way it reads `.env.development`, so a development + bot can use a different prefix from the one people invite. +- **In Docker it sits beside `.env` too.** `docker-compose.yml` mounts the folder it runs from, read-only, so the bot + finds the file there, and a missing one simply means the defaults. See [Docker](hosting.md). +- **It is ignored by git, like `.env`.** In a fork you want to commit it in, delete its two lines from `.gitignore`. + +### The operator + +If people other than you use your bot, say who runs it. The privacy notice tells people to ask the operator about +their data and about a blacklist entry; with `operator` set, both the privacy notice and the terms open with a card +naming you and linking your contact, which is an email address or an `https://` page. Where the GDPR or the UK GDPR +applies, the operator is the controller of the data, and has to be identifiable. + +### The default prefix + +A server that has never chosen a prefix follows `defaultPrefix`, so changing it reaches every one of them on the +next restart. A server that chose its own keeps it, and the prefix panel's Reset moves it back to yours. One catch +for a copy that ran an older version: a server's prefix could be saved before this setting existed even when the +server never chose one, and those keep what was saved until someone presses Reset. + +### The getting-started message + +When the bot joins a server, it sends whoever added it one direct message: how to see what it can do, where to set +it up — the dashboard's setup checklist when the dashboard is on — and how to change the prefix. It finds that +person the same way whether they used an invite link, the Add App button on the bot's profile or the App Directory: +the server's audit log records who added the bot, the bot's own integration records it too for a bot not given View +Audit Log, and the server's owner gets it when neither says. Closed direct messages are left alone, bots and +blacklisted accounts get nothing, and `"greetInviter": false` turns it off. + +## 🛠️ What takes code + +Everything else is a small number of files, chosen so that a change to them rarely meets a change from upstream: + +| To change | Edit | +| ------------------------------------------ | ------------------------------------------------------------------------------------------------ | +| The colour of each category's embeds | `src/config/theme.ts`, the only place a colour is written | +| The emoji the bot uses | `src/config/theme.ts` | +| The dashboard's colours, corners and fonts | `dashboard/src/index.css`, whose `@theme` tokens are the whole palette | +| What the bot says | `src/config/strings.ts`; the refusals every command shares are `src/config/replies.ts` | +| What the dashboard says | `dashboard/src/i18n/locales/*.json`, one file per language | +| The help articles `/ask` answers with | `assets/support/*.md` | +| A command of your own | A new file under `src/commands/` — see [Adding a command](../README.md#️-adding-your-own-command) | + +Switching whole features off needs no code either: `DISABLED_FEATURES` in `.env` takes them out of Discord, the +dashboard and the docs. [Switching off a whole feature](articles/switching-features-off.md) explains how. + +## 🔄 Keeping a fork up to date + +Every release is tagged `release/vX.Y.Z`, and `main` is always the newest release. `develop` is work in progress, so +never merge it into a copy people use. + +```bash +git remote add upstream https://github.com/Kkkermit/Testify.git # once +git fetch upstream --tags +git merge release/v2.5.0 # the release you want +npm ci && npm run check +``` + +Merging stays easy when your changes stay in a few places: + +- **Put your settings in `testify.config.json` rather than in code**, and your links never conflict at all. +- **Add commands as new files** rather than editing the original ones; a new file cannot conflict. +- **Keep visual changes to `theme.ts` and `index.css`**, so a conflict, when there is one, is in a file you know. +- **Read a release's "Before you upgrade"** on the [releases page](https://github.com/Kkkermit/Testify/releases) + before merging it. + +Running the published Docker image needs no fork at all: `.env` and `testify.config.json` beside the compose files +are the whole of your copy, and `TESTIFY_TAG` in `.env` pins the release you run. + +## ⚖️ The licence + +Testify is MIT-licensed. Use it, change it, rename it and run it as your own; the one condition is that +[`LICENSE`](../LICENSE), with its copyright notice, stays with every copy you share. Changing `developer` changes who +`/bot info` names, and leaves that notice where it is. diff --git a/docs/hosting.md b/docs/hosting.md index 07ba8b865..2391deb79 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -35,6 +35,12 @@ docker compose up -d docker compose logs -f bot ``` +Your own links, who runs your copy and the default prefix go in `testify.config.json`, beside `.env`. It is +optional: copy `testify.config.example.json` to start one, and [Make it your own](customising.md) explains each +setting. The compose file mounts the folder it runs from into the container, read-only, and the bot reads the file +from there, so a missing one simply means the defaults. It mounts the folder rather than the file because Docker, +asked to mount a file that does not exist, creates an empty folder in its place. + Three variables have no sensible default and compose refuses to start without them, naming the one it wants: `DISCORD_TOKEN`, `DISCORD_CLIENT_ID` and `DISCORD_OWNER_IDS`. Everything else falls back to the same defaults the bot uses when run from source. @@ -63,7 +69,7 @@ and `.env` beside each other: docker compose -f docker-compose.yml -f docker-compose.image.yml up -d ``` -It follows the newest release. `TESTIFY_TAG=2.4.0` in `.env` pins one, and updating is the same command after a +Put `testify.config.json` in the same folder if you want one. It follows the newest release. `TESTIFY_TAG=2.4.0` in `.env` pins one, and updating is the same command after a `pull`: ```bash diff --git a/package.json b/package.json index 88168d129..066566a0a 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "db:wipe:dev": "tsx scripts/wipeDatabase.ts --dev", "dev": "npm run build:shared && cross-env NODE_ENV=development tsx watch --clear-screen=false src/index.ts", "dev:all": "tsx scripts/devAll.ts", + "config:schema": "tsx scripts/generateConfigSchema.ts", "docs:commands": "tsx scripts/generateCommandDocs.ts", "i18n:commands": "tsx scripts/commandStrings.ts", "docs:images": "tsx scripts/renderDocImages.ts", diff --git a/scripts/generateConfigSchema.ts b/scripts/generateConfigSchema.ts new file mode 100644 index 000000000..485ec3dea --- /dev/null +++ b/scripts/generateConfigSchema.ts @@ -0,0 +1,25 @@ +import { writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format, resolveConfig } from "prettier"; +import { instanceJsonSchema } from "@config/instance"; + +/** Writes `testify.config.schema.json` from the schema the bot reads its config file with. */ + +export const SCHEMA_FILE = "testify.config.schema.json"; + +export async function configSchemaText(): Promise { + const target = resolve(__dirname, "..", SCHEMA_FILE); + return format(JSON.stringify(instanceJsonSchema()), { ...(await resolveConfig(target)), parser: "json" }); +} + +if (require.main === module) { + configSchemaText() + .then((text) => { + writeFileSync(resolve(__dirname, "..", SCHEMA_FILE), text, "utf8"); + console.log(`Wrote ${SCHEMA_FILE}.`); + }) + .catch((error: unknown) => { + console.error(error); + process.exit(1); + }); +} diff --git a/scripts/setupEnv.ts b/scripts/setupEnv.ts index a7d28dc57..062ff0b65 100644 --- a/scripts/setupEnv.ts +++ b/scripts/setupEnv.ts @@ -2,6 +2,8 @@ import { randomBytes } from "node:crypto"; import { existsSync, writeFileSync } from "node:fs"; import { resolve } from "node:path"; import prompts from "prompts"; +import { type z } from "zod"; +import { instanceFileSchema } from "@config/instance"; import { box, painter } from "@core/terminal"; import { BOT_FEATURE_KEYS, isBotFeature } from "@testify/shared"; @@ -131,6 +133,79 @@ export function fields(isDev: boolean): Field[] { ]; } +/** The same rule the bot reads the file with, so a wizard answer can never write a file the bot refuses. */ +const byRule = + (rule: z.ZodType) => + (value: string): string | null => { + const result = rule.safeParse(value); + return result.success ? null : `It ${result.error.issues[0]?.message ?? "is not valid"}.`; + }; + +const keys = instanceFileSchema.shape; +const operator = keys.operator.unwrap().unwrap().shape; + +export function instanceFields(): Field[] { + return [ + { + key: "operator.name", + message: "Who runs this copy", + hint: "Your name or your organisation's, shown on the privacy notice", + required: false, + check: byRule(operator.name), + }, + { + key: "supportServer", + message: "Support server link", + hint: "Where Support buttons lead. Type none to hide them, or leave blank for the default", + required: false, + check: (value) => (value === "none" ? null : byRule(keys.supportServer)(value)), + }, + { + key: "repository", + message: "Your fork on GitHub", + hint: "Blank keeps the original repository", + required: false, + check: byRule(keys.repository), + }, + { + key: "defaultPrefix", + message: "Default prefix", + hint: "What a server starts with; blank keeps t?", + required: false, + check: byRule(keys.defaultPrefix), + }, + ]; +} + +export const OPERATOR_CONTACT: Field = { + key: "operator.contact", + message: "How to reach them", + hint: "An email address or an https:// page", + required: true, + check: byRule(operator.contact), +}; + +/** The file the wizard writes: only what was answered, so everything left blank keeps following the defaults. */ +export function instanceFileText(answers: Record): string | null { + const given = (key: string): string | undefined => { + const value = answers[key]?.trim() ?? ""; + return value === "" ? undefined : value; + }; + const name = given("operator.name"); + const contact = given("operator.contact"); + const support = given("supportServer"); + + const config: Record = { + ...(given("repository") === undefined ? {} : { repository: given("repository") }), + ...(support === undefined ? {} : { supportServer: support === "none" ? null : support }), + ...(name === undefined || contact === undefined ? {} : { operator: { name, contact } }), + ...(given("defaultPrefix") === undefined ? {} : { defaultPrefix: given("defaultPrefix") }), + }; + if (Object.keys(config).length === 0) return null; + + return `${JSON.stringify({ $schema: "./testify.config.schema.json", ...config }, null, "\t")}\n`; +} + export function dashboardFields(isDev: boolean): Field[] { return [ { @@ -263,9 +338,47 @@ async function main(): Promise { steps.push("", "One more step in the Developer Portal, under OAuth2 → Redirects:", ` ${paint.bold(callback)}`); } + const configured = await makeItYours(isDev); + if (configured !== null) steps.push("", `Your links and settings are in ${paint.bold(configured)}.`); + print(["", ...box("Done", steps, "success", paint).map((line) => ` ${line}`), ""]); } +/** Optional, and separate from `.env`, because none of it is secret and a fork may want to commit it. */ +async function makeItYours(isDev: boolean): Promise { + const filename = isDev ? "testify.config.development.json" : "testify.config.json"; + const target = resolve(process.cwd(), filename); + + const { wanted } = await prompts( + { + type: "confirm", + name: "wanted", + message: `${paint.bold("Make it your own?")}${paint.dim(` (who runs it, your links, the prefix — written to ${filename})`)}`, + initial: false, + }, + { onCancel: () => process.exit(1) }, + ); + if (wanted !== true) return null; + + if (existsSync(target)) { + const { overwrite } = await prompts({ + type: "confirm", + name: "overwrite", + message: `${filename} already exists. Replace it?`, + initial: false, + }); + if (overwrite !== true) return null; + } + + const answers = await ask(instanceFields()); + const contact = (answers["operator.name"] ?? "") === "" ? {} : await ask([OPERATOR_CONTACT]); + const text = instanceFileText({ ...answers, ...contact }); + if (text === null) return null; + + writeFileSync(target, text, "utf8"); + return filename; +} + if (require.main === module) { main().catch((error: unknown) => { process.stderr.write(`${String(error)}\n`); diff --git a/shared/src/api.ts b/shared/src/api.ts index 60d91ee3b..2588fcea1 100644 --- a/shared/src/api.ts +++ b/shared/src/api.ts @@ -24,7 +24,8 @@ export interface BotIdentity { bannerUrl: string | null; /** The profile accent as a CSS hex, when the application has set one. */ accentColour: string | null; - supportUrl: string; + /** Null when the host has no support server, so nothing links to somebody else's. */ + supportUrl: string | null; repositoryUrl: string; } diff --git a/shared/src/settings.ts b/shared/src/settings.ts index 2379d7a67..21fd0c794 100644 --- a/shared/src/settings.ts +++ b/shared/src/settings.ts @@ -9,6 +9,7 @@ export const SETTINGS_LIMITS = { maxCount: 1_000_000, } as const; +/** The built-in default; a host may set another in `testify.config.json`, which the bot and the API read instead. */ export const DEFAULT_PREFIX = "t?"; export const BYPASS_PERMISSIONS = ["ManageMessages", "ManageGuild", "ModerateMembers", "Administrator"] as const; @@ -64,11 +65,13 @@ export interface ServerSettings { } /** A prefix of pure whitespace matches every message; one with a space inside can never be typed. */ +export const prefixText = plainLine(1, SETTINGS_LIMITS.maxPrefix).refine( + (value) => !/\s/.test(value), + "cannot contain a space", +); + export const prefixPatch = z - .object({ - prefix: plainLine(1, SETTINGS_LIMITS.maxPrefix).refine((value) => !/\s/.test(value), "cannot contain a space"), - enabled: z.boolean(), - }) + .object({ prefix: prefixText, enabled: z.boolean() }) .partial() .refine((patch) => Object.keys(patch).length > 0, "must change something"); diff --git a/shared/src/site.ts b/shared/src/site.ts index 082b59cc7..3071def84 100644 --- a/shared/src/site.ts +++ b/shared/src/site.ts @@ -13,12 +13,21 @@ export const SITE_LIMITS = { pathMax: 400, } as const; +/** Who runs this copy of the bot, from its `testify.config.json`, so the privacy notice can say who to ask. */ +export interface InstanceOperator { + name: string; + contact: string; +} + export interface SiteInfo { dashboard: boolean; repository: string; version: string; /** What `DISABLED_FEATURES` switched off, so the pages leave out what the bot no longer does. */ featuresOff: BotFeature[]; + /** The prefix a server starts with, which a host may change from the built-in `t?`. */ + defaultPrefix: string; + operator: InstanceOperator | null; } interface LatestRelease { @@ -121,6 +130,15 @@ export function repositoryCoordinates(url: string): { owner: string; repo: strin return owner === undefined || repo === undefined ? null : { owner, repo }; } +const EMAIL = /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/; + +/** The link a contact opens: an `https` page or an email address, and nothing else, so no scheme can run script. */ +export function contactHref(contact: string): string | null { + if (/^https:\/\/[^\s<>"]+$/.test(contact)) return contact; + if (EMAIL.test(contact)) return `mailto:${contact}`; + return null; +} + export function githubFileUrl(repository: string, ref: string, path: string): string { const encoded = (value: string): string => value.split("/").map(encodeURIComponent).join("/"); return `${repository}/blob/${encoded(ref)}/${encoded(path)}`; diff --git a/src/api/routes/commandRunner.ts b/src/api/routes/commandRunner.ts index e6f3681ab..8b4b1c259 100644 --- a/src/api/routes/commandRunner.ts +++ b/src/api/routes/commandRunner.ts @@ -5,7 +5,7 @@ import { type ApiBindings } from "@api/context"; import { badRequest, notFound, notInGuild } from "@api/errors"; import { requireOwner } from "@api/middleware/session"; import { parseBody, parseParams } from "@api/validate"; -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { type TestifyClient } from "@core/client"; import { type Command, type CommandInput } from "@core/command"; import { UserFacingError } from "@core/errors"; @@ -27,7 +27,10 @@ commandRunner.get("/", (context) => { const client = context.get("client"); const runnable = [...client.commands.values()].filter((command) => runnableInDashboard(command.name)); - const body: CommandCatalogue = buildCatalogue(runnable, { prefix: DEFAULT_PREFIX, includeOwnerOnly: true }); + const body: CommandCatalogue = buildCatalogue(runnable, { + prefix: instanceConfig().defaultPrefix, + includeOwnerOnly: true, + }); return context.json(body); }); diff --git a/src/api/routes/commands.ts b/src/api/routes/commands.ts index 98f35becc..3f5996c30 100644 --- a/src/api/routes/commands.ts +++ b/src/api/routes/commands.ts @@ -1,7 +1,7 @@ import { Hono } from "hono"; import { type ApiBindings } from "@api/context"; import { requireAuth } from "@api/middleware/session"; -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { buildCatalogue } from "@lib/bot"; /** Every command the bot has; behind a session because owner commands are filtered by who asks. */ @@ -11,7 +11,7 @@ export const commands = new Hono().use("*", requireAuth).get("/", ( return context.json( buildCatalogue(client.commands.values(), { - prefix: DEFAULT_PREFIX, + prefix: instanceConfig().defaultPrefix, includeOwnerOnly: session !== undefined && client.isOwner(session.userId), }), ); diff --git a/src/api/routes/settings.ts b/src/api/routes/settings.ts index 6b55217d4..774238fc2 100644 --- a/src/api/routes/settings.ts +++ b/src/api/routes/settings.ts @@ -6,7 +6,7 @@ import { badRequest, notInGuild } from "@api/errors"; import { requireGrantable, requirePermission } from "@api/middleware/reach"; import { requireGuild } from "@api/middleware/session"; import { parseBody } from "@api/validate"; -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { botName } from "@core/brand"; import { disableAntiLink, setAntiLink } from "@database/repositories/antiLinkRepository"; import { setAutoRoles } from "@database/repositories/autoRoleRepository"; @@ -178,7 +178,9 @@ function summarisePrefix(patch: PrefixPatch): string { parts.push(patch.enabled ? "Turned prefix commands on" : "Turned prefix commands off"); if (patch.prefix !== undefined) parts.push(`Changed the prefix to ${patch.prefix}`); - return parts.length === 0 ? `Changed the prefix settings (default is ${DEFAULT_PREFIX})` : parts.join(", "); + return parts.length === 0 + ? `Changed the prefix settings (default is ${instanceConfig().defaultPrefix})` + : parts.join(", "); } function summariseAntiLink(patch: AntiLinkPatch): string { diff --git a/src/api/routes/site.ts b/src/api/routes/site.ts index b93bd37b1..32abfee6e 100644 --- a/src/api/routes/site.ts +++ b/src/api/routes/site.ts @@ -2,7 +2,7 @@ import { Hono } from "hono"; import { type ApiBindings } from "@api/context"; import { type ApiProblem, forbidden, notFound, UpstreamProblem } from "@api/errors"; import { parseQuery } from "@api/validate"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { ServiceError } from "@core/errors"; import { botVersion } from "@lib/bot"; import { type GitHubReader, SiteProblem, type SiteRefusal } from "@lib/site"; @@ -53,7 +53,9 @@ export function siteRoutes(github: GitHubReader): Hono { .get("/", (context) => { const body: SiteInfo = { dashboard: context.get("env").DASHBOARD_ENABLED, - repository: theme.repository, + repository: instanceConfig().repository, + defaultPrefix: instanceConfig().defaultPrefix, + operator: instanceConfig().operator, version: botVersion(), featuresOff: BOT_FEATURE_KEYS.filter((key) => context.get("client").featuresOff.has(key)), }; diff --git a/src/api/routes/support.ts b/src/api/routes/support.ts index 7b1d39035..bb86863d4 100644 --- a/src/api/routes/support.ts +++ b/src/api/routes/support.ts @@ -3,7 +3,7 @@ import { type ApiBindings } from "@api/context"; import { notFound } from "@api/errors"; import { requireAuth } from "@api/middleware/session"; import { parseBody, parseParams } from "@api/validate"; -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { supportContext, supportDesk } from "@lib/support"; import { supportArticleParams, type SupportIndex, supportQuestion, type SupportReply } from "@testify/shared"; @@ -18,7 +18,9 @@ supportQuestions.use("*", requireAuth); supportArticles.get("/", (context) => { const client = context.get("client"); - const body: SupportIndex = { articles: supportDesk(client).catalogue(supportContext(DEFAULT_PREFIX)) }; + const body: SupportIndex = { + articles: supportDesk(client).catalogue(supportContext(instanceConfig().defaultPrefix)), + }; return context.json(body); }); @@ -26,7 +28,7 @@ supportArticles.get("/", (context) => { supportQuestions.post("/ask", async (context) => { const client = context.get("client"); const { question } = await parseBody(context, supportQuestion); - const body: SupportReply = await supportDesk(client).ask(question, supportContext(DEFAULT_PREFIX)); + const body: SupportReply = await supportDesk(client).ask(question, supportContext(instanceConfig().defaultPrefix)); return context.json(body); }); @@ -34,7 +36,7 @@ supportQuestions.post("/ask", async (context) => { supportArticles.get("/articles/:articleId", (context) => { const client = context.get("client"); const { articleId } = parseParams(context, supportArticleParams); - const help = supportContext(DEFAULT_PREFIX); + const help = supportContext(instanceConfig().defaultPrefix); const desk = supportDesk(client); const answer = desk.article(articleId, help); diff --git a/src/api/server.ts b/src/api/server.ts index 519907539..4eb094bed 100644 --- a/src/api/server.ts +++ b/src/api/server.ts @@ -28,7 +28,7 @@ import { status } from "@api/routes/status"; import { supportArticles, supportQuestions } from "@api/routes/support"; import { dashboardRoot, serveDashboard } from "@api/static"; import { type Env } from "@config/env"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { type TestifyClient } from "@core/client"; import { toError } from "@core/errors"; import { botVersion, siteUrl } from "@lib/bot"; @@ -79,7 +79,7 @@ export function createApi(client: TestifyClient, env: Env): Hono { const appealing = limiterPair(APPEAL_LIMIT); const oauth = oauthConfigFrom(env); const github = new GitHubReader({ - repository: theme.repository, + repository: instanceConfig().repository, version: botVersion(), token: env.SITE_GITHUB_TOKEN, logger: client.logger, diff --git a/src/buttons/help.ts b/src/buttons/help.ts index 1e754c00e..e6b5c8bb9 100644 --- a/src/buttons/help.ts +++ b/src/buttons/help.ts @@ -1,4 +1,4 @@ -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { defineButton } from "@core/button"; import { getPrefix } from "@database/repositories/prefixRepository"; import { @@ -19,7 +19,7 @@ export default defineButton({ async run(interaction, context) { const { client, action, args } = context; - const prefix = interaction.guildId === null ? DEFAULT_PREFIX : await getPrefix(interaction.guildId); + const prefix = interaction.guildId === null ? instanceConfig().defaultPrefix : await getPrefix(interaction.guildId); const ownerId = args.at(-1) ?? interaction.user.id; if (action === "noop") return; diff --git a/src/buttons/prefixSetup.ts b/src/buttons/prefixSetup.ts index 9f37cb4cf..89b6b65f3 100644 --- a/src/buttons/prefixSetup.ts +++ b/src/buttons/prefixSetup.ts @@ -1,5 +1,5 @@ import { PermissionFlagsBits } from "discord.js"; -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { defineButton } from "@core/button"; import { UserFacingError } from "@core/errors"; import { getPrefixConfig, setPrefix, setPrefixEnabled } from "@database/repositories/prefixRepository"; @@ -81,8 +81,11 @@ export default recordsSettings( } case "reset": { - await setPrefix(guildId, DEFAULT_PREFIX); - await show({ ...state, prefix: DEFAULT_PREFIX }, `Back to \`${DEFAULT_PREFIX}\`.`); + await setPrefix(guildId, instanceConfig().defaultPrefix); + await show( + { ...state, prefix: instanceConfig().defaultPrefix }, + `Back to \`${instanceConfig().defaultPrefix}\`.`, + ); return; } diff --git a/src/buttons/support.ts b/src/buttons/support.ts index 3fe483a8e..98baacda5 100644 --- a/src/buttons/support.ts +++ b/src/buttons/support.ts @@ -1,5 +1,4 @@ -import { DEFAULT_PREFIX } from "@config/constants"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { defineButton } from "@core/button"; import { getPrefix } from "@database/repositories/prefixRepository"; import { dashboardUrl } from "@lib/bot"; @@ -13,7 +12,7 @@ export default defineButton({ if (!interaction.isButton() || context.action !== "open") return; const [articleId = ""] = context.args; - const prefix = interaction.guild === null ? DEFAULT_PREFIX : await getPrefix(interaction.guild.id); + const prefix = interaction.guild === null ? instanceConfig().defaultPrefix : await getPrefix(interaction.guild.id); const help = supportContext(prefix); const desk = supportDesk(context.client); @@ -24,7 +23,7 @@ export default defineButton({ bot: help.bot, ownerId: interaction.user.id, dashboard: dashboardUrl(context.client.env), - supportServer: theme.supportServer, + supportServer: instanceConfig().supportServer, }, ), ); diff --git a/src/commands/info/ask.command.ts b/src/commands/info/ask.command.ts index af96d1091..6d5d3ba4b 100644 --- a/src/commands/info/ask.command.ts +++ b/src/commands/info/ask.command.ts @@ -1,5 +1,4 @@ -import { DEFAULT_PREFIX } from "@config/constants"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { defineCommand } from "@core/command"; import { UserFacingError } from "@core/errors"; import { getPrefix } from "@database/repositories/prefixRepository"; @@ -45,7 +44,7 @@ export default defineCommand({ // Matching can call out to a model, which may take longer than Discord waits for a first reply. await interaction.deferReply(); - const prefix = interaction.guild === null ? DEFAULT_PREFIX : await getPrefix(interaction.guild.id); + const prefix = interaction.guild === null ? instanceConfig().defaultPrefix : await getPrefix(interaction.guild.id); const help = supportContext(prefix); const desk = supportDesk(client); const { question } = parsed.data; @@ -63,14 +62,14 @@ export default defineCommand({ bot: help.bot, ownerId: interaction.user.id, dashboard: dashboardUrl(client.env), - supportServer: theme.supportServer, + supportServer: instanceConfig().supportServer, }), ); }, async autocomplete(interaction, client) { const typed = interaction.options.getFocused().slice(0, QUESTION_MAX); - const links = supportDesk(client).suggest(typed, supportContext(DEFAULT_PREFIX), CHOICES_MAX); + const links = supportDesk(client).suggest(typed, supportContext(instanceConfig().defaultPrefix), CHOICES_MAX); const choices = links.map((link) => ({ name: suggestionName(link), value: `${ARTICLE_CHOICE}${link.id}` })); // First, so pressing Enter asks exactly what was typed rather than opening the top suggestion. diff --git a/src/commands/info/bot.command.ts b/src/commands/info/bot.command.ts index d91b77c95..e9af2d72a 100644 --- a/src/commands/info/bot.command.ts +++ b/src/commands/info/bot.command.ts @@ -1,10 +1,11 @@ import { arch, type as osType, cpus, freemem, platform, totalmem } from "node:os"; import { version as djsVersion } from "discord.js"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { botName } from "@core/brand"; import { type TestifyClient } from "@core/client"; import { defineCommand, type CommandInput } from "@core/command"; -import { embed, linkButton, reply, row } from "@lib/discord"; +import { projectLinkButtons } from "@lib/bot"; +import { embed, reply, row } from "@lib/discord"; import { discordTime, formatBytes, formatUptime } from "@lib/format"; import { reachFields } from "@lib/info"; @@ -60,11 +61,11 @@ async function showInfo(interaction: CommandInput, client: TestifyClient): Promi category: "info", title: `About ${botName()}`, description: "An open source, multipurpose Discord bot written in TypeScript.", - fields: [...reachFields(client), { name: "Developer", value: theme.author, inline: true }], + fields: [...reachFields(client), { name: "Developer", value: instanceConfig().developer, inline: true }], thumbnail: client.user?.displayAvatarURL(), }), ], - components: [row(linkButton("Source code", theme.repository), linkButton("Support server", theme.supportServer))], + components: [row(...projectLinkButtons())], }); } diff --git a/src/commands/info/help.command.ts b/src/commands/info/help.command.ts index 35d227933..cfa20da19 100644 --- a/src/commands/info/help.command.ts +++ b/src/commands/info/help.command.ts @@ -1,4 +1,4 @@ -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { defineCommand } from "@core/command"; import { UserFacingError } from "@core/errors"; import { getPrefix } from "@database/repositories/prefixRepository"; @@ -23,7 +23,7 @@ export default defineCommand({ options: [{ name: "query", description: "A command or category name.", type: "string", autocomplete: true }], async run(interaction, client) { - const prefix = interaction.guild ? await getPrefix(interaction.guild.id) : DEFAULT_PREFIX; + const prefix = interaction.guild ? await getPrefix(interaction.guild.id) : instanceConfig().defaultPrefix; const query = interaction.options.getString("query")?.toLowerCase().trim(); const surface = "slash"; diff --git a/src/config/constants.ts b/src/config/constants.ts index 4117291dc..b9cf56f2c 100644 --- a/src/config/constants.ts +++ b/src/config/constants.ts @@ -85,7 +85,7 @@ export const TICKET = { closeDelayMs: 5 * SECOND_MS, } as const; -export { DEFAULT_PREFIX, TREASURE_DEFAULTS } from "@testify/shared"; +export { TREASURE_DEFAULTS } from "@testify/shared"; export const COUNTING_DEFAULT_MAX = 1_000_000; diff --git a/src/config/env.ts b/src/config/env.ts index 945688ad4..a9658d9b9 100644 --- a/src/config/env.ts +++ b/src/config/env.ts @@ -79,6 +79,9 @@ const fields = z.object({ // Support assistant. Without a key it answers by search alone and never contacts anybody. SUPPORT_AI_API_KEY: z.string().min(1).optional(), SUPPORT_AI_MODEL: z.string().min(1).default("claude-opus-5"), + + // Where `testify.config.json` is, when it is not beside `.env`. Only docker-compose.yml sets it. + TESTIFY_CONFIG: z.string().min(1).optional(), }); /** Every variable name, so the support assistant can refuse to repeat one. */ diff --git a/src/config/instance.ts b/src/config/instance.ts new file mode 100644 index 000000000..5a26fe655 --- /dev/null +++ b/src/config/instance.ts @@ -0,0 +1,181 @@ +import { readFileSync, statSync } from "node:fs"; +import { basename, resolve } from "node:path"; +import { z } from "zod"; +import { type Env } from "@config/env"; +import { + contactHref, + DEFAULT_PREFIX, + type InstanceOperator, + plainLine, + prefixText, + repositoryCoordinates, +} from "@testify/shared"; + +/** What makes a copy of the bot somebody's own, read from `testify.config.json` beside `.env`. Nothing here is secret. */ + +export interface InstanceConfig { + repository: string; + supportServer: string | null; + developer: string; + operator: InstanceOperator | null; + defaultPrefix: string; + greetInviter: boolean; +} + +export const INSTANCE_DEFAULTS: Readonly = Object.freeze({ + repository: "https://github.com/Kkkermit/Testify", + supportServer: "https://discord.gg/xcMVwAVjSD", + developer: "Kkermit", + operator: null, + defaultPrefix: DEFAULT_PREFIX, + greetInviter: true, +}); + +const httpsLink = z + .string() + .trim() + .max(200, "is too long") + .regex(/^https:\/\/[^\s<>"]+$/, "should be an https:// link"); + +const repository = httpsLink + .refine( + (value) => repositoryCoordinates(value) !== null, + "should be a GitHub repository, like https://github.com/you/your-fork", + ) + .transform((value) => { + const { owner, repo } = repositoryCoordinates(value) ?? { owner: "", repo: "" }; + return `https://github.com/${owner}/${repo}`; + }); + +const contact = z + .string() + .trim() + .max(200, "is too long") + .refine((value) => contactHref(value) !== null, "should be an email address or an https:// link"); + +export const instanceFileSchema = z.strictObject({ + $schema: z.string().optional(), + repository: repository + .describe( + "Your copy's GitHub repository. The website's source browser shows it, and the bot's Source code buttons open it.", + ) + .optional(), + supportServer: z + .union([z.null(), httpsLink]) + .describe("Where the bot's Support buttons lead, such as a Discord invite. null hides them.") + .optional(), + developer: plainLine(1, 64).describe("Who /bot info names as the developer.").optional(), + operator: z + .strictObject({ + name: plainLine(1, 100).describe("A person or an organisation."), + contact: contact.describe("An email address or an https:// page."), + }) + .nullable() + .describe("Who runs this copy and how to reach them, shown on the privacy notice and the terms.") + .optional(), + defaultPrefix: prefixText + .describe("The prefix a server starts with until it picks its own. Up to 8 characters, with no spaces.") + .optional(), + greetInviter: z + .boolean() + .describe("Sends whoever adds the bot to a server a direct message on how to get started.") + .optional(), +}); + +export interface InstanceFile { + name: string; + path: string; + exists: boolean; +} + +/** Beside `.env`, as `npm run dev` reads `.env.development`; `TESTIFY_CONFIG` names another place, as Docker does. */ +export function instanceFile(env: Pick): InstanceFile { + const given = + env.TESTIFY_CONFIG ?? (env.NODE_ENV === "development" ? "testify.config.development.json" : "testify.config.json"); + const path = resolve(process.cwd(), given); + + // A folder is not the file, which is what Docker leaves where it was asked to mount one that did not exist. + return { name: basename(given), path, exists: statSync(path, { throwIfNoEntry: false })?.isFile() ?? false }; +} + +interface InstanceProblem { + key: string; + message: string; +} + +export class InstanceError extends Error { + readonly file: InstanceFile; + readonly problems: InstanceProblem[]; + + constructor(file: InstanceFile, problems: InstanceProblem[]) { + const lines = problems.map((problem) => ` ${problem.key} ${problem.message}`).join("\n"); + super(`Your ${file.name} file needs attention:\n\n${lines}`); + this.name = "InstanceError"; + this.file = file; + this.problems = problems; + } +} + +function problemsOf(error: z.ZodError): InstanceProblem[] { + return error.issues.map((issue): InstanceProblem => { + if (issue.code === "unrecognized_keys") { + const where = issue.path.length === 0 ? "" : `${issue.path.join(".")}.`; + return { key: issue.keys.map((key) => `${where}${key}`).join(", "), message: "is not a setting this bot has" }; + } + return { key: issue.path.join("."), message: issue.message }; + }); +} + +/** Reads the file once; the result is fixed for the run, because nothing it decides may change under a live bot. */ +export function readInstance(file: InstanceFile): InstanceConfig { + if (!file.exists) return INSTANCE_DEFAULTS; + + let raw: unknown; + try { + raw = JSON.parse(readFileSync(file.path, "utf8")); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new InstanceError(file, [{ key: file.name, message: `is not valid JSON: ${reason}` }]); + } + + const result = instanceFileSchema.safeParse(raw); + if (!result.success) throw new InstanceError(file, problemsOf(result.error)); + + const given = Object.fromEntries( + Object.entries(result.data).filter(([key, value]) => key !== "$schema" && value !== undefined), + ); + return Object.freeze({ ...INSTANCE_DEFAULTS, ...given }); +} + +let loaded: InstanceConfig | null = null; + +export function loadInstance(env: Pick): InstanceConfig { + loaded = readInstance(instanceFile(env)); + return loaded; +} + +/** The defaults until start-up has read the file, which is what the tests and the scripts see. */ +export function instanceConfig(): InstanceConfig { + return loaded ?? INSTANCE_DEFAULTS; +} + +/** Used by the tests, to run as a host whose file says something else. */ +export function useInstance(config: InstanceConfig | null): void { + loaded = config; +} + +/** Used by the tests, so one case's config never reaches the next. */ +export function resetInstance(): void { + loaded = null; +} + +/** What `testify.config.schema.json` holds, so an editor completes and checks the file as it is typed. */ +export function instanceJsonSchema(): Record { + const { $schema, ...rest } = z.toJSONSchema(instanceFileSchema, { io: "input", unrepresentable: "any" }); + return { + $schema, + title: "testify.config.json", + description: "What makes this copy of the bot your own. Every setting is optional; docs/customising.md lists them.", + ...rest, + }; +} diff --git a/src/config/theme.ts b/src/config/theme.ts index 4cae3bf54..dd5cdaca6 100644 --- a/src/config/theme.ts +++ b/src/config/theme.ts @@ -2,10 +2,6 @@ import { type ColorResolvable } from "discord.js"; import { CATEGORIES, type Category } from "@config/categories"; export const theme = { - author: "Kkermit", - repository: "https://github.com/Kkkermit/Testify", - supportServer: "https://discord.gg/xcMVwAVjSD", - /** The only place a colour is written. Everything else names one of these. */ colours: { default: "Blurple", diff --git a/src/database/models/prefix.schema.ts b/src/database/models/prefix.schema.ts index 6db697fd4..4c856e129 100644 --- a/src/database/models/prefix.schema.ts +++ b/src/database/models/prefix.schema.ts @@ -1,9 +1,9 @@ import { model, Schema } from "mongoose"; -import { DEFAULT_PREFIX } from "@config/constants"; export interface PrefixSettings { guildId: string; - prefix: string; + /** Absent until a server picks one, so it follows the default prefix in `testify.config.json`. */ + prefix?: string; /** Prefix commands can be switched off per server; slash commands always work. */ isEnabled: boolean; createdAt: Date; @@ -13,7 +13,7 @@ export interface PrefixSettings { const prefixSchema = new Schema( { guildId: { type: String, required: true, unique: true }, - prefix: { type: String, required: true, default: DEFAULT_PREFIX }, + prefix: { type: String }, isEnabled: { type: Boolean, required: true, default: true }, }, { timestamps: true }, diff --git a/src/database/repositories/prefixRepository.ts b/src/database/repositories/prefixRepository.ts index 5173af21c..667e77a6d 100644 --- a/src/database/repositories/prefixRepository.ts +++ b/src/database/repositories/prefixRepository.ts @@ -1,4 +1,5 @@ -import { CACHE, DEFAULT_PREFIX } from "@config/constants"; +import { CACHE } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { GuildPrefix, type PrefixSettings } from "@database/models/prefix.schema"; const UPSERT = { upsert: true as const, new: true as const, lean: true as const, setDefaultsOnInsert: true as const }; @@ -24,7 +25,7 @@ export async function getPrefixConfig(guildId: string): Promise { const record = await GuildPrefix.findOne({ guildId }).lean().exec(); return remember(guildId, { - prefix: record?.prefix ?? DEFAULT_PREFIX, + prefix: record?.prefix ?? instanceConfig().defaultPrefix, // A server that has never touched the setting gets prefix commands on. isEnabled: record?.isEnabled ?? true, }); @@ -34,10 +35,10 @@ export async function getPrefix(guildId: string): Promise { return (await getPrefixConfig(guildId)).prefix; } +/** The default is stored as nothing, so a server that is on it moves when the host changes it. */ export async function setPrefix(guildId: string, prefix: string): Promise { - const record = await GuildPrefix.findOneAndUpdate({ guildId }, { $set: { prefix } }, UPSERT) - .lean() - .exec(); + const update = prefix === instanceConfig().defaultPrefix ? { $unset: { prefix: 1 } } : { $set: { prefix } }; + const record = await GuildPrefix.findOneAndUpdate({ guildId }, update, UPSERT).lean().exec(); remember(guildId, { prefix, isEnabled: record?.isEnabled ?? true }); return prefix; @@ -48,7 +49,7 @@ export async function setPrefixEnabled(guildId: string, isEnabled: boolean): Pro .lean() .exec(); - return remember(guildId, { prefix: record?.prefix ?? DEFAULT_PREFIX, isEnabled }); + return remember(guildId, { prefix: record?.prefix ?? instanceConfig().defaultPrefix, isEnabled }); } /** Used by the tests, and after a prefix is changed elsewhere. */ diff --git a/src/events/create/guildCreate.event.ts b/src/events/create/guildCreate.event.ts index 96222f592..2b2420585 100644 --- a/src/events/create/guildCreate.event.ts +++ b/src/events/create/guildCreate.event.ts @@ -1,10 +1,11 @@ import { Events, type Guild } from "discord.js"; import { defineEvent } from "@core/event"; -import { announceGuildChange } from "@lib/bot"; +import { announceGuildChange, greetInviter } from "@lib/bot"; export default defineEvent({ name: Events.GuildCreate, async run(client, guild: Guild) { - await announceGuildChange(client, guild, "joined"); + // Neither waits on the other: the log post and the getting-started message are separate jobs. + await Promise.all([announceGuildChange(client, guild, "joined"), greetInviter(client, guild)]); }, }); diff --git a/src/events/message/mentionReply.event.ts b/src/events/message/mentionReply.event.ts index 2b418782e..bdfb5eb48 100644 --- a/src/events/message/mentionReply.event.ts +++ b/src/events/message/mentionReply.event.ts @@ -1,9 +1,9 @@ -import { DEFAULT_PREFIX } from "@config/constants"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { botName } from "@core/brand"; import { defineMessageHandler } from "@core/message"; import { getPrefix } from "@database/repositories/prefixRepository"; -import { embed, linkButton, row } from "@lib/discord"; +import { projectLinkButtons } from "@lib/bot"; +import { embed, row } from "@lib/discord"; /** Replies when someone mentions the bot on its own, and nothing else. */ export default defineMessageHandler({ @@ -14,7 +14,7 @@ export default defineMessageHandler({ if (botId === undefined) return; if (!new RegExp(`^<@!?${botId}>$`).test(message.content.trim())) return; - const prefix = message.guild === null ? DEFAULT_PREFIX : await getPrefix(message.guild.id); + const prefix = message.guild === null ? instanceConfig().defaultPrefix : await getPrefix(message.guild.id); await message.reply({ embeds: [ @@ -25,7 +25,7 @@ export default defineMessageHandler({ thumbnail: client.user?.displayAvatarURL(), }), ], - components: [row(linkButton("Source code", theme.repository), linkButton("Support", theme.supportServer))], + components: [row(...projectLinkButtons("Support"))], }); return true; diff --git a/src/events/message/prefixCommands.event.ts b/src/events/message/prefixCommands.event.ts index 1247fd62b..b85b17a88 100644 --- a/src/events/message/prefixCommands.event.ts +++ b/src/events/message/prefixCommands.event.ts @@ -1,4 +1,4 @@ -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { botName } from "@core/brand"; import { runChecks } from "@core/checks"; import { runCommand } from "@core/errors"; @@ -20,7 +20,9 @@ export default defineMessageHandler({ // A direct message has no server to have configured anything. const config = - message.guild === null ? { prefix: DEFAULT_PREFIX, isEnabled: true } : await getPrefixConfig(message.guild.id); + message.guild === null + ? { prefix: instanceConfig().defaultPrefix, isEnabled: true } + : await getPrefixConfig(message.guild.id); if (!config.isEnabled) return; diff --git a/src/events/ready/ready.event.ts b/src/events/ready/ready.event.ts index a519f038b..6c52381b6 100644 --- a/src/events/ready/ready.event.ts +++ b/src/events/ready/ready.event.ts @@ -1,5 +1,6 @@ import { ActivityType, type Client, Events } from "discord.js"; -import { DEFAULT_PREFIX, INTERVALS } from "@config/constants"; +import { INTERVALS } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { type TestifyClient } from "@core/client"; import { defineEvent } from "@core/event"; import { publishScope } from "@core/loader"; @@ -9,7 +10,7 @@ export default defineEvent({ name: Events.ClientReady, once: true, run(client, ready: Client) { - printBanner(client, ready, DEFAULT_PREFIX, publishScope(client), client.loaded); + printBanner(client, ready, instanceConfig().defaultPrefix, publishScope(client), client.loaded); ready.user.setStatus("online"); rotatePresence(client, ready); diff --git a/src/index.ts b/src/index.ts index 85cb1ced1..c797cb529 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,7 @@ import { startApi } from "@api/server"; import { dashboardBuilt } from "@api/static"; import { envFile, loadEnv } from "@config/env"; +import { instanceFile, loadInstance } from "@config/instance"; import { botName } from "@core/brand"; import { TestifyClient } from "@core/client"; import { loadEverything, publishCommands, publishScope } from "@core/loader"; @@ -23,6 +24,8 @@ import { BOT_FEATURE_KEYS, BOT_FEATURES, switchedOff } from "@testify/shared"; async function main(): Promise { const env = loadEnv(); + const instance = instanceFile(env); + loadInstance(env); // A development bot always prints readable lines, even through `npm run dev:all`'s pipe. const logger = createLogger(env.LOG_LEVEL, process.stdout.isTTY === true || env.NODE_ENV === "development"); @@ -44,7 +47,7 @@ async function main(): Promise { `${process.version} is older than the ${MINIMUM_NODE} this is tested on — update Node`, ); } - report.note("done", "Settings", `read from ${envFile().name}`); + report.note("done", "Settings", `read from ${envFile().name}${instance.exists ? ` and ${instance.name}` : ""}`); const { pulled } = switchedOff(env.DISABLED_FEATURES); if (client.featuresOff.size > 0) { diff --git a/src/lib/bot/banner.util.ts b/src/lib/bot/banner.util.ts index 16e29f3b5..2019985a3 100644 --- a/src/lib/bot/banner.util.ts +++ b/src/lib/bot/banner.util.ts @@ -1,5 +1,5 @@ import { type Client } from "discord.js"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { botName } from "@core/brand"; import { type TestifyClient } from "@core/client"; import { colourEnabled } from "@core/terminal"; @@ -135,7 +135,7 @@ export function bannerLines(facts: BannerFacts, colour: boolean): string[] { fact(ICONS.messages, "Messages", `${formatNumber(facts.loaded.messageHandlers)} loaded`), "", ...(facts.watching ? [` ${paint(ansi.yellow, RELOAD_GLYPH)} ${paint(ansi.bold, "Hot reload is on")}`, ""] : []), - paint(ansi.grey, ` ${theme.repository}`), + paint(ansi.grey, ` ${instanceConfig().repository}`), "", ]; } diff --git a/src/lib/bot/botIdentity.util.ts b/src/lib/bot/botIdentity.util.ts index 59e077524..c2898373b 100644 --- a/src/lib/bot/botIdentity.util.ts +++ b/src/lib/bot/botIdentity.util.ts @@ -1,5 +1,5 @@ import { type APIUser, type ClientUser, Routes } from "discord.js"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { botName } from "@core/brand"; import { type TestifyClient } from "@core/client"; import { toError } from "@core/errors"; @@ -36,8 +36,8 @@ export function identityOf(user: ClientUser): BotIdentity { avatarUrl: user.displayAvatarURL({ size: SIZE }), bannerUrl: user.bannerURL({ size: 1024 }) ?? null, accentColour: hexOf(user.accentColor), - supportUrl: theme.supportServer, - repositoryUrl: theme.repository, + supportUrl: instanceConfig().supportServer, + repositoryUrl: instanceConfig().repository, }; } @@ -60,8 +60,8 @@ async function connectingIdentity(client: TestifyClient, now: number): Promise entry.targetId === botId && now - entry.createdTimestamp <= FRESH_MS) + .sort((a, b) => b.createdTimestamp - a.createdTimestamp)[0]; + return newest?.executorId ?? null; +} + +interface FindOptions { + wait?: (ms: number) => Promise; + now?: () => number; +} + +/** + * Who added the bot. An invite link, the Add App button and the App Directory all write the same audit entry; the + * integration records it too, for a bot that was not given View Audit Log; the owner is the last resort. + */ +export async function findInviter( + guild: Guild, + botId: string, + { wait = sleep, now = Date.now }: FindOptions = {}, +): Promise<{ user: User; source: InviterSource } | null> { + const me = guild.members.me; + + if (me?.permissions.has(PermissionFlagsBits.ViewAuditLog) === true) { + for (const delay of [0, AUDIT_RETRY_MS]) { + if (delay > 0) await wait(delay); + // A refusal here falls through to the next way of telling, so it is not an error worth more than that. + const logs = await guild.fetchAuditLogs({ type: AuditLogEvent.BotAdd, limit: 5 }).catch(() => null); + const id = logs === null ? null : pickBotAdd([...logs.entries.values()], botId, now()); + // The entry may carry a partial user, so the one written to is fetched whole. + const user = id === null ? null : await guild.client.users.fetch(id).catch(() => null); + if (user !== null) return { user, source: "audit log" }; + } + } + + if (me?.permissions.has(PermissionFlagsBits.ManageGuild) === true) { + const integrations = await guild.fetchIntegrations().catch(() => null); + const user = integrations?.find((integration) => integration.account.id === botId)?.user ?? null; + if (user !== null) return { user, source: "integration" }; + } + + const owner = await guild.fetchOwner().catch(() => null); + return owner === null ? null : { user: owner.user, source: "owner" }; +} + +export interface GreetingFacts { + bot: string; + server: string; + prefix: string; + /** The server's overview on the dashboard, where its setup checklist is; null when the dashboard is off. */ + setupUrl: string | null; +} + +export function inviterGreeting(facts: GreetingFacts): MessageCreateOptions { + const server = escapeMarkdown(facts.server); + const setUp = + facts.setupUrl === null + ? "**Set it up** — every feature has a setup command, and `/help` lists them by category." + : "**Set it up** — the dashboard's setup checklist picks channels for welcomes, logs and more in a few clicks."; + + const lines = [ + "Here's how to get going:", + "", + `**See what it can do** — \`/help\`, or \`${facts.prefix}help\` in any channel.`, + setUp, + `**Change the prefix** — \`/prefix\`, if \`${facts.prefix}\` clashes with another bot.`, + "", + `-# You're getting this because you added ${facts.bot} to ${server}.`, + ]; + const buttons = [ + ...(facts.setupUrl === null ? [] : [linkButton("Set up the server", facts.setupUrl)]), + ...projectLinkButtons(), + ]; + + return { + embeds: [ + embed({ + category: "info", + title: `Thanks for adding ${facts.bot} to ${facts.server}`, + description: lines.join("\n"), + }), + ], + components: [row(...buttons)], + }; +} + +/** One direct message to whoever added the bot; closed DMs are their choice, so nothing about this can fail the join. */ +export async function greetInviter(client: TestifyClient, guild: Guild, options: FindOptions = {}): Promise { + const botId = client.user?.id; + if (botId === undefined || !instanceConfig().greetInviter) return; + + const found = await findInviter(guild, botId, options); + if (found === null || found.user.bot || (await findBlacklistEntry(found.user.id)) !== null) return; + + const dashboard = dashboardUrl(client.env); + const message = inviterGreeting({ + bot: botName(), + server: guild.name, + prefix: await getPrefix(guild.id), + setupUrl: dashboard === null ? null : `${dashboard}/guilds/${guild.id}`, + }); + + try { + await found.user.send(message); + client.logger.debug({ guildId: guild.id, source: found.source }, "[GUILD] Sent the getting-started message."); + } catch (error) { + const closed = error instanceof DiscordAPIError && error.code === RESTJSONErrorCodes.CannotSendMessagesToThisUser; + if (closed) { + client.logger.debug({ guildId: guild.id }, "[GUILD] Whoever added the bot has their direct messages closed."); + } else { + client.logger.warn( + { err: toError(error), guildId: guild.id }, + "[GUILD] Could not send the getting-started message. The bot joined normally.", + ); + } + } +} diff --git a/src/lib/bot/projectLinks.util.ts b/src/lib/bot/projectLinks.util.ts new file mode 100644 index 000000000..d854daaa0 --- /dev/null +++ b/src/lib/bot/projectLinks.util.ts @@ -0,0 +1,11 @@ +import { type ButtonBuilder } from "discord.js"; +import { instanceConfig } from "@config/instance"; +import { linkButton } from "@lib/discord/components.util"; + +/** Source code, then Support unless the host has no support server, from the copy's own config. */ +export function projectLinkButtons(support = "Support server"): ButtonBuilder[] { + const { repository, supportServer } = instanceConfig(); + const source = linkButton("Source code", repository); + + return supportServer === null ? [source] : [source, linkButton(support, supportServer)]; +} diff --git a/src/lib/bot/runtime.util.ts b/src/lib/bot/runtime.util.ts index bf2a88e22..43a57b386 100644 --- a/src/lib/bot/runtime.util.ts +++ b/src/lib/bot/runtime.util.ts @@ -1,7 +1,7 @@ import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import { version as discordVersion } from "discord.js"; -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { type TestifyClient } from "@core/client"; import { repoRoot } from "@core/paths"; import { type RuntimeInfo } from "@testify/shared"; @@ -47,7 +47,7 @@ export function runtimeInfo(client: TestifyClient, now = Date.now()): RuntimeInf rss: Math.round(memory.rss / MB), }, // Linked rather than checked: a bot that calls home on a timer is not something to ship by default. - repositoryUrl: theme.repository, + repositoryUrl: instanceConfig().repository, commands: client.commands.size, events: client.eventNames().length, guilds: client.guilds.cache.size, diff --git a/src/lib/bot/startup.util.ts b/src/lib/bot/startup.util.ts index d8959500a..b489e349d 100644 --- a/src/lib/bot/startup.util.ts +++ b/src/lib/bot/startup.util.ts @@ -1,5 +1,6 @@ import { type Client, DiscordAPIError, Events, HTTPError } from "discord.js"; import { EnvError, type EnvFile } from "@config/env"; +import { InstanceError } from "@config/instance"; import { SetupError } from "@core/errors"; import { badge, box, colourEnabled, type Paint, painter, stepLine, type StepState, type Tone } from "@core/terminal"; @@ -137,6 +138,26 @@ function fixEnv(file: EnvFile, paint: Paint): string[] { ]; } +function instanceFailure(error: InstanceError, paint: Paint): StartupFailure { + const width = Math.max(...error.problems.map((problem) => problem.key.length)); + const count = error.problems.length === 1 ? "one change" : "a few changes"; + + return { + title: "The config file needs attention", + tone: "warning", + lines: [ + `${paint.bold(error.file.name)} needs ${count}:`, + "", + ...error.problems.map( + (problem) => ` ${paint.yellow("•")} ${paint.bold(problem.key.padEnd(width))} ${problem.message}`, + ), + "", + `${paint.cyan("➜")} Fix it, or delete it to use the built-in settings.`, + ` ${paint.bold("docs/customising.md")} explains every setting.`, + ], + }; +} + function discordFailure(error: DiscordAPIError): StartupFailure | null { if (error.status === 401) return FATAL_CLOSE_CODES[4004] ?? null; @@ -239,6 +260,7 @@ function unreachableFailure(error: unknown): StartupFailure | null { /** Turns anything start-up can throw into a titled explanation, keeping the stack only for real bugs. */ export function explainStartupFailure(error: unknown, paint: Paint = painter()): StartupFailure { if (error instanceof EnvError) return envFailure(error, paint); + if (error instanceof InstanceError) return instanceFailure(error, paint); if (error instanceof SetupError) return { title: "The bot could not start", tone: "error", lines: error.message.split("\n") }; diff --git a/src/lib/info/helpPages.util.ts b/src/lib/info/helpPages.util.ts index 305db47d7..15d72ca89 100644 --- a/src/lib/info/helpPages.util.ts +++ b/src/lib/info/helpPages.util.ts @@ -13,7 +13,8 @@ import { customId } from "@core/button"; import { type TestifyClient } from "@core/client"; import { type Command, subcommandsOf } from "@core/command"; import { dashboardUrl } from "@lib/bot/dashboard.util"; -import { button, linkButton, row, select, selectRow } from "@lib/discord/components.util"; +import { projectLinkButtons } from "@lib/bot/projectLinks.util"; +import { button, row, select, selectRow } from "@lib/discord/components.util"; import { embed } from "@lib/discord/embeds.util"; import { truncate } from "@lib/format/format.util"; import { HELP_HOME } from "@lib/info/info.constants"; @@ -233,7 +234,7 @@ export function categoryControls( } export function helpLinks() { - return row(linkButton("Support server", theme.supportServer), linkButton("Source code", theme.repository)); + return row(...projectLinkButtons()); } export function resolveCategory(value: string): Category | null { diff --git a/src/lib/settings/prefixPanel.util.ts b/src/lib/settings/prefixPanel.util.ts index 8374271f6..796937414 100644 --- a/src/lib/settings/prefixPanel.util.ts +++ b/src/lib/settings/prefixPanel.util.ts @@ -1,4 +1,4 @@ -import { DEFAULT_PREFIX } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { type ContainerMessage } from "@lib/discord/discord.types"; import { PREFIX_LIMITS, PREFIX_PANEL_ID } from "@lib/settings/settings.constants"; import { type PrefixPanelState } from "@lib/settings/settings.types"; @@ -35,7 +35,11 @@ export function prefixPanel(state: PrefixPanelState, ownerId: string): Container ], actions: [ switchAction(state.isEnabled), - { action: "reset", label: `Reset to ${DEFAULT_PREFIX}`, disabled: state.prefix === DEFAULT_PREFIX }, + { + action: "reset", + label: `Reset to ${instanceConfig().defaultPrefix}`, + disabled: state.prefix === instanceConfig().defaultPrefix, + }, ], footer: "Mentioning the bot works as a prefix too, whatever this is set to.", }); diff --git a/src/lib/support/supportDesk.util.ts b/src/lib/support/supportDesk.util.ts index 25859c569..43206318a 100644 --- a/src/lib/support/supportDesk.util.ts +++ b/src/lib/support/supportDesk.util.ts @@ -1,4 +1,4 @@ -import { theme } from "@config/theme"; +import { instanceConfig } from "@config/instance"; import { botName } from "@core/brand"; import { type TestifyClient } from "@core/client"; import { toError } from "@core/errors"; @@ -256,7 +256,7 @@ function buildEntries(client: TestifyClient, secrets: readonly string[]): Suppor } export function supportContext(prefix: string): SupportContext { - return { bot: botName(), prefix, repository: theme.repository }; + return { bot: botName(), prefix, repository: instanceConfig().repository }; } let desk: SupportDesk | null = null; diff --git a/src/lib/support/supportFacts.util.ts b/src/lib/support/supportFacts.util.ts index b00e779b0..55cbdd76a 100644 --- a/src/lib/support/supportFacts.util.ts +++ b/src/lib/support/supportFacts.util.ts @@ -1,15 +1,6 @@ import { PermissionsBitField } from "discord.js"; -import { - AFK, - DAY_MS, - DEFAULT_PREFIX, - ECONOMY, - ECONOMY_COOLDOWNS, - HOUR_MS, - LEVELLING, - MINUTE_MS, - TICKET, -} from "@config/constants"; +import { AFK, DAY_MS, ECONOMY, ECONOMY_COOLDOWNS, HOUR_MS, LEVELLING, MINUTE_MS, TICKET } from "@config/constants"; +import { instanceConfig } from "@config/instance"; import { ANSWER_EVERY_MS } from "@lib/autoResponders/autoResponders.util"; import { CASINO_TIMING } from "@lib/casino/casino.constants"; import { COINFLIP_RETURN, DICE_RETURNS } from "@lib/casino/chance.util"; @@ -43,7 +34,10 @@ import { /** Every number an article quotes, read from the code, so an article cannot state a limit the bot no longer has. */ export const FACTS: Readonly> = { - "prefix.default": DEFAULT_PREFIX, + // Read when an article is filled, because the host's config is loaded after this module is. + get "prefix.default"(): string { + return instanceConfig().defaultPrefix; + }, "prefix.maxLength": formatNumber(SETTINGS_LIMITS.maxPrefix), "invite.permissions": new PermissionsBitField(BigInt(INVITE_PERMISSIONS)) .toArray() diff --git a/testify.config.example.json b/testify.config.example.json new file mode 100644 index 000000000..9bc22f2ae --- /dev/null +++ b/testify.config.example.json @@ -0,0 +1,9 @@ +{ + "$schema": "./testify.config.schema.json", + "repository": "https://github.com/Kkkermit/Testify", + "supportServer": "https://discord.gg/xcMVwAVjSD", + "developer": "Kkermit", + "operator": null, + "defaultPrefix": "t?", + "greetInviter": true +} diff --git a/testify.config.schema.json b/testify.config.schema.json new file mode 100644 index 000000000..6ae084044 --- /dev/null +++ b/testify.config.schema.json @@ -0,0 +1,44 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "testify.config.json", + "description": "What makes this copy of the bot your own. Every setting is optional; docs/customising.md lists them.", + "type": "object", + "properties": { + "$schema": { "type": "string" }, + "repository": { + "description": "Your copy's GitHub repository. The website's source browser shows it, and the bot's Source code buttons open it.", + "type": "string", + "maxLength": 200, + "pattern": "^https:\\/\\/[^\\s<>\"]+$" + }, + "supportServer": { + "anyOf": [{ "type": "null" }, { "type": "string", "maxLength": 200, "pattern": "^https:\\/\\/[^\\s<>\"]+$" }], + "description": "Where the bot's Support buttons lead, such as a Discord invite. null hides them." + }, + "developer": { "description": "Who /bot info names as the developer.", "type": "string" }, + "operator": { + "anyOf": [ + { + "type": "object", + "properties": { + "name": { "description": "A person or an organisation.", "type": "string" }, + "contact": { "type": "string", "maxLength": 200, "description": "An email address or an https:// page." } + }, + "required": ["name", "contact"], + "additionalProperties": false + }, + { "type": "null" } + ], + "description": "Who runs this copy and how to reach them, shown on the privacy notice and the terms." + }, + "defaultPrefix": { + "description": "The prefix a server starts with until it picks its own. Up to 8 characters, with no spaces.", + "type": "string" + }, + "greetInviter": { + "type": "boolean", + "description": "Sends whoever adds the bot to a server a direct message on how to get started." + } + }, + "additionalProperties": false +} diff --git a/tests/api/site.test.ts b/tests/api/site.test.ts index 0857c3533..c0d444398 100644 --- a/tests/api/site.test.ts +++ b/tests/api/site.test.ts @@ -1,7 +1,7 @@ import { gitHubAdvice } from "@api/routes/site"; import { createApi } from "@api/server"; import { type Env } from "@config/env"; -import { theme } from "@config/theme"; +import { INSTANCE_DEFAULTS, useInstance } from "@config/instance"; import { ServiceError } from "@core/errors"; import { fetchJson } from "@lib/infra/http.util"; import { type ApiErrorBody, type SiteInfo } from "@testify/shared"; @@ -36,7 +36,7 @@ function github(repo: object | Error): void { } const repo = (isPrivate = false) => ({ - html_url: theme.repository, + html_url: INSTANCE_DEFAULTS.repository, full_name: "owner/bot", description: null, private: isPrivate, @@ -61,9 +61,19 @@ describe("GET /api/site", () => { const off = (await (await api(false).request("/api/site")).json()) as SiteInfo; const on = (await (await api(true).request("/api/site")).json()) as SiteInfo; - expect(off).toMatchObject({ dashboard: false, repository: theme.repository }); + expect(off).toMatchObject({ dashboard: false, repository: INSTANCE_DEFAULTS.repository, operator: null }); expect(on.dashboard).toBe(true); }); + + /** The privacy notice tells people to ask the operator, so it has to be able to say who that is. */ + it("names who runs this copy and its default prefix, from the config file", async () => { + const operator = { name: "Sam's Servers", contact: "privacy@example.com" }; + useInstance({ ...INSTANCE_DEFAULTS, operator, defaultPrefix: "!" }); + + const info = (await (await api(false).request("/api/site")).json()) as SiteInfo; + + expect(info).toMatchObject({ operator, defaultPrefix: "!" }); + }); }); describe("the source browser's routes", () => { diff --git a/tests/config/instance.test.ts b/tests/config/instance.test.ts new file mode 100644 index 000000000..27498ff86 --- /dev/null +++ b/tests/config/instance.test.ts @@ -0,0 +1,144 @@ +import { mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, relative, resolve } from "node:path"; +import { + INSTANCE_DEFAULTS, + InstanceError, + instanceFile, + type InstanceFile, + instanceJsonSchema, + readInstance, +} from "@config/instance"; + +const ROOT = resolve(__dirname, "../.."); + +function fileWith(contents: string): InstanceFile { + const path = join(mkdtempSync(join(tmpdir(), "testify-config-")), "testify.config.json"); + writeFileSync(path, contents, "utf8"); + return { name: "testify.config.json", path, exists: true }; +} + +const json = (value: unknown): InstanceFile => fileWith(JSON.stringify(value)); + +function problemsIn(file: InstanceFile): string[] { + try { + readInstance(file); + return []; + } catch (error) { + return error instanceof InstanceError ? error.problems.map((problem) => `${problem.key} ${problem.message}`) : []; + } +} + +describe("the instance config file", () => { + it("is optional, and a copy without one keeps the original's links and prefix", () => { + expect(readInstance({ name: "testify.config.json", path: "/nowhere", exists: false })).toEqual(INSTANCE_DEFAULTS); + }); + + it("keeps the defaults for whatever it leaves out, and tidies a repository address", () => { + const config = readInstance( + json({ + $schema: "./testify.config.schema.json", + repository: "https://github.com/someone/fork.git/", + supportServer: null, + operator: { name: "Sam's Servers", contact: "privacy@example.com" }, + defaultPrefix: "!", + }), + ); + + expect(config).toEqual({ + ...INSTANCE_DEFAULTS, + repository: "https://github.com/someone/fork", + supportServer: null, + operator: { name: "Sam's Servers", contact: "privacy@example.com" }, + defaultPrefix: "!", + }); + }); + + /** A typo in a key would otherwise do nothing at all, silently, which is the worst way for a setting to fail. */ + it("names every problem at once, unknown keys included, so one start fixes them all", () => { + const problems = problemsIn( + json({ + supportserver: "https://discord.gg/x", + repository: "https://gitlab.com/someone/fork", + operator: { name: "Sam", contact: "javascript:alert(1)" }, + defaultPrefix: "t ?", + greetInviter: "yes", + }), + ); + + expect(problems).toEqual( + expect.arrayContaining([ + "supportserver is not a setting this bot has", + expect.stringMatching(/^repository should be a GitHub repository/), + expect.stringMatching(/^operator\.contact should be an email address or an https/), + "defaultPrefix cannot contain a space", + expect.stringMatching(/^greetInviter /), + ]), + ); + expect(problems).toHaveLength(5); + }); + + it("says a file that is not JSON is not JSON, rather than failing somewhere later", () => { + expect(problemsIn(fileWith("{ repository: oops }"))).toEqual([expect.stringMatching(/is not valid JSON/)]); + }); + + /** Mounting a file that does not exist makes Docker create a folder there, which must read as no file. */ + it("reads a folder in the file's place as no file", () => { + const folder = mkdtempSync(join(tmpdir(), "testify-config-")); + mkdirSync(join(folder, "testify.config.json")); + const cwd = jest.spyOn(process, "cwd").mockReturnValue(folder); + + expect(instanceFile({ NODE_ENV: "production", TESTIFY_CONFIG: undefined }).exists).toBe(false); + cwd.mockRestore(); + }); + + it("is read beside .env, as the development file under npm run dev, and wherever Docker points", () => { + const names = [ + instanceFile({ NODE_ENV: "production", TESTIFY_CONFIG: undefined }).name, + instanceFile({ NODE_ENV: "development", TESTIFY_CONFIG: undefined }).name, + instanceFile({ NODE_ENV: "production", TESTIFY_CONFIG: "/app/instance/testify.config.json" }).path, + ]; + + expect(names).toEqual([ + "testify.config.json", + "testify.config.development.json", + resolve("/app/instance/testify.config.json"), + ]); + }); + + it("ships an example that changes nothing when copied as it is", () => { + const example = { name: "example", path: join(ROOT, "testify.config.example.json"), exists: true }; + + expect(readInstance(example)).toEqual(INSTANCE_DEFAULTS); + }); + + /** The schema is what an editor checks the file against, so it has to follow the bot's own rules. */ + it("keeps testify.config.schema.json in step with the schema the bot reads with; npm run config:schema rewrites it", () => { + expect(JSON.parse(readFileSync(join(ROOT, "testify.config.schema.json"), "utf8"))).toEqual(instanceJsonSchema()); + }); +}); + +/** Every self-hosted copy linked its users to the original's support server, because the links were written in code. */ +describe("what a host sets in the file", () => { + function sources(directory: string): string[] { + return readdirSync(directory).flatMap((name) => { + const path = join(directory, name); + if (statSync(path).isDirectory()) return sources(path); + return /\.tsx?$/.test(name) ? [path] : []; + }); + } + + const OWNED_BY_THE_CONFIG = join(ROOT, "src", "config", "instance.ts"); + + it("is written nowhere else in the bot", () => { + const written = sources(join(ROOT, "src")) + .filter((path) => path !== OWNED_BY_THE_CONFIG) + .filter((path) => { + const text = readFileSync(path, "utf8"); + return /discord\.gg\/xcMVwAVjSD|github\.com\/Kkkermit\/Testify|\bDEFAULT_PREFIX\b/.test(text); + }) + .map((path) => relative(ROOT, path)); + + expect(written).toEqual([]); + }); +}); diff --git a/tests/database/guildRepository.test.ts b/tests/database/guildRepository.test.ts index f1d36b1ed..fea206048 100644 --- a/tests/database/guildRepository.test.ts +++ b/tests/database/guildRepository.test.ts @@ -1,5 +1,4 @@ import { describeWithMongo } from "../helpers/mongo"; -import { DEFAULT_PREFIX } from "@config/constants"; import { getAntiLink, setAntiLink } from "@database/repositories/antiLinkRepository"; import { getAuditLogConfig, setAuditLogConfig } from "@database/repositories/auditLogRepository"; import { createAutoResponder, listAutoResponders } from "@database/repositories/autoResponderRepository"; @@ -16,6 +15,7 @@ import { listSticky, setSticky } from "@database/repositories/stickyRepository"; import { getTreasureConfig, saveTreasureConfig } from "@database/repositories/treasureRepository"; import { getVoiceCounter, setVoiceCounter } from "@database/repositories/voiceCounterRepository"; import { getWelcome, saveWelcome } from "@database/repositories/welcomeRepository"; +import { DEFAULT_PREFIX } from "@testify/shared"; const GUILD = "900000000000000001"; const OTHER = "900000000000000002"; diff --git a/tests/lib/bot/botIdentity.test.ts b/tests/lib/bot/botIdentity.test.ts index 609facabe..2d4952042 100644 --- a/tests/lib/bot/botIdentity.test.ts +++ b/tests/lib/bot/botIdentity.test.ts @@ -1,4 +1,4 @@ -import { theme } from "@config/theme"; +import { INSTANCE_DEFAULTS, useInstance } from "@config/instance"; import { nameBot } from "@core/brand"; import { type TestifyClient } from "@core/client"; import { botIdentity, forgetBotIdentity, identityOf } from "@lib/bot/botIdentity.util"; @@ -33,8 +33,18 @@ describe("identityOf", () => { avatarUrl: "https://cdn.discordapp.com/avatars/1/abc.png", bannerUrl: "https://cdn.discordapp.com/banners/1/def.png", accentColour: "#7c3aed", - supportUrl: theme.supportServer, - repositoryUrl: theme.repository, + supportUrl: INSTANCE_DEFAULTS.supportServer, + repositoryUrl: INSTANCE_DEFAULTS.repository, + }); + }); + + /** Every self-hosted copy linked its users to the original's support server and code, because the links were code. */ + it("links the host's own repository and support server, and no support server when there is none", () => { + useInstance({ ...INSTANCE_DEFAULTS, repository: "https://github.com/someone/fork", supportServer: null }); + + expect(identityOf(userLike() as never)).toMatchObject({ + supportUrl: null, + repositoryUrl: "https://github.com/someone/fork", }); }); diff --git a/tests/lib/bot/inviterGreeting.test.ts b/tests/lib/bot/inviterGreeting.test.ts new file mode 100644 index 000000000..3d2e9cdab --- /dev/null +++ b/tests/lib/bot/inviterGreeting.test.ts @@ -0,0 +1,194 @@ +import { Collection, DiscordAPIError, PermissionFlagsBits, RESTJSONErrorCodes } from "discord.js"; +import { INSTANCE_DEFAULTS, useInstance } from "@config/instance"; +import { type TestifyClient } from "@core/client"; +import { findInviter, greetInviter, inviterGreeting, pickBotAdd } from "@lib/bot/inviterGreeting.util"; +import { createMockClient } from "@tests/helpers/mocks"; + +const blocked = new Set(); +jest.mock("@database/repositories/blacklistRepository", () => ({ + findBlacklistEntry: jest.fn(async (id: string) => Promise.resolve(blocked.has(id) ? { userId: id } : null)), +})); +jest.mock("@database/repositories/prefixRepository", () => ({ getPrefix: jest.fn(async () => Promise.resolve("t?")) })); + +const BOT = "200000000000000002"; +const ADDER = "100000000000000001"; +const OWNER = "100000000000000009"; +const NOW = 1_800_000_000_000; + +interface Person { + id: string; + bot: boolean; + send: jest.Mock; +} + +const person = (id: string, bot = false): Person => ({ id, bot, send: jest.fn(async () => Promise.resolve({})) }); + +interface GuildOptions { + can?: bigint[]; + /** One answer per audit-log read, in order. */ + audit?: { targetId: string; executorId: string; createdTimestamp: number }[][]; + integrationUser?: Person | null; + adder?: Person; + owner?: Person; +} + +function guildWith({ can = [], audit = [], integrationUser = null, adder, owner = person(OWNER) }: GuildOptions) { + const reads = [...audit]; + return { + id: "900000000000000001", + name: "Sam's *Server*", + members: { me: { permissions: { has: (flag: bigint) => can.includes(flag) } } }, + fetchAuditLogs: jest.fn(async () => + Promise.resolve({ entries: new Collection((reads.shift() ?? []).map((e, i) => [String(i), e])) }), + ), + fetchIntegrations: jest.fn(async () => + Promise.resolve( + new Collection(integrationUser === null ? [] : [["1", { account: { id: BOT }, user: integrationUser }]]), + ), + ), + fetchOwner: jest.fn(async () => Promise.resolve({ user: owner })), + client: { users: { fetch: jest.fn(async () => Promise.resolve(adder ?? person(ADDER))) } }, + }; +} + +const noWait = { wait: jest.fn(async () => Promise.resolve()), now: () => NOW }; + +describe("pickBotAdd", () => { + /** A bot removed and added again has two entries, and only the newest is the person who just added it. */ + it("takes the newest entry that added this bot, and only one recent enough to be this join", () => { + const entry = (targetId: string, executorId: string, ageMs: number) => ({ + targetId, + executorId, + createdTimestamp: NOW - ageMs, + }); + const cases: [string, ReturnType[], string | null][] = [ + ["newest of two", [entry(BOT, "old", 60_000), entry(BOT, "new", 1_000)], "new"], + ["another bot's", [entry("300000000000000003", "other", 1_000)], null], + ["from an earlier add", [entry(BOT, "stale", 11 * 60_000)], null], + ["none", [], null], + ]; + + expect(cases.filter(([, entries, want]) => pickBotAdd(entries, BOT, NOW) !== want).map(([name]) => name)).toEqual( + [], + ); + }); +}); + +describe("findInviter", () => { + /** An invite link, the Add App button and the App Directory all write this entry, so it covers every way in. */ + it("reads who added the bot from the audit log, asking again when the entry has not landed yet", async () => { + const guild = guildWith({ + can: [PermissionFlagsBits.ViewAuditLog], + audit: [[], [{ targetId: BOT, executorId: ADDER, createdTimestamp: NOW - 1_000 }]], + }); + + const found = await findInviter(guild as never, BOT, noWait); + + expect(found).toMatchObject({ user: { id: ADDER }, source: "audit log" }); + expect(guild.fetchAuditLogs).toHaveBeenCalledTimes(2); + expect(noWait.wait).toHaveBeenCalledWith(3_000); + }); + + it("falls back to the bot's integration, then to the owner, when the audit log cannot say", async () => { + const viaIntegration = guildWith({ can: [PermissionFlagsBits.ManageGuild], integrationUser: person(ADDER) }); + const viaOwner = guildWith({ can: [] }); + + expect(await findInviter(viaIntegration as never, BOT, noWait)).toMatchObject({ source: "integration" }); + expect(await findInviter(viaOwner as never, BOT, noWait)).toMatchObject({ user: { id: OWNER }, source: "owner" }); + expect(viaOwner.fetchAuditLogs).not.toHaveBeenCalled(); + }); +}); + +describe("inviterGreeting", () => { + const text = (message: ReturnType): string => JSON.stringify(message); + + it("points at /help, the prefix and the dashboard's setup checklist", () => { + const message = text( + inviterGreeting({ + bot: "Testify", + server: "Sam's *Server*", + prefix: "!", + setupUrl: "https://x.example/guilds/1", + }), + ); + + expect(message).toContain("/help"); + expect(message).toContain("!help"); + expect(message).toContain("https://x.example/guilds/1"); + expect(message).toContain("Sam's \\\\*Server\\\\*"); + }); + + /** A host without a support server must not send people to somebody else's. */ + it("names the setup commands without a dashboard, and leaves out a support server the host has not got", () => { + useInstance({ ...INSTANCE_DEFAULTS, supportServer: null }); + const message = text(inviterGreeting({ bot: "Testify", server: "S", prefix: "t?", setupUrl: null })); + + expect(message).toContain("every feature has a setup command"); + expect(message).not.toContain("Set up the server"); + expect(message).not.toContain("Support server"); + expect(message).toContain(INSTANCE_DEFAULTS.repository); + }); +}); + +describe("greetInviter", () => { + function client(): TestifyClient { + return createMockClient({ + user: { id: BOT }, + env: { DASHBOARD_ENABLED: true, DASHBOARD_BASE_URL: "https://dash.example", SITE_ENABLED: true }, + } as never); + } + + const audited = (adder: Person) => + guildWith({ + can: [PermissionFlagsBits.ViewAuditLog], + audit: [[{ targetId: BOT, executorId: adder.id, createdTimestamp: NOW - 1_000 }]], + adder, + }); + + beforeEach(() => blocked.clear()); + + it("sends whoever added the bot one message with the server's setup link", async () => { + const adder = person(ADDER); + + await greetInviter(client(), audited(adder) as never, noWait); + + expect(adder.send).toHaveBeenCalledTimes(1); + expect(JSON.stringify(adder.send.mock.calls[0])).toContain("https://dash.example/guilds/900000000000000001"); + }); + + /** Closed direct messages are the person's choice, so they must never fail the join or reach the error log. */ + it("swallows closed direct messages, noting them only at debug", async () => { + const adder = person(ADDER); + adder.send.mockRejectedValue( + new DiscordAPIError( + { code: RESTJSONErrorCodes.CannotSendMessagesToThisUser, message: "Cannot send messages to this user" }, + RESTJSONErrorCodes.CannotSendMessagesToThisUser, + 403, + "POST", + "/users/@me/channels", + {}, + ), + ); + const bot = client(); + const warn = jest.spyOn(bot.logger, "warn"); + + await expect(greetInviter(bot, audited(adder) as never, noWait)).resolves.toBeUndefined(); + expect(warn).not.toHaveBeenCalled(); + }); + + it("writes to nobody who is a bot or blacklisted, or when the host has turned it off", async () => { + const robot = person(ADDER, true); + await greetInviter(client(), audited(robot) as never, noWait); + + const banned = person(ADDER); + blocked.add(ADDER); + await greetInviter(client(), audited(banned) as never, noWait); + blocked.clear(); + + const quiet = person(ADDER); + useInstance({ ...INSTANCE_DEFAULTS, greetInviter: false }); + await greetInviter(client(), audited(quiet) as never, noWait); + + expect([robot, banned, quiet].filter((who) => who.send.mock.calls.length > 0)).toEqual([]); + }); +}); diff --git a/tests/lib/settingsScreens.test.ts b/tests/lib/settingsScreens.test.ts index 18500aafa..609995fc3 100644 --- a/tests/lib/settingsScreens.test.ts +++ b/tests/lib/settingsScreens.test.ts @@ -1,5 +1,4 @@ import { MessageFlags } from "discord.js"; -import { DEFAULT_PREFIX } from "@config/constants"; import { parseCustomId } from "@core/button"; import { text } from "@lib/discord/containers.util"; import { type ContainerMessage } from "@lib/discord/discord.types"; @@ -17,6 +16,7 @@ import { } from "@lib/settings/settings.constants"; import { channelValue, roleValue, settingsScreen, statusDot } from "@lib/settings/settingsScreen.util"; import { voiceStatsPanel } from "@lib/settings/voiceStatsPanel.util"; +import { DEFAULT_PREFIX } from "@testify/shared"; import { buttonsOf, duplicateIds, idsOf, textOf } from "@tests/helpers/containers"; const OWNER = "100000000000000001"; diff --git a/tests/scripts/setupEnv.test.ts b/tests/scripts/setupEnv.test.ts index b805f9983..c3f1530d4 100644 --- a/tests/scripts/setupEnv.test.ts +++ b/tests/scripts/setupEnv.test.ts @@ -1,4 +1,15 @@ -import { dashboardFields, type Field, fields } from "../../scripts/setupEnv"; +import { mkdtempSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + dashboardFields, + type Field, + fields, + instanceFields, + instanceFileText, + OPERATOR_CONTACT, +} from "../../scripts/setupEnv"; +import { INSTANCE_DEFAULTS, readInstance } from "@config/instance"; function field(list: Field[], key: string): Field { const found = list.find((candidate) => candidate.key === key); @@ -31,3 +42,36 @@ describe("the setup questions", () => { expect(field(fields(true), "MONGODB_URI").initial).toBe("mongodb://localhost:27017/testify-dev"); }); }); + +describe("making it your own", () => { + /** A wizard that wrote a file the bot then refused would turn the friendly path into a failed start. */ + it("checks each answer with the rule the bot reads the file with", () => { + const questions = instanceFields(); + + expect(field(questions, "repository").check?.("https://gitlab.com/me/fork")).toMatch(/GitHub repository/); + expect(field(questions, "repository").check?.("https://github.com/me/fork")).toBeNull(); + expect(field(questions, "supportServer").check?.("none")).toBeNull(); + expect(field(questions, "defaultPrefix").check?.("t ?")).toMatch(/space/); + expect(OPERATOR_CONTACT.check?.("javascript:alert(1)")).toMatch(/email address or an https/); + }); + + it("writes only what was answered, which the bot then reads back", () => { + const text = instanceFileText({ + "operator.name": "Sam's Servers", + "operator.contact": "privacy@example.com", + supportServer: "none", + repository: "", + defaultPrefix: "!", + }); + const path = join(mkdtempSync(join(tmpdir(), "testify-wizard-")), "testify.config.json"); + writeFileSync(path, text ?? "", "utf8"); + + expect(readInstance({ name: "testify.config.json", path, exists: true })).toEqual({ + ...INSTANCE_DEFAULTS, + operator: { name: "Sam's Servers", contact: "privacy@example.com" }, + supportServer: null, + defaultPrefix: "!", + }); + expect(instanceFileText({ repository: " " })).toBeNull(); + }); +}); diff --git a/tests/setup.ts b/tests/setup.ts index e2c7b5d6b..69c37cc58 100644 --- a/tests/setup.ts +++ b/tests/setup.ts @@ -1,6 +1,7 @@ /** Module-level caches the harness empties between tests, so no test inherits another's state. */ const RESETS: readonly (readonly [module: string, name: string])[] = [ ["@config/env", "resetEnv"], + ["@config/instance", "resetInstance"], ["@core/checks", "clearCooldowns"], ["@database/repositories/afkRepository", "clearAfkCache"], ["@database/repositories/autoResponderRepository", "clearAutoResponderCache"], From da1d3fdab2c85fef6fc492ae3ad632fba8d8e637 Mon Sep 17 00:00:00 2001 From: "Kkermit." <132657029+Kkkermit@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:33:55 +0000 Subject: [PATCH 2/7] test: Pin that the default prefix is stored as nothing --- tests/database/prefixRepository.test.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 tests/database/prefixRepository.test.ts diff --git a/tests/database/prefixRepository.test.ts b/tests/database/prefixRepository.test.ts new file mode 100644 index 000000000..ded9f488e --- /dev/null +++ b/tests/database/prefixRepository.test.ts @@ -0,0 +1,23 @@ +import { describeWithMongo } from "../helpers/mongo"; +import { INSTANCE_DEFAULTS, useInstance } from "@config/instance"; +import { GuildPrefix } from "@database/models/prefix.schema"; +import { clearPrefixCache, getPrefix, setPrefix, setPrefixEnabled } from "@database/repositories/prefixRepository"; + +const ON_DEFAULT = "900000000000000001"; +const CHOSE_ITS_OWN = "900000000000000002"; + +describeWithMongo("prefixRepository", () => { + /** A stored copy of the default would pin that server to it, so a host changing the default would never reach it. */ + it("stores the default as nothing, so a host's new default reaches every server that never chose one", async () => { + await setPrefix(CHOSE_ITS_OWN, "!"); + await setPrefix(ON_DEFAULT, "?"); + await setPrefix(ON_DEFAULT, INSTANCE_DEFAULTS.defaultPrefix); + await setPrefixEnabled(ON_DEFAULT, false); + + useInstance({ ...INSTANCE_DEFAULTS, defaultPrefix: "$" }); + clearPrefixCache(); + + expect(await GuildPrefix.findOne({ guildId: ON_DEFAULT }).lean().exec()).not.toHaveProperty("prefix"); + expect([await getPrefix(ON_DEFAULT), await getPrefix(CHOSE_ITS_OWN)]).toEqual(["$", "!"]); + }); +}); From 73f0a86df41e4fbb24adf838f72e7d58a9ac37e2 Mon Sep 17 00:00:00 2001 From: "Kkermit." <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 19 Nov 2026 08:12:03 +0000 Subject: [PATCH 3/7] update: Read one testify.config.json in development and production, and carry it into the image --- .env.development.example | 10 +++++----- .env.example | 6 +++--- .gitignore | 3 +-- AGENTS.md | 9 ++++++--- Dockerfile | 3 +++ docs/customising.md | 9 ++++++--- docs/hosting.md | 14 ++++++++++++++ scripts/setupEnv.ts | 6 +++--- src/config/instance.ts | 9 ++++----- tests/config/instance.test.ts | 28 +++++++++++++++------------- 10 files changed, 60 insertions(+), 37 deletions(-) diff --git a/.env.development.example b/.env.development.example index 197b1797d..bcffb75f1 100644 --- a/.env.development.example +++ b/.env.development.example @@ -4,8 +4,8 @@ # The point of the split is that `npm run dev` must never start the production # bot. Use a SECOND Discord application here, not the one your users invite. # -# Links, who runs it and the default prefix go in `testify.config.development.json` -# beside this file, which `npm run dev` reads. See docs/customising.md. +# Links, who runs it and the default prefix go in `testify.config.json` beside this +# file, which `npm run dev` and `npm start` both read. See docs/customising.md. # Your development bot's token — a different application from production. DISCORD_TOKEN= @@ -116,9 +116,9 @@ SUPPORT_AI_API_KEY= # Defaults to claude-opus-5. Any Claude model that supports structured outputs works. SUPPORT_AI_MODEL= -# Where `testify.config.json` is, when it is not beside this file. Blank looks beside it, which is what you want -# almost always; docker-compose.yml sets this itself. The file holds your links, who runs your copy and the -# default prefix — see docs/customising.md. +# Where `testify.config.json` is, when it is not beside this file: on a Railway volume, say. Blank looks beside +# it, which is what you want almost always; docker-compose.yml sets this itself. The file holds your links, who +# runs your copy and the default prefix — see docs/customising.md. TESTIFY_CONFIG= # NODE_ENV is deliberately not here. `npm run dev` sets it with cross-env, which is what makes the bot read diff --git a/.env.example b/.env.example index 486b48c16..4d1e7acc0 100644 --- a/.env.example +++ b/.env.example @@ -121,9 +121,9 @@ SUPPORT_AI_API_KEY= # Defaults to claude-opus-5. Any Claude model that supports structured outputs works. SUPPORT_AI_MODEL= -# Where `testify.config.json` is, when it is not beside this file. Blank looks beside it, which is what you want -# almost always; docker-compose.yml sets this itself. The file holds your links, who runs your copy and the -# default prefix — see docs/customising.md. +# Where `testify.config.json` is, when it is not beside this file: on a Railway volume, say. Blank looks beside +# it, which is what you want almost always; docker-compose.yml sets this itself. The file holds your links, who +# runs your copy and the default prefix — see docs/customising.md. TESTIFY_CONFIG= # NODE_ENV is deliberately not here. `npm run dev` sets it with cross-env, which is what makes the bot read diff --git a/.gitignore b/.gitignore index bce1a005f..ac46d6ce2 100644 --- a/.gitignore +++ b/.gitignore @@ -10,9 +10,8 @@ coverage/ .env.* !.env.example !.env.development.example -# Per copy, like .env; a fork that wants its own committed removes these two lines. +# Per copy, like .env. A fork that deploys from git commits its own with `git add -f testify.config.json`. testify.config.json -testify.config.development.json # Logs logs/ diff --git a/AGENTS.md b/AGENTS.md index f4fe2e82b..6ccdd269e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -840,8 +840,8 @@ prefix and whether the bot greets whoever adds it — is `testify.config.json`, [`docs/customising.md`](docs/customising.md) is the reader's guide to it. Six things about it are load-bearing: - **Every key is optional and the defaults are the original's** (`INSTANCE_DEFAULTS`), so a copy with no file behaves - as it always did. It sits beside `.env` and is found the same way, `testify.config.development.json` under - `npm run dev`, and it is gitignored like `.env`; a fork that wants it committed removes those two lines. + as it always did. It sits beside `.env`, one file for `npm run dev` and `npm start` alike, and it is gitignored like + `.env`; a fork that deploys from git adds it with `git add -f`. - **It is read once, in `main()` straight after `loadEnv`, and fails start-up with a list**, unknown keys included (`z.strictObject`), so a misspelt setting never silently does nothing. `explainStartupFailure` turns an `InstanceError` into the same kind of box as a bad `.env`. Everything else reads `instanceConfig()`, which is the @@ -850,7 +850,10 @@ prefix and whether the bot greets whoever adds it — is `testify.config.json`, `prefix.default` is a getter for exactly that reason. - **Docker mounts the folder, not the file.** `docker-compose.yml` mounts the folder it runs from at `/app/instance`, read-only, and sets `TESTIFY_CONFIG` to the file there. Mounting a file that does not exist makes Docker create a - folder in its place, and `instanceFile` reads a folder as no file, so the defaults apply either way. + folder in its place, and `instanceFile` reads a folder as no file, so the defaults apply either way. **A host that + builds the `Dockerfile` gets the file in the image:** Railway has nowhere else to put one, so the runtime stage copies + `testify.config.jso[n]` into `/app` beside `package.json`, because the legacy builder refuses a pattern that is a + `COPY`'s only source. The published image is built from a checkout without one, so it never carries anybody's. - **The links live nowhere else.** `theme.ts` no longer holds `author`, `repository` or `supportServer`, and `tests/config/instance.test.ts` fails on the original's repository, its support invite or `DEFAULT_PREFIX` written anywhere in `src` but `instance.ts`. `projectLinkButtons` draws Source code and Support, leaving Support out when the diff --git a/Dockerfile b/Dockerfile index 735c06b71..431795810 100644 --- a/Dockerfile +++ b/Dockerfile @@ -69,6 +69,9 @@ RUN npm ci --omit=dev --ignore-scripts --workspace @testify/shared --include-wor COPY --from=build /app/dist ./dist COPY --from=build /app/shared/dist ./shared/dist COPY --from=build /app/dashboard/dist ./dashboard/dist +# A copy's testify.config.json, when its repository carries one, since a host building this file (Railway, say) has +# nowhere else to put it. The bracket makes it optional; the legacy builder refuses a pattern that is the only source. +COPY package.json testify.config.jso[n] ./ # `dist/api` resolves the SPA at ../../dashboard/dist, so the two must keep this layout. USER node diff --git a/docs/customising.md b/docs/customising.md index ad092cc34..183330403 100644 --- a/docs/customising.md +++ b/docs/customising.md @@ -62,11 +62,14 @@ A few things worth knowing: most other editors complete the keys and underline a mistake. - **It is read once, at start-up.** Restart the bot after changing it. A mistake stops the start with a list of every problem, and an unknown key is one of them, so a misspelt setting never quietly does nothing. -- **`npm run dev` reads `testify.config.development.json`**, the way it reads `.env.development`, so a development - bot can use a different prefix from the one people invite. +- **One file, however the bot runs.** `npm run dev` and `npm start` both read `testify.config.json`; only `.env` is + split in two. - **In Docker it sits beside `.env` too.** `docker-compose.yml` mounts the folder it runs from, read-only, so the bot finds the file there, and a missing one simply means the defaults. See [Docker](hosting.md). -- **It is ignored by git, like `.env`.** In a fork you want to commit it in, delete its two lines from `.gitignore`. +- **On Railway, commit it, or put it on a volume.** A host that builds from your repository finds nothing that git + does not have. [Your settings on Railway](hosting.md#your-settings-on-railway) has both ways. +- **It is ignored by git, like `.env`.** `git add -f testify.config.json` commits it anyway, and git keeps tracking it + from then on. ### The operator diff --git a/docs/hosting.md b/docs/hosting.md index 2391deb79..2a1913f1c 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -167,6 +167,20 @@ Vercel is worth being explicit about, because people ask: it can host Discord _H webhook-delivered slash commands — but not a gateway client, and a serverless function cannot hold a voice connection open. There is no configuration that makes this bot run there. +### Your settings on Railway + +`.env`'s variables go in the service's **Variables** tab. `testify.config.json` is a file, and Railway has no folder +beside them to put it in, so it gets there one of two ways: + +- **Building from your fork:** commit it. It is gitignored so that nobody commits their settings by accident, and + `git add -f testify.config.json` adds it anyway; once it is tracked, git keeps tracking it. The image copies it to + `/app`, where the bot looks, so a change is a push and Railway's rebuild. +- **Running the published image:** attach a volume to the service, put the file on it with Railway's volume file + browser, and set `TESTIFY_CONFIG` to its path there, such as `/data/testify.config.json`. A change needs only a + restart. + +Without either, the bot runs with the built-in settings, exactly as a copy with no file does. + --- ## 🩺 The health check diff --git a/scripts/setupEnv.ts b/scripts/setupEnv.ts index 062ff0b65..68516f495 100644 --- a/scripts/setupEnv.ts +++ b/scripts/setupEnv.ts @@ -338,15 +338,15 @@ async function main(): Promise { steps.push("", "One more step in the Developer Portal, under OAuth2 → Redirects:", ` ${paint.bold(callback)}`); } - const configured = await makeItYours(isDev); + const configured = await makeItYours(); if (configured !== null) steps.push("", `Your links and settings are in ${paint.bold(configured)}.`); print(["", ...box("Done", steps, "success", paint).map((line) => ` ${line}`), ""]); } /** Optional, and separate from `.env`, because none of it is secret and a fork may want to commit it. */ -async function makeItYours(isDev: boolean): Promise { - const filename = isDev ? "testify.config.development.json" : "testify.config.json"; +async function makeItYours(): Promise { + const filename = "testify.config.json"; const target = resolve(process.cwd(), filename); const { wanted } = await prompts( diff --git a/src/config/instance.ts b/src/config/instance.ts index 5a26fe655..178fbc638 100644 --- a/src/config/instance.ts +++ b/src/config/instance.ts @@ -88,10 +88,9 @@ export interface InstanceFile { exists: boolean; } -/** Beside `.env`, as `npm run dev` reads `.env.development`; `TESTIFY_CONFIG` names another place, as Docker does. */ -export function instanceFile(env: Pick): InstanceFile { - const given = - env.TESTIFY_CONFIG ?? (env.NODE_ENV === "development" ? "testify.config.development.json" : "testify.config.json"); +/** Beside `.env`, for `npm run dev` and `npm start` alike; `TESTIFY_CONFIG` names another place, as Docker does. */ +export function instanceFile(env: Pick): InstanceFile { + const given = env.TESTIFY_CONFIG ?? "testify.config.json"; const path = resolve(process.cwd(), given); // A folder is not the file, which is what Docker leaves where it was asked to mount one that did not exist. @@ -149,7 +148,7 @@ export function readInstance(file: InstanceFile): InstanceConfig { let loaded: InstanceConfig | null = null; -export function loadInstance(env: Pick): InstanceConfig { +export function loadInstance(env: Pick): InstanceConfig { loaded = readInstance(instanceFile(env)); return loaded; } diff --git a/tests/config/instance.test.ts b/tests/config/instance.test.ts index 27498ff86..a7409684c 100644 --- a/tests/config/instance.test.ts +++ b/tests/config/instance.test.ts @@ -88,22 +88,16 @@ describe("the instance config file", () => { mkdirSync(join(folder, "testify.config.json")); const cwd = jest.spyOn(process, "cwd").mockReturnValue(folder); - expect(instanceFile({ NODE_ENV: "production", TESTIFY_CONFIG: undefined }).exists).toBe(false); + expect(instanceFile({ TESTIFY_CONFIG: undefined }).exists).toBe(false); cwd.mockRestore(); }); - it("is read beside .env, as the development file under npm run dev, and wherever Docker points", () => { - const names = [ - instanceFile({ NODE_ENV: "production", TESTIFY_CONFIG: undefined }).name, - instanceFile({ NODE_ENV: "development", TESTIFY_CONFIG: undefined }).name, - instanceFile({ NODE_ENV: "production", TESTIFY_CONFIG: "/app/instance/testify.config.json" }).path, - ]; - - expect(names).toEqual([ - "testify.config.json", - "testify.config.development.json", - resolve("/app/instance/testify.config.json"), - ]); + /** `npm run dev` and `npm start` read one file, so a development bot never runs with links nobody set. */ + it("is read beside .env whichever way the bot runs, and wherever Docker points", () => { + expect([ + instanceFile({ TESTIFY_CONFIG: undefined }).path, + instanceFile({ TESTIFY_CONFIG: "/srv/t.json" }).path, + ]).toEqual([resolve("testify.config.json"), resolve("/srv/t.json")]); }); it("ships an example that changes nothing when copied as it is", () => { @@ -112,6 +106,14 @@ describe("the instance config file", () => { expect(readInstance(example)).toEqual(INSTANCE_DEFAULTS); }); + /** Railway and every other host that builds the Dockerfile ran with the defaults, because the file never left the build. */ + it("goes into the image when the repository carries one, and the image still builds when it does not", () => { + const runtime = readFileSync(join(ROOT, "Dockerfile"), "utf8").split(/^FROM .* AS runtime$/m)[1] ?? ""; + + expect(runtime).toMatch(/^COPY \S+ testify\.config\.jso\[n\] \.\/$/m); + expect(readFileSync(join(ROOT, ".dockerignore"), "utf8")).not.toMatch(/testify\.config/); + }); + /** The schema is what an editor checks the file against, so it has to follow the bot's own rules. */ it("keeps testify.config.schema.json in step with the schema the bot reads with; npm run config:schema rewrites it", () => { expect(JSON.parse(readFileSync(join(ROOT, "testify.config.schema.json"), "utf8"))).toEqual(instanceJsonSchema()); From 7cf97e50fba3d8908a9d38cc24dbd90e12dc1fc6 Mon Sep 17 00:00:00 2001 From: "Kkermit." <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 19 Nov 2026 10:40:15 +0000 Subject: [PATCH 4/7] chore: Clear the install warnings and drop the withdrawn picomatch suppression --- .nsprc | 5 - AGENTS.md | 9 + dashboard/src/test/setup.ts | 9 + docs/future-feature.md | 19 +- docs/security.md | 23 +- package-lock.json | 685 +++++++++++++++++++++--------------- package.json | 9 +- 7 files changed, 448 insertions(+), 311 deletions(-) diff --git a/.nsprc b/.nsprc index 65b1e41a7..2cbc313e9 100644 --- a/.nsprc +++ b/.nsprc @@ -1,9 +1,4 @@ { - "1247710": { - "active": true, - "notes": "picomatch ReDoS through repeated extglobs (GHSA-fc5q-39xc-vjpf), reached only through development tooling: jest, lint-staged, vite, eslint-import-resolver-typescript and tsc-alias (chokidar, readdirp, anymatch, micromatch). Nothing the bot runs installs it (npm ls picomatch --omit=dev is empty, and the image installs with --omit=dev), and those tools match only globs written in this repository, while the advisory needs an attacker\u2019s pattern. No fixed release yet: picomatch 4.0.7 is already the latest and the advisory covers every version up to it. Re-evaluate when a patched picomatch ships.", - "expiry": 1802649600000 - }, "//example": { "active": false, "notes": "TEMPLATE \u2014 copy this shape, do not activate it. Every real entry needs three things: why it cannot be fixed now, the version that fixes it, and a hard expiry, so a suppression cannot rot into a permanent blind spot. Wording to follow: reached only through @, which cannot be upgraded without a breaking change to . Fixed in @ \u2014 re-evaluate when ships a compatible release.", diff --git a/AGENTS.md b/AGENTS.md index 496f87186..3144f8aa0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2779,6 +2779,15 @@ Three things there are load-bearing and non-obvious, all commented in place: `moduleNameMapper` pinning React to the workspace copy (`discord-html-transcripts` drags React 18 into the root `node_modules`, and elements built by 19 rendered by 18 fail with "Objects are not valid as a React child"). +**jsdom loads no stylesheet, so `src/test/setup.ts` gives it the display rules an accessible name depends on.** A +name is joined from its parts with a space only where a part is not `display: inline`. jsdom 26 called every element +a block, so every name had its spaces; jsdom 27 and later call a `` inline, as a browser does without CSS, and +`Failed AB12CD` read as `FailedAB12CD`. In the real page those parts are flex items or `block`, and Chromium with the +built CSS reads all four names that failed with their spaces, so the setup makes the children of `flex`, `inline-flex`, +`grid` and `inline-grid` and anything `block` block-level, as the browser does. A name built from plain inline spans +still runs together, which is what a browser would read too. jsdom itself is held at 29 by an override, because +`jest-environment-jsdom` still asks for 26 (see `docs/security.md`). + ### Adding to the dashboard Three registries exist so the common changes are data rather than edits to a screen. Reach for these first — a diff --git a/dashboard/src/test/setup.ts b/dashboard/src/test/setup.ts index be348a93a..bb640928f 100644 --- a/dashboard/src/test/setup.ts +++ b/dashboard/src/test/setup.ts @@ -43,6 +43,15 @@ globalThis.ResizeObserver = class { Element.prototype.scrollIntoView = jest.fn(); +// jsdom loads no stylesheet, so an accessible name joins flex items and block spans with no space where a browser +// puts one; these are the display rules a name depends on. +const displayRules = document.createElement("style"); +displayRules.textContent = [ + ".block, :is(.flex, .inline-flex, .grid, .inline-grid) > * { display: block; }", + ".flex { display: flex; } .inline-flex { display: inline-flex; } .grid { display: grid; }", +].join("\n"); +document.head.append(displayRules); + // Node's fetch demands an absolute URL where a browser resolves against the document, so the harness supplies the origin. const nodeFetch = globalThis.fetch; globalThis.fetch = (input: RequestInfo | URL, init?: RequestInit) => diff --git a/docs/future-feature.md b/docs/future-feature.md index 8f21101bd..e30a709f7 100644 --- a/docs/future-feature.md +++ b/docs/future-feature.md @@ -68,14 +68,14 @@ server, and each should be before it is relied on. ### Dependencies behind their latest release -| Package | Here | Latest | What it takes | -| -------------------------- | ------- | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `discord-html-transcripts` | 3.2.0 | 3.3.0 | It moves to undici 7, so the `undici` override can go, but it pins React to exactly 19.1.1. Installed over this lockfile, React 18 stays hoisted for its components and a transcript fails with "Objects are not valid as a React child"; it needs React 19 at the root first | -| `typescript` | 5.9.3 | 7.0.2 | The native compiler. `baseUrl` is already gone from `tsconfig.json`; `tsc-alias` and `tsup` need checking with it | -| `mongoose` | 8.24.1 | 9.12.0 | A major. Read its migration guide against every repository, then run the suite with `REQUIRE_DB_TESTS=1` | -| `react-router` | 7.18.2 | 8.5.1 | A major. `useBlocker` (the leave guard) and the lazy routes are what to check first | -| `msw` | 2.15.0 | 3.0.3 | A major, test-only. `handlers.ts` uses it, and so do the steps in `docs/dashboard/screenshots/README.md` | -| `@anthropic-ai/sdk` | 0.128.0 | 1.6.0 | Its first major. Only the support assistant's optional model picker uses it | +| Package | Here | Latest | What it takes | +| -------------------------- | ------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `discord-html-transcripts` | 3.2.0 | 3.3.0 | Not an option: its author has deprecated 3.3.0 as "broken due to a critical bug" and points back to 3.2.0. Wait for the release after it, which should also move to undici 7 and let the `undici` override go | +| `typescript` | 5.9.3 | 7.0.2 | The native compiler. `baseUrl` is already gone from `tsconfig.json`; `tsc-alias` and `tsup` need checking with it | +| `mongoose` | 8.24.1 | 9.12.0 | A major. Read its migration guide against every repository, then run the suite with `REQUIRE_DB_TESTS=1` | +| `react-router` | 7.18.2 | 8.5.1 | A major. `useBlocker` (the leave guard) and the lazy routes are what to check first | +| `msw` | 2.15.0 | 3.0.3 | A major, test-only. `handlers.ts` uses it, and so do the steps in `docs/dashboard/screenshots/README.md` | +| `@anthropic-ai/sdk` | 0.128.0 | 1.6.0 | Its first major. Only the support assistant's optional model picker uses it | `discord-giveaways` is at its latest, 6.0.1, but that was published in **August 2022** and nothing since. Replacing it with a giveaway system of the bot's own — records in MongoDB, a job that ends them, entries counted from a button — @@ -87,5 +87,6 @@ Each `overrides` pin in `package.json` exists because a parent asked for a versi is explained in [`security.md`](security.md); remove a pin once its parent asks for a fixed version by itself. On 5 November 2026 none did: minimatch 10 still asks `brace-expansion` `^5.0.5` (only minimatch 11 asks `^5.0.12`), cosmiconfig 9 asks `js-yaml` `^4.1.0`, ajv asks `fast-uri` `^3.0.1`, `@istanbuljs/load-nyc-config` asks `js-yaml` -`^3.13.1`, and `discord-html-transcripts` 3.2.0 still pins undici v5. On 10 November 2026 `discord-giveaways` 6.0.1 +`^3.13.1`, and `discord-html-transcripts` 3.2.0 still pins undici v5. On 19 November 2026 jest-environment-jsdom 30.5.2 still +asked jsdom `^26.1.0`. On 10 November 2026 `discord-giveaways` 6.0.1 still asked `deepmerge-ts` `^4.2.1`. diff --git a/docs/security.md b/docs/security.md index deb81886c..7877f4b72 100644 --- a/docs/security.md +++ b/docs/security.md @@ -141,14 +141,15 @@ Nothing is suppressed today. A fix that a pin in `overrides` can reach, below, i `overrides` in `package.json` pins transitive dependencies. npm does not allow comments there, so the reasons live here. Each one should be dropped the moment its parent updates — check when a dependency bump lands. -| Pin | Why | -| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `glob: $glob` | Several transitive dependencies still ask for glob v7, which warns on install. Pinned to the version this project already uses. | -| `test-exclude: ^7.0.1` | Reached through jest's coverage reporter; older releases depend on the deprecated glob v7. | -| `serialize-javascript: ^7.1.3` | Reached through discord-giveaways, which asks for `^6.0.0`. 7.1.3 fixes GHSA-m5mm-p8h7-m29v; older releases also carry a prototype-pollution advisory. | -| `brace-expansion: ^5.0.12` | Reached through minimatch, which glob, ESLint and jest all load and which asks for `^5.0.8`. 5.0.12 fixes GHSA-qhr7-859c-m2p7, GHSA-6j4f-fj2g-mc7p and GHSA-q2hr-2g5m-vwhr. | -| `fast-uri: ^3.1.9` | Reached through better-npm-audit → table → ajv, which asks for `^3.0.1`. 3.1.9 fixes GHSA-7p8r-x3mc-p8w7, GHSA-w74x-v6f9-j3xg, GHSA-xhq7-xmqj-769h, GHSA-wjr9-j795-jxcr and GHSA-333x-w4r6-6crp. | -| `js-yaml: ^4.3.2` | Reached through commitlint → cosmiconfig. 4.3.1 fixes GHSA-5p4m-2wfm-xmqj, which the advisory's range ends before. | -| `@istanbuljs/load-nyc-config` → `js-yaml: ^3.15.1` | The same advisory on the 3.x line, reached through jest's coverage plugin. Scoped, because 3.x and 4.x have different APIs. | -| `discord-html-transcripts` → `undici` | The package pins undici v5, which has open advisories. v6 is API-compatible, and `^6.29.1` fixes GHSA-rfgv-xxqx-mfg5, GHSA-4qv8-2p9j-2685 and GHSA-xjj6-f33q-929c. | -| `discord-giveaways` → `deepmerge-ts: ^8.0.1` | Its latest release, 6.0.1, asks for `^4.2.1`. 8.0.0 fixes GHSA-ggr8-5vv4-36mx, and the `deepmerge` and `deepmergeCustom({ mergeArrays: false })` calls it makes give the same results on 8. | +| Pin | Why | +| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `glob: $glob` | Several transitive dependencies still ask for glob v7, which warns on install. Pinned to the version this project already uses. | +| `test-exclude: ^7.0.1` | Reached through jest's coverage reporter; older releases depend on the deprecated glob v7. | +| `serialize-javascript: ^7.1.3` | Reached through discord-giveaways, which asks for `^6.0.0`. 7.1.3 fixes GHSA-m5mm-p8h7-m29v; older releases also carry a prototype-pollution advisory. | +| `brace-expansion: ^5.0.12` | Reached through minimatch, which glob, ESLint and jest all load and which asks for `^5.0.8`. 5.0.12 fixes GHSA-qhr7-859c-m2p7, GHSA-6j4f-fj2g-mc7p and GHSA-q2hr-2g5m-vwhr. | +| `fast-uri: ^3.1.9` | Reached through better-npm-audit → table → ajv, which asks for `^3.0.1`. 3.1.9 fixes GHSA-7p8r-x3mc-p8w7, GHSA-w74x-v6f9-j3xg, GHSA-xhq7-xmqj-769h, GHSA-wjr9-j795-jxcr and GHSA-333x-w4r6-6crp. | +| `js-yaml: ^4.3.2` | Reached through commitlint → cosmiconfig. 4.3.1 fixes GHSA-5p4m-2wfm-xmqj, which the advisory's range ends before. | +| `@istanbuljs/load-nyc-config` → `js-yaml: ^3.15.1` | The same advisory on the 3.x line, reached through jest's coverage plugin. Scoped, because 3.x and 4.x have different APIs. | +| `undici@^5: ^6.29.1` | discord-html-transcripts 3.2.0 pins undici v5, which has open advisories. v6 is API-compatible, and `^6.29.1` fixes GHSA-rfgv-xxqx-mfg5, GHSA-4qv8-2p9j-2685 and GHSA-xjj6-f33q-929c. Keyed on v5 so jsdom's v7 is left alone, and at the top level because npm 11.6, which Node 24.11 ships, reports a pin nested under a package with peers as a false peer conflict on every install. | +| `jsdom: ^29.1.1` | jest-environment-jsdom 30.5.2, its latest, still asks for jsdom 26, whose `whatwg-encoding` is deprecated and warns on every install. 29 is the newest that supports Node 24.11; 30 needs 24.15. Test-only. | +| `discord-giveaways` → `deepmerge-ts: ^8.0.1` | Its latest release, 6.0.1, asks for `^4.2.1`. 8.0.0 fixes GHSA-ggr8-5vv4-36mx, and the `deepmerge` and `deepmergeCustom({ mergeArrays: false })` calls it makes give the same results on 8. | diff --git a/package-lock.json b/package-lock.json index 1f4fe4795..03170922c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,7 +42,7 @@ "@types/jest": "30.0.0", "@types/node": "24.19.2", "@types/prompts": "2.4.9", - "better-npm-audit": "3.11.0", + "better-npm-audit": "4.2.1", "cross-env": "10.1.0", "eslint": "10.14.0", "eslint-config-prettier": "10.1.8", @@ -278,26 +278,39 @@ } } }, - "node_modules/@asamuzakjp/css-color": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz", - "integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==", + "node_modules/@asamuzakjp/dom-selector": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz", + "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==", "dev": true, "license": "MIT", "dependencies": { - "@csstools/css-calc": "^2.1.3", - "@csstools/css-color-parser": "^3.0.9", - "@csstools/css-parser-algorithms": "^3.0.4", - "@csstools/css-tokenizer": "^3.0.3", - "lru-cache": "^10.4.3" + "@asamuzakjp/generational-cache": "^1.0.1", + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.2.1", + "is-potential-custom-element-name": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, - "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", + "node_modules/@asamuzakjp/generational-cache": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz", + "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==", "dev": true, - "license": "ISC" + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" }, "node_modules/@babel/code-frame": { "version": "7.29.7", @@ -824,6 +837,19 @@ "dev": true, "license": "MIT" }, + "node_modules/@bramus/specificity": { + "version": "2.4.3", + "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz", + "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==", + "dev": true, + "license": "MIT", + "dependencies": { + "css-tree": "^3.2.1" + }, + "bin": { + "specificity": "bin/cli.js" + } + }, "node_modules/@cacheable/memory": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/@cacheable/memory/-/memory-2.2.0.tgz", @@ -1299,10 +1325,10 @@ "node": ">=22" } }, - "node_modules/@csstools/color-helpers": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", - "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.1.17", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.17.tgz", + "integrity": "sha512-IPx9W33+t0Yt5TVb+Y7oICrThOIry0TY6GuXfSHOatxA0uiHqbzi98Gai905lpBAX1m/LH7iI96e9jcI7Dkvxw==", "dev": true, "funding": [ { @@ -1315,103 +1341,13 @@ } ], "license": "MIT-0", - "engines": { - "node": ">=18" - } - }, - "node_modules/@csstools/css-calc": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", - "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=18" - }, - "peerDependencies": { - "@csstools/css-parser-algorithms": "^3.0.5", - "@csstools/css-tokenizer": "^3.0.4" - } - }, - "node_modules/@csstools/css-color-parser": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", - "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "dependencies": { - "@csstools/color-helpers": "^5.1.0", - "@csstools/css-calc": "^2.1.4" - }, - "engines": { - "node": ">=18" - }, "peerDependencies": { - "@csstools/css-parser-algorithms": "^3.0.5", - "@csstools/css-tokenizer": "^3.0.4" - } - }, - "node_modules/@csstools/css-parser-algorithms": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", - "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" - } - ], - "license": "MIT", - "engines": { - "node": ">=18" + "css-tree": "^3.2.1" }, - "peerDependencies": { - "@csstools/css-tokenizer": "^3.0.4" - } - }, - "node_modules/@csstools/css-tokenizer": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", - "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/csstools" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/csstools" + "peerDependenciesMeta": { + "css-tree": { + "optional": true } - ], - "license": "MIT", - "engines": { - "node": ">=18" } }, "node_modules/@derhuerst/http-basic": { @@ -2220,6 +2156,24 @@ "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@exodus/bytes": { + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", + "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@noble/hashes": "^1.8.0 || ^2.0.0" + }, + "peerDependenciesMeta": { + "@noble/hashes": { + "optional": true + } + } + }, "node_modules/@hono/node-server": { "version": "2.1.6", "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.6.tgz", @@ -6798,23 +6752,33 @@ } }, "node_modules/better-npm-audit": { - "version": "3.11.0", - "resolved": "https://registry.npmjs.org/better-npm-audit/-/better-npm-audit-3.11.0.tgz", - "integrity": "sha512-/Pt05DK6HQaRjWDc5McsCkJBZYfhgQGneKnxzPJExtRq38NttO1Hm30m0GVQeZogE94LVNBVrhWwVsoCo+at3g==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/better-npm-audit/-/better-npm-audit-4.2.1.tgz", + "integrity": "sha512-q7kA4VEpHUVY8Cl3qpWoA35zQ3gO0kKDiDdBvFpVfbuuQdpNJalT6oEOsru+v/P0lXW0RVYvampxuIqT8BrHFQ==", "dev": true, "license": "MIT", "dependencies": { "commander": "^8.0.0", "dayjs": "^1.10.6", - "lodash.get": "^4.4.2", "semver": "^7.6.3", - "table": "^6.7.1" + "table": "^6.9.0", + "yaml": "^2.9.1" }, "bin": { "better-npm-audit": "index.js" }, "engines": { - "node": ">= 8.12" + "node": ">= 18" + } + }, + "node_modules/bidi-js": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz", + "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" } }, "node_modules/binary-extensions": { @@ -7366,27 +7330,27 @@ "node": ">= 8" } }, - "node_modules/css.escape": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", - "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cssstyle": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.6.0.tgz", - "integrity": "sha512-2z+rWdzbbSZv6/rhtvzvqeZQHrBaqgogqt85sqFNbabZOuFbCVFb8kPeEtZjiKkbrm395irpNKiYeFeLiQnFPg==", + "node_modules/css-tree": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz", + "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==", "dev": true, "license": "MIT", "dependencies": { - "@asamuzakjp/css-color": "^3.2.0", - "rrweb-cssom": "^0.8.0" + "mdn-data": "2.27.1", + "source-map-js": "^1.2.1" }, "engines": { - "node": ">=18" + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" } }, + "node_modules/css.escape": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/css.escape/-/css.escape-1.5.1.tgz", + "integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==", + "dev": true, + "license": "MIT" + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", @@ -7404,17 +7368,55 @@ } }, "node_modules/data-urls": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz", - "integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==", + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz", + "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==", "dev": true, "license": "MIT", "dependencies": { - "whatwg-mimetype": "^4.0.0", - "whatwg-url": "^14.0.0" + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.0" }, "engines": { - "node": ">=18" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/data-urls/node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/data-urls/node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/data-urls/node_modules/whatwg-url": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, "node_modules/dateformat": { @@ -8988,16 +8990,16 @@ "license": "MIT" }, "node_modules/html-encoding-sniffer": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", - "integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", "dev": true, "license": "MIT", "dependencies": { - "whatwg-encoding": "^3.1.1" + "@exodus/bytes": "^1.6.0" }, "engines": { - "node": ">=18" + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, "node_modules/html-escaper": { @@ -9016,20 +9018,6 @@ "url": "https://locize.com" } }, - "node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/http-response-object": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/http-response-object/-/http-response-object-3.0.2.tgz", @@ -9133,19 +9121,6 @@ "@babel/runtime": "^7.23.2" } }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/ignore": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", @@ -10556,35 +10531,36 @@ } }, "node_modules/jsdom": { - "version": "26.1.0", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz", - "integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==", + "version": "29.1.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz", + "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==", "dev": true, "license": "MIT", "dependencies": { - "cssstyle": "^4.2.1", - "data-urls": "^5.0.0", - "decimal.js": "^10.5.0", - "html-encoding-sniffer": "^4.0.0", - "http-proxy-agent": "^7.0.2", - "https-proxy-agent": "^7.0.6", + "@asamuzakjp/css-color": "^5.1.11", + "@asamuzakjp/dom-selector": "^7.1.1", + "@bramus/specificity": "^2.4.2", + "@csstools/css-syntax-patches-for-csstree": "^1.1.3", + "@exodus/bytes": "^1.15.0", + "css-tree": "^3.2.1", + "data-urls": "^7.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", "is-potential-custom-element-name": "^1.0.1", - "nwsapi": "^2.2.16", - "parse5": "^7.2.1", - "rrweb-cssom": "^0.8.0", + "lru-cache": "^11.3.5", + "parse5": "^8.0.1", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", - "tough-cookie": "^5.1.1", + "tough-cookie": "^6.0.1", + "undici": "^7.25.0", "w3c-xmlserializer": "^5.0.0", - "webidl-conversions": "^7.0.0", - "whatwg-encoding": "^3.1.1", - "whatwg-mimetype": "^4.0.0", - "whatwg-url": "^14.1.1", - "ws": "^8.18.0", + "webidl-conversions": "^8.0.1", + "whatwg-mimetype": "^5.0.0", + "whatwg-url": "^16.0.1", "xml-name-validator": "^5.0.0" }, "engines": { - "node": ">=18" + "node": "^20.19.0 || ^22.13.0 || >=24.0.0" }, "peerDependencies": { "canvas": "^3.0.0" @@ -10595,6 +10571,222 @@ } } }, + "node_modules/jsdom/node_modules/@asamuzakjp/css-color": { + "version": "5.1.11", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz", + "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/generational-cache": "^1.0.1", + "@csstools/css-calc": "^3.2.0", + "@csstools/css-color-parser": "^4.1.0", + "@csstools/css-parser-algorithms": "^4.0.0", + "@csstools/css-tokenizer": "^4.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, + "node_modules/jsdom/node_modules/@csstools/color-helpers": { + "version": "6.1.3", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.3.tgz", + "integrity": "sha512-c6CpX5G1pvuOKTXiRFJ54Lzc8zQrZ3qUjp44QC5DJNt1OmA1vmfUxOMCcKdDqsvffVDG0/MHnY63J+Mn0nmdUg==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/jsdom/node_modules/@csstools/css-calc": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.4.tgz", + "integrity": "sha512-Jwo1Z8DUsZ8xVOLBdLMfhjJFvWD6pqaUTlBNQZ+qIB2i9g7yG8kd/UBJj2c9J9Twr+u87cjy9BjkmfvMbyOk3Q==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.3", + "@csstools/css-tokenizer": "^4.0.3" + } + }, + "node_modules/jsdom/node_modules/@csstools/css-color-parser": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.8.tgz", + "integrity": "sha512-JLsKBee9dmnA3L+H+vYK4lQ6n5CoY3yEnh33zdlMutRfrTxtqt+hFeoZ1maHRt5vLw67huDLpOkDb3rl9A51MQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^6.1.3", + "@csstools/css-calc": "^3.4.4" + }, + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^4.0.3", + "@csstools/css-tokenizer": "^4.0.3" + } + }, + "node_modules/jsdom/node_modules/@csstools/css-parser-algorithms": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.3.tgz", + "integrity": "sha512-EpCfUDaJtwohPHC7egoXxPGT/R1/WyyAhw87MKB/7BPPZvZU+IcEqo4er5FpLnby2Gvwt9Lpxy+WNEDyFjoXtA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^4.0.3" + } + }, + "node_modules/jsdom/node_modules/@csstools/css-tokenizer": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.3.tgz", + "integrity": "sha512-gdkFe/Z4KU1q8Y5S3GYScXGcOnO56dgWwIs5+97Ij1VIKISItOIUlCXUq4VLbdnRclF+SSQ49sLsn3KeV111AA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=20.19.0" + } + }, + "node_modules/jsdom/node_modules/entities": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-9.0.0.tgz", + "integrity": "sha512-oJFNDJg3kTPwAD1cNn2+WmUq4wFoo09npc3Ydf1D7ED4smRiWrsKnaLxykrTWgyGEcusc87P5dxlAleol9kpkg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20.19.0" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jsdom/node_modules/parse5": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.1.1.tgz", + "integrity": "sha512-EcR/6WDcU7b2N3vQSxKALCk9lXGtUMQxXio008OEMBE0kavu/7JLfBEeFPzi43nMqVDSbEn3QCK+BMCc9zO//w==", + "dev": true, + "license": "MIT", + "dependencies": { + "entities": "^9.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/jsdom/node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/jsdom/node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, + "node_modules/jsdom/node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/jsdom/node_modules/whatwg-url": { + "version": "16.0.1", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz", + "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.11.0", + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -11063,14 +11255,6 @@ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", "license": "MIT" }, - "node_modules/lodash.get": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", - "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", - "deprecated": "This package is deprecated. Use the optional chaining (?.) operator instead.", - "dev": true, - "license": "MIT" - }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", @@ -11194,6 +11378,13 @@ "node": ">= 18" } }, + "node_modules/mdn-data": { + "version": "2.27.1", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz", + "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/memory-pager": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz", @@ -11592,39 +11783,6 @@ } } }, - "node_modules/msw/node_modules/tldts": { - "version": "7.4.19", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.19.tgz", - "integrity": "sha512-48dH6aSpQnpbzDUc4vIQZ1VjB8tkK+e8c1yx05/SZK+rkssgjEOlxDd/yU8/a4vGYQ9vRgJr9dwMq9TJ0b3X2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "tldts-core": "^7.4.19" - }, - "bin": { - "tldts": "bin/cli.js" - } - }, - "node_modules/msw/node_modules/tldts-core": { - "version": "7.4.20", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.20.tgz", - "integrity": "sha512-C630TWXZCZmLq0F2bW4QqwnaaxCQ/svpAqvJwnC4JvgEM5ohhBnGsEzTLSOXcN+xjz+kEaHS5uoWIw2klnqd0A==", - "dev": true, - "license": "MIT" - }, - "node_modules/msw/node_modules/tough-cookie": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", - "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "tldts": "^7.0.5" - }, - "engines": { - "node": ">=16" - } - }, "node_modules/msw/node_modules/type-fest": { "version": "5.10.0", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz", @@ -11789,13 +11947,6 @@ "node": ">= 20" } }, - "node_modules/nwsapi": { - "version": "2.2.28", - "resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.28.tgz", - "integrity": "sha512-IlVB7OS7qrOsVYlpnFIkETjMwT9jwvmocJmmM+GZU/PAB3uGi9Ezd7vcWhWBUnSc0ya4ppmQITOyP1ez9gg8cg==", - "dev": true, - "license": "MIT" - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -12893,13 +13044,6 @@ "fsevents": "~2.3.2" } }, - "node_modules/rrweb-cssom": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz", - "integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==", - "dev": true, - "license": "MIT" - }, "node_modules/run-parallel": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", @@ -12954,13 +13098,6 @@ "node": ">=10" } }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, - "license": "MIT" - }, "node_modules/saxes": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", @@ -13603,22 +13740,22 @@ } }, "node_modules/tldts": { - "version": "6.1.86", - "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz", - "integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.5.4.tgz", + "integrity": "sha512-Rn2ABgjHZrA+jzqom5zhxA0hLohzYrIgfCPyhpTUxqsUrcsBYuab49LseR9waB9Jr8/MxdodvMHA91oRiGLO3Q==", "dev": true, "license": "MIT", "dependencies": { - "tldts-core": "^6.1.86" + "tldts-core": "^7.5.4" }, "bin": { "tldts": "bin/cli.js" } }, "node_modules/tldts-core": { - "version": "6.1.86", - "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz", - "integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==", + "version": "7.5.4", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.5.4.tgz", + "integrity": "sha512-9+4zWtKEDZ3V3FoZ1B97rv+5z5oqp7yeXGVze3CxgQ+CJro9do9DCPD00wxstYZDXDMXsurkBerFfiB6GYtPbA==", "dev": true, "license": "MIT" }, @@ -13636,13 +13773,13 @@ } }, "node_modules/tough-cookie": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz", - "integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.1.0.tgz", + "integrity": "sha512-FTxc8u8Kl2tz0Lat1u8ksvcy8bwHRyEMawwTWybo51JqaC6O7SvfuhAKg+Ld6VqyIe2QRJBzY9HA7y2WyFRT2w==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "tldts": "^6.1.32" + "tldts": "^7.0.5" }, "engines": { "node": ">=16" @@ -14205,28 +14342,14 @@ "node": ">=12" } }, - "node_modules/whatwg-encoding": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", - "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", - "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", - "dev": true, - "license": "MIT", - "dependencies": { - "iconv-lite": "0.6.3" - }, - "engines": { - "node": ">=18" - } - }, "node_modules/whatwg-mimetype": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", - "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz", + "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==", "dev": true, "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/whatwg-url": { diff --git a/package.json b/package.json index 88168d129..0471ce511 100644 --- a/package.json +++ b/package.json @@ -73,15 +73,14 @@ "brace-expansion": "^5.0.12", "js-yaml": "^4.3.2", "fast-uri": "^3.1.9", - "discord-html-transcripts": { - "undici": "^6.29.1" - }, + "undici@^5": "^6.29.1", "discord-giveaways": { "deepmerge-ts": "^8.0.1" }, "@istanbuljs/load-nyc-config": { "js-yaml": "^3.15.1" - } + }, + "jsdom": "^29.1.1" }, "dependencies": { "@anthropic-ai/sdk": "0.128.0", @@ -117,7 +116,7 @@ "@types/jest": "30.0.0", "@types/node": "24.19.2", "@types/prompts": "2.4.9", - "better-npm-audit": "3.11.0", + "better-npm-audit": "4.2.1", "cross-env": "10.1.0", "eslint": "10.14.0", "eslint-config-prettier": "10.1.8", From d39350854a876dde6ca2b7391e119b71f3695cf3 Mon Sep 17 00:00:00 2001 From: "Kkermit." <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:04:02 +0000 Subject: [PATCH 5/7] fix: Stop start-up quietly on a reload and run the dev bot on shared's source --- AGENTS.md | 40 +++++++++++++++++++--------- README.md | 21 ++++++++------- docs/dashboard/guide.md | 23 +++++++++-------- package.json | 2 +- scripts/devAll.ts | 43 +++++++++++++++++++++---------- shared/package.json | 8 ++++++ src/core/shutdown.ts | 5 ++++ src/database/connection.ts | 10 ++++--- src/index.ts | 7 +++-- src/lib/bot/startup.util.ts | 27 ++++++++++++++++--- tests/database/connection.test.ts | 30 ++++++++++++++++++++- tests/lib/bot/startup.test.ts | 28 ++++++++++++++++++++ tests/scripts/devAll.test.ts | 30 ++++++++++++++++++++- 13 files changed, 217 insertions(+), 57 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 496f87186..c5ebebe5a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -872,7 +872,12 @@ script draws with the same `painter`, `box`, `badge` and `stepLine`. Three thing happens. `explainStartupFailure` turns `EnvError` (each unset variable with where to find it), `SetupError`, and Discord's 401, 10002 and 50001 into advice; only an error it does not recognise keeps its stack, because that is a bug. `exitOnFatalClose` catches gateway close codes 4004 and 4014: without it a bot missing the privileged - intents logged one line and then waited for ever, never becoming ready. + intents logged one line and then waited for ever, never becoming ready. **A signal partway through start-up ends + it quietly.** `shutdown()` closes the database while `main()` is still starting, so a reload mid-start used to + print "connected", then the log history failing and the connection "lost" — what its own shutdown had done. The + report is built with `stopWhen(isShuttingDown)`: it prints nothing once shutting down, its next step throws + `StartupStopped`, and `main().catch` leaves the exit to `shutdown()`. A disconnect `disconnectDatabase` asked for is + never reported as a lost connection. - **Boxes are measured, not guessed.** `visibleWidth` strips colour codes and counts `\p{Emoji_Presentation}` as two columns and everything else as one; counting a range of code points put `➜` at two, which pushed the right edge of one line out. Keep every box line under 80 columns, which is why the hints are short. @@ -2465,6 +2470,16 @@ restarts the bot on every save, which the ordering cannot help with, so the prox with one line per outage — Vite registers its handler immediately **after** calling `configure`, so the replacement waits a tick, and that ordering was read out of `vite/dist/node/chunks/node.js` rather than guessed. +**The dev bot runs `@testify/shared` from its source.** `npm run dev` and `BOT_WATCH` pass `--conditions=development`, +which the `exports` in `shared/package.json` answer with `src/index.ts`, so a change there restarts the bot like any +other and nothing has to be built first. Building it first was the old answer, and both halves of it went wrong: on +macOS the watcher saw that write and restarted the bot a second in, and a branch switched under a running `dev:all` +left it on a build without an export the new code read. **A synced +folder is named, not left to look like a bug:** iCloud Drive, Dropbox and Google Drive touch files as they sync, which +restarts the bot over and over, and macOS cancels a read of a file still downloading, which crashes it with +`ECANCELED`. `dev:all` recognises that line (`syncedFolderRead`) and says once to move the project or name its folder +`.nosync`; the README's troubleshooting table says the same for `npm run dev`. + ### `@testify/shared` is a real package, not an alias **It is deliberately absent from `tsconfig.json`'s `paths`, and adding it there would break the build in a way @@ -2475,22 +2490,23 @@ type-checks, and the only symptom is an empty object at runtime. So the workspace resolves like any other package, and each consumer reads what suits it: -| Consumer | Reads | Needs a build? | -| ----------------- | ------------------------- | -------------- | -| `tsc` | `types: "src/index.ts"` | No | -| Jest | an explicit source mapper | No | -| Vite | an alias to source | No | -| The bot's `dist/` | `main: "dist/index.js"` | **Yes** | +| Consumer | Reads | Needs a build? | +| ----------------- | ---------------------------------------- | -------------- | +| `tsc` | the `types` export, `src/index.ts` | No | +| Jest | an explicit source mapper | No | +| Vite | an alias to source | No | +| The dev bot | the `development` export, `src/index.ts` | No | +| The bot's `dist/` | the `require` export, `dist/index.js` | **Yes** | `prepare` builds it after any install, so a fresh clone works. Editing `shared/src` and then running the built bot is the one case that needs `npm run build:shared` by hand. > [!WARNING] -> **`tsx` reads the built `dist`, not the source — and `shared/dist` is gitignored.** So does the dev bot, not -> just the production one. Pull a commit that adds an export to `shared/src`, run the bot without reinstalling, -> and that export is `undefined` at runtime: every route validating with it dies on -> `Cannot read properties of undefined (reading 'safeParse')`, naming nothing that points at the cause. `dev` -> and `dev:all` now build shared first — about 40ms — so the state cannot happen. +> **Anything that runs without the `development` condition reads `shared/dist`, and it is gitignored.** That is the +> built bot and any other `tsx` run — `npm run setup`, the docs generators. Pull a commit that adds an export to +> `shared/src`, run one of those without reinstalling, and that export is `undefined` at runtime: a schema read from +> it dies on `Cannot read properties of undefined (reading 'safeParse')`, naming nothing that points at the cause. +> The dev bot once did exactly that, mid-session, after a branch switch. `shared/` stays dependency-light: zod and nothing else. No discord.js, no React. diff --git a/README.md b/README.md index 7c707e265..ce89b174e 100644 --- a/README.md +++ b/README.md @@ -862,16 +862,17 @@ The colours and links live in `src/config/theme.ts`. ## 🩺 Troubleshooting -| Symptom | Fix | -| ------------------------------------------------ | ---------------------------------------------------------------------------------------------------- | -| `Your .env file needs attention` | The message lists exactly which values are wrong. Optional ones can be left blank | -| `querySrv ECONNREFUSED` | Your DNS cannot resolve the Atlas address. Try another network, or use the non-SRV connection string | -| `MongoServerError: bad auth` | Wrong database password, or `` was left in the connection string | -| `Maximum number of application commands reached` | You are over Discord's limit of 100. Group commands under a shared parent — the error explains how | -| `Used disallowed intents` | Turn the privileged intents on in the Developer Portal | -| `EBADENGINE` during install | Your Node is older than 24.11. Run `nvm use` | -| Cards render with no text on them | You are in a container without fonts — use this repository's `Dockerfile` | -| `Sign in to confirm you're not a bot` | YouTube is refusing the host. Update yt-dlp, or set `/play` to SoundCloud only | +| Symptom | Fix | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | +| `Your .env file needs attention` | The message lists exactly which values are wrong. Optional ones can be left blank | +| `querySrv ECONNREFUSED` | Your DNS cannot resolve the Atlas address. Try another network, or use the non-SRV connection string | +| `MongoServerError: bad auth` | Wrong database password, or `` was left in the connection string | +| `Maximum number of application commands reached` | You are over Discord's limit of 100. Group commands under a shared parent — the error explains how | +| `Used disallowed intents` | Turn the privileged intents on in the Developer Portal | +| `EBADENGINE` during install | Your Node is older than 24.11. Run `nvm use` | +| Cards render with no text on them | You are in a container without fonts — use this repository's `Dockerfile` | +| `Sign in to confirm you're not a bot` | YouTube is refusing the host. Update yt-dlp, or set `/play` to SoundCloud only | +| `ECANCELED`, or the dev bot restarts on its own | The project is in a synced folder, such as an iCloud Desktop. Move it, or rename it to end in `.nosync` | Still stuck? [Ask in Discord](https://discord.gg/xcMVwAVjSD) or [open an issue](https://github.com/Kkkermit/Testify/issues/new/choose). diff --git a/docs/dashboard/guide.md b/docs/dashboard/guide.md index 6486486cb..7172d4c3a 100644 --- a/docs/dashboard/guide.md +++ b/docs/dashboard/guide.md @@ -101,22 +101,23 @@ only symptom is an empty object at runtime. Each consumer reads what suits it: -| Consumer | Reads | Needs a build? | -| ----------------- | ------------------------- | -------------- | -| `tsc` | `types: "src/index.ts"` | No | -| Jest | an explicit source mapper | No | -| Vite | an alias to source | No | -| The bot's `dist/` | `main: "dist/index.js"` | **Yes** | +| Consumer | Reads | Needs a build? | +| ----------------- | ---------------------------------------- | -------------- | +| `tsc` | the `types` export, `src/index.ts` | No | +| Jest | an explicit source mapper | No | +| Vite | an alias to source | No | +| The dev bot | the `development` export, `src/index.ts` | No | +| The bot's `dist/` | the `require` export, `dist/index.js` | **Yes** | `prepare` builds it after any install. Editing `shared/src` and then running the **built** bot is the one case needing `npm run build:shared` by hand. > [!WARNING] -> **This bit once cost an afternoon.** `tsx` resolves `@testify/shared` to `dist/index.js`, so the **dev** bot -> reads the build too, and `shared/dist` is gitignored — pulling never refreshes it. A new export in -> `shared/src` is then `undefined` at runtime and every route using it 500s with -> `Cannot read properties of undefined (reading 'safeParse')`. `npm run dev` and `npm run dev:all` build shared -> first now, so it cannot recur. +> **This bit once cost an afternoon.** Anything run without the `development` condition resolves +> `@testify/shared` to `dist/index.js`, and `shared/dist` is gitignored — pulling never refreshes it. A new export +> in `shared/src` is then `undefined` at runtime and every route using it 500s with +> `Cannot read properties of undefined (reading 'safeParse')`. `npm run dev` and `npm run dev:all` pass the +> condition, so the dev bot always reads the source. `shared/` stays dependency-light: **zod and nothing else.** No discord.js, no React. diff --git a/package.json b/package.json index 88168d129..964a59e4a 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "dashboard:dev": "npm run dev --workspace dashboard", "db:wipe": "tsx scripts/wipeDatabase.ts", "db:wipe:dev": "tsx scripts/wipeDatabase.ts --dev", - "dev": "npm run build:shared && cross-env NODE_ENV=development tsx watch --clear-screen=false src/index.ts", + "dev": "cross-env NODE_ENV=development tsx watch --clear-screen=false --conditions=development src/index.ts", "dev:all": "tsx scripts/devAll.ts", "docs:commands": "tsx scripts/generateCommandDocs.ts", "i18n:commands": "tsx scripts/commandStrings.ts", diff --git a/scripts/devAll.ts b/scripts/devAll.ts index e75d8624d..727c16d3c 100644 --- a/scripts/devAll.ts +++ b/scripts/devAll.ts @@ -14,6 +14,9 @@ const paint = painter(); const GRACE_MS = 5_000; +/** Shared runs from its source, through its `development` export, so it can never be an old build. */ +export const BOT_WATCH = ["watch", "--clear-screen=false", "--conditions=development", "src/index.ts"]; + function label(name: string): string { const colour = COLOURS[name]; return colour === undefined || !colourEnabled() ? `[${name}] ` : `${paint.bold(paint[colour](`[${name}]`))} `; @@ -37,9 +40,34 @@ function child(script: string, args: string[]): ChildProcess { }); } +/** macOS cancels a read of a file that iCloud Drive, or another sync client, has not finished downloading. */ +export function syncedFolderRead(chunk: string): boolean { + return chunk.includes("ECANCELED: operation canceled"); +} + +let toldAboutSync = false; + function pipe(name: string, process_: ChildProcess): void { process_.stdout?.on("data", (chunk: Buffer) => process.stdout.write(prefixLines(name, chunk.toString()))); - process_.stderr?.on("data", (chunk: Buffer) => process.stderr.write(prefixLines(name, chunk.toString()))); + process_.stderr?.on("data", (chunk: Buffer) => { + const text = chunk.toString(); + process.stderr.write(prefixLines(name, text)); + if (toldAboutSync || !syncedFolderRead(text)) return; + toldAboutSync = true; + print( + [ + "macOS cancelled reading a file, which is what a folder kept in sync", + "by iCloud Drive, Dropbox or Google Drive does while it downloads one.", + "The same syncing touches files, so the bot keeps restarting too.", + "With Desktop & Documents on, iCloud syncs ~/Desktop and ~/Documents.", + "", + `${paint.cyan("➜")} Move the project somewhere not synced, such as ~/Developer,`, + " or rename its folder to end in .nosync, which iCloud leaves alone.", + ], + "warning", + "The project folder is being synced", + ); + }); } export function stopTree(target: ChildProcess, signal: NodeJS.Signals = "SIGTERM"): void { @@ -103,17 +131,6 @@ function main(): void { const values = readyToStart(resolve(root, ".env.development")); if (values === null) process.exit(1); - // Build shared first: `tsx` resolves it to its `dist`, and a stale one breaks every validating route. - const shared = spawnSync(process.execPath, [resolve(root, "node_modules/tsup/dist/cli-default.js")], { - cwd: resolve(root, "shared"), - stdio: "pipe", - }); - if (shared.status !== 0) { - process.stderr.write(`${shared.stdout.toString()}${shared.stderr.toString()}`); - print(["Run `npm run build:shared` on its own to see why."], "error", "Could not build @testify/shared"); - process.exit(1); - } - print( [ `${label(BOT)}the Discord bot, restarting whenever a file under src/ is saved`, @@ -128,7 +145,7 @@ function main(): void { const tsx = resolve(root, "node_modules/tsx/dist/cli.mjs"); const children = [ - [BOT, child(tsx, ["watch", "--clear-screen=false", "src/index.ts"])], + [BOT, child(tsx, BOT_WATCH)], [WEB, child(tsx, ["scripts/devWeb.ts"])], ] as const; diff --git a/shared/package.json b/shared/package.json index 678aa8b82..4bb3626a3 100644 --- a/shared/package.json +++ b/shared/package.json @@ -18,5 +18,13 @@ }, "devDependencies": { "tsup": "9.0.0" + }, + "exports": { + ".": { + "types": "./src/index.ts", + "development": "./src/index.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + } } } diff --git a/src/core/shutdown.ts b/src/core/shutdown.ts index e384bff29..6db11a80f 100644 --- a/src/core/shutdown.ts +++ b/src/core/shutdown.ts @@ -11,6 +11,11 @@ import { destroyAllSessions } from "@lib/music/musicSession.util"; let stopping = false; +/** True from the first signal on, so start-up stops instead of reporting what shutting down undid. */ +export function isShuttingDown(): boolean { + return stopping; +} + /** Stops timers, closes the database and disconnects, then exits. */ export async function shutdown(client: TestifyClient, reason: string, code = 0): Promise { if (stopping) return; diff --git a/src/database/connection.ts b/src/database/connection.ts index 412f1073d..fd89fb755 100644 --- a/src/database/connection.ts +++ b/src/database/connection.ts @@ -13,6 +13,8 @@ interface ConnectOptions { } let everConnected = false; +/** Set by `disconnectDatabase`, so the disconnect it asks for is not reported as a lost connection. */ +let closing = false; /** Turns the driver's failure into something you can act on. */ export function explainConnectionFailure(error: unknown, uri: string): string { @@ -93,10 +95,11 @@ export async function connectDatabase(options: ConnectOptions): Promise { - // Only worth saying after a connection has been lost. - if (everConnected) + // Only worth saying after a connection has been lost, and not when shutting down closed it. + if (everConnected && !closing) options.logger.warn("[DATABASE] Lost the connection to MongoDB. Mongoose is reconnecting on its own."); }); mongoose.connection.on("reconnected", () => { @@ -104,7 +107,7 @@ export async function connectDatabase(options: ConnectOptions): Promise { // The retry loop below reports a failure to connect, so this would only say the same thing twice. - if (everConnected) + if (everConnected && !closing) options.logger.error({ err: toError(error) }, "[DATABASE_ERROR] The MongoDB connection reported an error."); }); @@ -155,6 +158,7 @@ export async function pingDatabase(timeoutMs = 2_000): Promise { } export async function disconnectDatabase(): Promise { + closing = true; if (mongoose.connection.readyState === mongoose.ConnectionStates.disconnected) return; await mongoose.disconnect(); } diff --git a/src/index.ts b/src/index.ts index 85cb1ced1..a41564716 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,7 +5,7 @@ import { botName } from "@core/brand"; import { TestifyClient } from "@core/client"; import { loadEverything, publishCommands, publishScope } from "@core/loader"; import { createLogger } from "@core/logger"; -import { handleProcessSignals } from "@core/shutdown"; +import { handleProcessSignals, isShuttingDown } from "@core/shutdown"; import { connectDatabase } from "@database/connection"; import { BootReport, @@ -29,7 +29,7 @@ async function main(): Promise { const client = new TestifyClient(env, logger); handleProcessSignals(client); - const report = new BootReport(); + const report = new BootReport().stopWhen(isShuttingDown); report.header({ name: botName(), version: botVersion(), @@ -88,6 +88,7 @@ async function main(): Promise { exitOnFatalClose(client); report.note("working", "Discord", "logging in…"); await client.login(env.DISCORD_TOKEN); + if (isShuttingDown()) return; // After login, so the cache is filled; a website that fails to start does not stop the bot. if (website) { @@ -99,6 +100,8 @@ async function main(): Promise { // Startup is the one place a failure still exits: a bot that never connected has nothing to keep alive. main().catch((error: unknown) => { + // A reload or Ctrl+C partway through: shutdown() is already exiting, and whatever failed was its doing. + if (isShuttingDown()) return; printStartupFailure(error); process.exit(1); }); diff --git a/src/lib/bot/startup.util.ts b/src/lib/bot/startup.util.ts index d8959500a..7cce8de89 100644 --- a/src/lib/bot/startup.util.ts +++ b/src/lib/bot/startup.util.ts @@ -18,15 +18,30 @@ type Write = (line: string) => void; const toStdout: Write = (line) => process.stdout.write(`${line}\n`); /** Prints one line per start-up step as it finishes, so a slow or failing step is visible where it happens. */ +/** Start-up was cut short by a reload or Ctrl+C; shutdown is already on its way out, so nothing is reported. */ +export class StartupStopped extends Error { + constructor() { + super("Start-up stopped because the bot is shutting down."); + this.name = "StartupStopped"; + } +} + export class BootReport { readonly #write: Write; readonly #paint: Paint; + #stopped: () => boolean = () => false; constructor(write: Write = toStdout, paint: Paint = painter()) { this.#write = write; this.#paint = paint; } + /** Once this answers true no line is printed, and the step running then ends start-up with `StartupStopped`. */ + stopWhen(stopped: () => boolean): this { + this.#stopped = stopped; + return this; + } + header(facts: BootFacts): void { const paint = this.#paint; this.#write(""); @@ -38,21 +53,27 @@ export class BootReport { } note(state: StepState, label: string, detail: string, ms?: number): void { + if (this.#stopped()) return; this.#write(stepLine(state, label, detail, ms, this.#paint)); } /** Runs one step and reports it; a failure is marked on its own line and then thrown on for the caller to explain. */ async step(label: string, work: () => Promise | T, describe: (result: T) => string): Promise { const started = performance.now(); + let result: T; try { - const result = await work(); - this.note("done", label, describe(result), performance.now() - started); - return result; + result = await work(); } catch (error) { + // A step that failed because shutting down closed what it was using is not a failure worth reporting. + if (this.#stopped()) throw new StartupStopped(); this.note("failed", label, this.#paint.red("could not finish"), performance.now() - started); throw error; } + + if (this.#stopped()) throw new StartupStopped(); + this.note("done", label, describe(result), performance.now() - started); + return result; } } diff --git a/tests/database/connection.test.ts b/tests/database/connection.test.ts index 6922e0bba..864a6adf8 100644 --- a/tests/database/connection.test.ts +++ b/tests/database/connection.test.ts @@ -1,6 +1,6 @@ import { getServers } from "node:dns"; import mongoose from "mongoose"; -import { explainConnectionFailure, pingDatabase } from "@database/connection"; +import { connectDatabase, disconnectDatabase, explainConnectionFailure, pingDatabase } from "@database/connection"; const SECRET = "sup3rs3cr3tw0rd"; const URI = `mongodb+srv://user:${SECRET}@cluster0.example.mongodb.net/testify`; @@ -110,3 +110,31 @@ describe("pingDatabase", () => { await expect(pingDatabase()).resolves.toBeNull(); }); }); + +describe("what the connection reports about itself", () => { + const events = ["disconnected", "reconnected", "error"] as const; + const before = Object.fromEntries(events.map((event) => [event, mongoose.connection.listeners(event)])); + + afterEach(() => { + for (const event of events) { + for (const listener of mongoose.connection.listeners(event)) { + if (!before[event]?.includes(listener)) mongoose.connection.off(event, listener as () => void); + } + } + jest.restoreAllMocks(); + }); + + /** Shutting down closed the connection, and the log said it had been lost and Mongoose was reconnecting. */ + it("warns about a connection that is lost, and not about the one shutting down closes", async () => { + jest.spyOn(mongoose, "connect").mockResolvedValue(mongoose); + const logger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn() }; + await connectDatabase({ uri: URI, logger: logger as never }); + + mongoose.connection.emit("disconnected"); + await disconnectDatabase(); + mongoose.connection.emit("disconnected"); + + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/Lost the connection/)); + }); +}); diff --git a/tests/lib/bot/startup.test.ts b/tests/lib/bot/startup.test.ts index bdd8b8abc..8db38fad4 100644 --- a/tests/lib/bot/startup.test.ts +++ b/tests/lib/bot/startup.test.ts @@ -8,6 +8,7 @@ import { FATAL_CLOSE_CODES, nodeTooOld, startupFailureLines, + StartupStopped, } from "@lib/bot/startup.util"; const plain = painter(false); @@ -127,6 +128,33 @@ describe("BootReport", () => { expect(lines[0]).toMatch(/✔ Modules\s+3 loaded/); expect(lines[1]).toMatch(/✖ Database/); }); + + /** A reload mid-start printed "connected", then the failures its own shutdown caused, as if both were true. */ + it("says nothing once the bot is shutting down, and ends start-up rather than report what that undid", async () => { + const lines: string[] = []; + let stopping = false; + const report = new BootReport((line) => lines.push(line), plain).stopWhen(() => stopping); + + const connecting = report.step( + "Database", + () => { + stopping = true; + return "ok"; + }, + () => "connected", + ); + await expect(connecting).rejects.toBeInstanceOf(StartupStopped); + await expect( + report.step( + "Logs", + () => Promise.reject(new Error("Client must be connected before running operations")), + () => "", + ), + ).rejects.toBeInstanceOf(StartupStopped); + report.note("working", "Discord", "logging in…"); + + expect(lines).toEqual([]); + }); }); describe("nodeTooOld", () => { diff --git a/tests/scripts/devAll.test.ts b/tests/scripts/devAll.test.ts index ab871a610..c903f4f17 100644 --- a/tests/scripts/devAll.test.ts +++ b/tests/scripts/devAll.test.ts @@ -1,5 +1,7 @@ import { type ChildProcess } from "node:child_process"; -import { prefixLines, stopTree } from "../../scripts/devAll"; +import { readFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { BOT_WATCH, prefixLines, stopTree, syncedFolderRead } from "../../scripts/devAll"; /** How a child's output is prefixed; the Windows interrupt behaviour itself needs a Windows terminal. */ @@ -70,3 +72,29 @@ describe("stopping a child", () => { killSpy.mockRestore(); }); }); + +describe("watching the bot", () => { + /** + * The dev bot read shared's build: a branch switch under a running dev:all crashed it on an export the build lacked, + * and rebuilding it at start restarted the bot a second in, because macOS reported the write. + */ + it("runs shared from its source, the same way in npm run dev and dev:all", () => { + const read = (path: string): unknown => JSON.parse(readFileSync(resolve(__dirname, "../..", path), "utf8")); + const { scripts } = read("package.json") as { scripts: Record }; + const { exports } = read("shared/package.json") as { exports: Record> }; + + expect(BOT_WATCH).toContain("--conditions=development"); + expect(exports["."]?.["development"]).toBe("./src/index.ts"); + expect(scripts["dev"]).toContain(`tsx ${BOT_WATCH.join(" ")}`); + }); + + /** A project on an iCloud-synced Desktop crashed on every restart with nothing to say why. */ + it("recognises the read macOS cancels in a synced folder, and nothing else", () => { + const cancelled = "Error: ECANCELED: operation canceled, read\n at Object.readFileSync (node:fs:440:20)"; + + expect([syncedFolderRead(cancelled), syncedFolderRead("Error: ENOENT: no such file or directory")]).toEqual([ + true, + false, + ]); + }); +}); From 7c6153320805b06704bb8b9a26d4eb846c8e8684 Mon Sep 17 00:00:00 2001 From: "Kkermit." <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:37:42 +0000 Subject: [PATCH 6/7] fix: Draw punctuation and accented letters in the start-up banner's name --- src/lib/bot/banner.util.ts | 37 ++++++++++++++++++++++++++++++++++-- tests/lib/bot/banner.test.ts | 21 ++++++++++++++++++-- 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/src/lib/bot/banner.util.ts b/src/lib/bot/banner.util.ts index 2019985a3..4fd0fc3d0 100644 --- a/src/lib/bot/banner.util.ts +++ b/src/lib/bot/banner.util.ts @@ -34,6 +34,7 @@ export const ICONS = { const RELOAD_GLYPH = "\u21BB"; +// figlet's ANSI Shadow, six rows of it. const LETTERS: Record = { A: [" █████╗ ", "██╔══██╗", "███████║", "██╔══██║", "██║ ██║", "╚═╝ ╚═╝"], B: ["██████╗ ", "██╔══██╗", "██████╔╝", "██╔══██╗", "██████╔╝", "╚═════╝ "], @@ -72,12 +73,44 @@ const LETTERS: Record = { "8": [" █████╗ ", "██╔══██╗", "╚█████╔╝", "██╔══██╗", "╚█████╔╝", " ╚════╝ "], "9": [" █████╗ ", "██╔══██╗", "╚██████║", " ╚═══██║", " █████╔╝", " ╚════╝ "], "-": [" ", " ", "█████╗", "╚════╝", " ", " "], + ".": [" ", " ", " ", " ", "██╗", "╚═╝"], + ",": [" ", " ", " ", " ", "▄█╗", "╚═╝"], + "!": ["██╗", "██║", "██║", "╚═╝", "██╗", "╚═╝"], + "?": ["██████╗ ", "╚════██╗", " ▄███╔╝", " ▀▀══╝ ", " ██╗ ", " ╚═╝ "], + ":": [" ", "██╗", "╚═╝", "██╗", "╚═╝", " "], + ";": [" ", "██╗", "╚═╝", "▄█╗", "▀═╝", " "], + _: [" ", " ", " ", " ", "███████╗", "╚══════╝"], + "/": [" ██╗", " ██╔╝", " ██╔╝ ", " ██╔╝ ", "██╔╝ ", "╚═╝ "], + "(": [" ██╗", "██╔╝", "██║ ", "██║ ", "╚██╗", " ╚═╝"], + ")": ["██╗ ", "╚██╗", " ██║", " ██║", "██╔╝", "╚═╝ "], + "[": ["███╗", "██╔╝", "██║ ", "██║ ", "███╗", "╚══╝"], + "]": ["███╗", "╚██║", " ██║", " ██║", "███║", "╚══╝"], + "<": [" ██╗", " ██╔╝", "██╔╝ ", "╚██╗ ", " ╚██╗", " ╚═╝"], + ">": ["██╗ ", "╚██╗ ", " ╚██╗", " ██╔╝", "██╔╝ ", "╚═╝ "], + "#": [" ██╗ ██╗ ", "████████╗", "╚██╔═██╔╝", "████████╗", "╚██╔═██╔╝", " ╚═╝ ╚═╝ "], + $: ["▄▄███▄▄ ", "██╔════╝", "███████╗", "╚════██║", "███████║", "╚═▀▀▀══╝"], + "%": ["██╗ ██╗", "╚═╝██╔╝", " ██╔╝ ", " ██╔╝ ", "██╔╝██╗", "╚═╝ ╚═╝"], + "&": [" ██╗ ", " ██║ ", "████████╗", "██╔═██╔═╝", "██████║ ", "╚═════╝ "], + "*": [" ", "▄ ██╗▄", " ████╗", "▀╚██╔▀", " ╚═╝ ", " "], + "@": [" ██████╗ ", "██╔═══██╗", "██║██╗██║", "██║██║██║", "╚█║████╔╝", " ╚╝╚═══╝ "], + "^": [" ███╗ ", "██╔██╗", "╚═╝╚═╝", " ", " ", " "], + // The font leaves these blank, so they are drawn to match it. + "'": ["██╗", "██║", "╚═╝", " ", " ", " "], + '"': ["██╗██╗", "██║██║", "╚═╝╚═╝", " ", " ", " "], + "+": [" ", " ██╗ ", "██████╗", "╚═██╔═╝", " ╚═╝ ", " "], + "=": [" ", "██████╗", "╚═════╝", "██████╗", "╚═════╝", " "], + "\\": ["██╗ ", "╚██╗ ", " ╚██╗ ", " ╚██╗ ", " ╚██╗", " ╚═╝"], + "|": ["██╗", "██║", "██║", "██║", "██║", "╚═╝"], " ": [" ", " ", " ", " ", " ", " "], }; -/** Turns a word into six lines of block capitals. */ +/** Turns a name into six lines of block capitals, without accents, leaving out any character the font cannot draw. */ export function bigText(text: string): string[] { - const glyphs = [...text.toUpperCase()].map((character) => LETTERS[character]).filter((glyph) => glyph !== undefined); + const plain = text + .normalize("NFD") + .replace(/\p{Mn}/gu, "") + .toUpperCase(); + const glyphs = [...plain].map((character) => LETTERS[character]).filter((glyph) => glyph !== undefined); if (glyphs.length === 0) return []; return Array.from({ length: 6 }, (_unused, line) => glyphs.map((glyph) => glyph[line] ?? "").join("")); diff --git a/tests/lib/bot/banner.test.ts b/tests/lib/bot/banner.test.ts index 424c7a2ea..c7bbc75aa 100644 --- a/tests/lib/bot/banner.test.ts +++ b/tests/lib/bot/banner.test.ts @@ -28,12 +28,29 @@ describe("bigText", () => { }); it("skips characters it has no glyph for rather than breaking the block", () => { - const widths = new Set(bigText("A-B!").map((line) => [...line].length)); + const widths = new Set(bigText("A-B✓").map((line) => [...line].length)); expect(widths.size).toBe(1); }); it("returns nothing for a name it cannot draw at all", () => { - expect(bigText("!!!")).toEqual([]); + expect(bigText("✓✓✓")).toEqual([]); + }); + + /** A bot called Fixxer2.0 was drawn as FIXXER20, because the font had no full stop. */ + it("draws the punctuation a bot's name can hold, each glyph a rectangle", () => { + const width = (text: string): number => [...(bigText(text)[0] ?? "")].length; + const punctuation = [...".,!?:;'\"-_+=/\\|()[]<>#$%&*@^"]; + const broken = punctuation.filter((mark) => { + const lines = bigText(mark); + return lines.length !== 6 || new Set(lines.map((line) => [...line].length)).size !== 1 || width(mark) === 0; + }); + + expect(broken).toEqual([]); + expect(width("Fixxer2.0")).toBe(width("Fixxer20") + width(".")); + }); + + it("draws an accented letter as the letter", () => { + expect(bigText("Café")).toEqual(bigText("Cafe")); }); }); From 790065ebb33f4d426f3b03b52e03a1bb2117fdc0 Mon Sep 17 00:00:00 2001 From: "Kkermit." <132657029+Kkkermit@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:09:59 +0000 Subject: [PATCH 7/7] chore: Bumped the version to 2.4.6 --- .github/ISSUE_TEMPLATE/bug_report.yml | 2 +- dashboard/package.json | 2 +- package-lock.json | 8 ++++---- package.json | 2 +- shared/package.json | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index f0d01fb3f..f0af0a69d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -50,7 +50,7 @@ body: id: version attributes: label: Testify version or commit - placeholder: 2.4.5 + placeholder: 2.4.6 validations: required: true diff --git a/dashboard/package.json b/dashboard/package.json index 77eb26470..a39817ca3 100644 --- a/dashboard/package.json +++ b/dashboard/package.json @@ -1,6 +1,6 @@ { "name": "@testify/dashboard", - "version": "2.4.5", + "version": "2.4.6", "private": true, "type": "module", "scripts": { diff --git a/package-lock.json b/package-lock.json index 03170922c..5275b9311 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "testify", - "version": "2.4.5", + "version": "2.4.6", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "testify", - "version": "2.4.5", + "version": "2.4.6", "license": "MIT", "workspaces": [ "shared", @@ -70,7 +70,7 @@ }, "dashboard": { "name": "@testify/dashboard", - "version": "2.4.5", + "version": "2.4.6", "dependencies": { "@tanstack/react-query": "5.107.1", "@testify/shared": "*", @@ -14596,7 +14596,7 @@ }, "shared": { "name": "@testify/shared", - "version": "2.4.5", + "version": "2.4.6", "license": "MIT", "dependencies": { "zod": "4.6.7" diff --git a/package.json b/package.json index 62a29e226..88d1860ab 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "testify", - "version": "2.4.5", + "version": "2.4.6", "description": "Self-hosted, all-in-one Discord bot in TypeScript: every command works as slash and prefix, with a web dashboard", "main": "dist/index.js", "license": "MIT", diff --git a/shared/package.json b/shared/package.json index 4bb3626a3..9499785b3 100644 --- a/shared/package.json +++ b/shared/package.json @@ -1,6 +1,6 @@ { "name": "@testify/shared", - "version": "2.4.5", + "version": "2.4.6", "private": true, "description": "Types and zod schemas shared by the bot's API and the dashboard.", "license": "MIT",