diff --git a/CLAUDE.md b/CLAUDE.md index 4f40a05..b6b81f7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -45,7 +45,7 @@ Never modify: `data/` contents on the server (`/root/Dezio/data`, live user data - Build and test on this PC: `source ~/.cargo/env; cargo build --release` and `cargo test` (about 227 unit tests). Tests that need the internet are `#[ignore]`d (`cargo test live_ -- --ignored`). - Without `DEZIO_LIVE=1` the binary only lists its commands and exits. **Never run it with the real token on this PC**: the live bot would answer twice. - Local website for testing: `cargo build && DISCORD_BOT_TOKEN=dev-placeholder target/debug/dezio --web-dev` → http://127.0.0.1:8099 (also the `dezio-web-dev` entry in `.claude/launch.json`). -- Server: the Chromebook, `ssh root@192.168.1.71` (Arch Linux, x86_64). Bot in `/root/Dezio` (binary `dezio`, `assets/`, `web/`, `data/`, `.env`). `dezio-bot.service` runs `/root/Dezio/dezio --headless`, Restart=always; website on 127.0.0.1:8080, public at https://astar76.com. Logs: `journalctl -u dezio-bot`. +- Server: the Chromebook, `ssh root@192.168.1.71` (Arch Linux, x86_64). Bot in `/root/Dezio` (binary `dezio`, `assets/`, `web/`, `data/`, `.env`). `dezio-bot.service` runs `/root/Dezio/dezio --headless`, Restart=always; website on 127.0.0.1:8080, public at https://archlinux.tail7c4f5e.ts.net. Logs: `journalctl -u dezio-bot`. - The server's line is slow: measured about 425 KB/s down and **114 KB/s (≈ 0.9 Mbit/s) up**, on `wlan0`. `dezio-shape.service` (deploy/shape-upload.sh, installed as `/usr/local/bin/dezio-shape`) caps internet-bound upload at 800 kbit with fq_codel so voice packets go first. Voice and every upload share that. - Discord HTTP client: one twilight `Client` with a 180 s timeout for every call (`src/main.rs`). `/download` retries uploads 3 times (`UPLOAD_RETRIES`), so a file that can't finish in 180 s costs 9+ minutes (seen 2026-11-12: a 9.2 MB video, 3 timeouts, handler took 792 s). - Discord's attachment limit for bots is 10 MiB unless the server is boosted (tier 2: 50 MiB, tier 3: 100 MiB). `media::upload_limit` reads the server's tier; `FALLBACK_UPLOAD_LIMIT` lives in `download/plan.rs`. @@ -64,7 +64,7 @@ Never modify: `data/` contents on the server (`/root/Dezio/data`, live user data - Upload time, not file size, is what breaks: at ~100 KB/s a 10 MiB file needs ~105 s on an idle line and much longer with voice. Any upload path must think in seconds. - Retrying a whole upload that timed out just repeats the timeout. Retry only on errors that can succeed the second time. - yt-dlp, ffmpeg, gallery-dl and curl are child processes fed user links: never pass user text where it can become an option (`--`), keep the private-network check (`safe_redirects`, music's check) on every fetch. -- Security testing runs against a **local copy only** (`--web-dev` on 127.0.0.1). Never send attack traffic to https://astar76.com or Discord. Never connect to Tor or proxies. +- Security testing runs against a **local copy only** (`--web-dev` on 127.0.0.1). Never send attack traffic to https://archlinux.tail7c4f5e.ts.net or Discord. Never connect to Tor or proxies. - Discord changes can't be tested on this PC; things only the owner checks in Discord are marked 🧑. - `/help` pages and slash registration change when commands are added or removed: run the help-limits test. diff --git a/Cargo.lock b/Cargo.lock index 1345ad2..b0d57d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -745,7 +745,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" dependencies = [ "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -1408,9 +1408,9 @@ dependencies = [ [[package]] name = "form_urlencoded" -version = "1.2.3" +version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" dependencies = [ "percent-encoding", ] @@ -5900,9 +5900,9 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.9" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", "idna", diff --git a/PLAN.md b/PLAN.md index 978d140..950571a 100644 --- a/PLAN.md +++ b/PLAN.md @@ -16,10 +16,6 @@ security test has been done beyond earlier spot fixes. `/image` (`D!fx`) bundles recovering from drops, shaping tuned with the bot. - Phase 2 — Image commands: `/image` and `D!fx` removed; `/speechbubble` and `/caption` (and their `D!` versions) work like the well-known caption bots. -- Phase 2b — fm commands: every fm feature gets its data from ListenBrainz and MusicBrainz (plus the cover - fallbacks), with no leftover Last.fm API logic; only song links still point to the Last.fm website. -- Phase 2c — Website path: all of Dezio's website moves to `/dezio/` on the Tailscale URL; the root gets a minimal - landing page (to be improved later). - Phase 3 — Security: website and dashboard, media inputs, commands and abuse, dependency audit; fixes for what is found; tested on a local copy only. - Phase 4 — Deploy and owner check in Discord. diff --git a/Plans/01 Network/S001-upload-by-speed.md b/Plans/01 Network/S001-upload-by-speed.md deleted file mode 100644 index 72b8ea0..0000000 --- a/Plans/01 Network/S001-upload-by-speed.md +++ /dev/null @@ -1,37 +0,0 @@ -# S001 — Uploads timed by line speed - -> Category 01 Network · Model: Sonnet · Effort: medium · Depends on: — · Size: L · Human: no -> Files touched: src/commands/media/mod.rs, src/commands/media/download/{mod,plan}.rs, src/commands/media/convert.rs, src/commands/music/card.rs, src/hosted.rs, src/main.rs, other callers of attachments - -## Goal -Every Discord upload is planned in seconds, not bytes (D-001): a result that would not upload in about 60-90 s at the measured ~114 KB/s, or is over the server's Discord limit, is sent as a website link (`hosted.rs`) instead. Uploads are retried only on errors that can succeed the second time; a timed-out upload is never repeated as is. PLAN Phase 1, first bullet. - -## Read -- `src/commands/media/mod.rs` `upload_limit` (line ~130; still says 20 MiB for tier 0/1, Discord's real bot limit is 10 MiB) -- `src/commands/media/download/mod.rs` lines ~30-80 (constants) and ~290-400 (`upload`, `download`) -- `src/commands/media/download/plan.rs` top constants (`FALLBACK_UPLOAD_LIMIT`) -- `src/hosted.rs` (whole, 102 lines) -- `src/main.rs` line ~527 (Discord client with 180 s timeout) -- `grep -rn "Attachment::from_bytes\|attachments(" src` to list the other upload paths; read only the call sites - -## Steps -- [x] Fold in the owner's loose edit (seen uncommitted in the main checkout, not in this worktree): tier 0/1 limit is 10 MiB, `FALLBACK_UPLOAD_LIMIT` = 10 MiB, `upload_limit` returns the real Discord limit (10/50/100 MiB) — do it here cleanly, with a newline after `let limit = …;` -- [x] Add one shared helper in `media/mod.rs` that returns the byte budget for one upload: `min(discord_limit, UPLOAD_SECONDS × UPLOAD_BYTES_PER_SEC)`, both named constants with a comment (114 KB/s measured 2026-11-12, see CLAUDE.md §2), plus a pure function with a unit test -- [x] `/download`: plan the target size from that budget; anything bigger goes to `hosted.rs` as a link (existing path); retry only on errors that are not timeouts (connection reset before sending, 5xx, rate limit); a timeout ends retries and falls back to the link -- [x] Other upload paths (convert, music animated card, quote, the grep list): use the same budget; oversize → link or a smaller encode, whichever the path already supports -- [x] Discord HTTP timeout: keep 180 s for uploads, but give plain API calls a shorter timeout if twilight allows it per request; otherwise write in PROGRESS "Later" why not (not done: per-request timeout, see PROGRESS Later) -- [x] `docs/tests/S001-upload-by-speed.md` from the test-file template (checks: budget math, link fallback, no retry after timeout, each upload path) -- [x] PROGRESS entry, INDEX line, commit `S001: …` - -## End criteria -- `source ~/.cargo/env; cargo build` compiles with no new warnings. -- `grep -n "UPLOAD_RETRIES" src` shows the retry only on retryable errors. -- `ls docs/tests/S001-*` exists. - -## Pitfalls -- No test runs, release builds or server deploys in this plan; the test phase does them. -- Don't touch `.env` or `data/`. The hosted link must keep the private-network checks. -- Upload time, not file size, is what breaks (CLAUDE.md §4). - -## Handoff (→ PROGRESS.md) -Name of the budget helper and its constants, so S002 and S008 reuse them. diff --git a/Plans/01 Network/S002-outbound-timeouts.md b/Plans/01 Network/S002-outbound-timeouts.md deleted file mode 100644 index 082882a..0000000 --- a/Plans/01 Network/S002-outbound-timeouts.md +++ /dev/null @@ -1,35 +0,0 @@ -# S002 — Timeouts on every outbound call - -> Category 01 Network · Model: Sonnet · Effort: medium · Depends on: S001 · Size: M · Human: no -> Files touched: src/state.rs, src/commands/media/download/tools.rs, src/commands/media/{ffmpeg,convert,quote,emoji}.rs, src/commands/music/{source,ytdl}.rs, other files found by the grep - -## Goal -Every outbound HTTP call and every child process (yt-dlp, ffmpeg, gallery-dl, curl) has a named time limit, is killed when it runs over, and ends in a plain error card. Nothing can hang a command forever on the slow line. D-002, PLAN Phase 1 third bullet. - -## Read -- `src/state.rs` line ~50 (shared reqwest client, 20 s timeout) -- `src/commands/media/download/tools.rs` lines ~25-130 (the run-with-cancel helper and yt-dlp args) -- `grep -rn "Command::new\|tokio::process" src` and `grep -rn "reqwest::Client\|\.timeout(" src`: read only call sites without a timeout or kill -- `src/error.rs` (`bail_user!`) - -## Steps -- [x] List every outbound call site and child process with its current limit; put the list in the test file's Built section -- [x] Child processes: one shared run helper (reuse `tools.rs` if it fits) with a time limit, `kill_on_drop(true)` and a clear error; switch every caller that lacks one -- [x] HTTP: calls that download big bodies (media fetch, covers) get a size cap and a total timeout; separate clients built outside `state.rs` get timeouts -- [x] Time limits as named constants next to their use, with why the number (e.g. download size ÷ 425 KB/s down) -- [x] User errors: timeouts show "took too long" cards through `bail_user!`, not raw errors -- [x] `docs/tests/S002-outbound-timeouts.md` (checks: a stuck child is killed, a slow server times out, error card text) -- [x] PROGRESS entry, INDEX line, commit `S002: …` - -## End criteria -- `cargo build` compiles. -- `grep -rn "Command::new" src` call sites all go through a helper with a timeout, or the test file says why not. -- `ls docs/tests/S002-*` exists. - -## Pitfalls -- Never pass user text where it can become an option (`--`). Keep `safe_redirects` on every fetch. -- Music streaming processes run for the whole song: their limit is "no data for N s", not total time. -- No test runs here. - -## Handoff (→ PROGRESS.md) -The helper's name and the list of limits. diff --git a/Plans/01 Network/S003-recovery-and-shaping.md b/Plans/01 Network/S003-recovery-and-shaping.md deleted file mode 100644 index bbfa4ac..0000000 --- a/Plans/01 Network/S003-recovery-and-shaping.md +++ /dev/null @@ -1,34 +0,0 @@ -# S003 — Gateway, voice and music recovery; shaping - -> Category 01 Network · Model: Sonnet · Effort: medium · Depends on: S002 · Size: M · Human: no -> Files touched: src/main.rs (gateway loop), src/commands/music/{mod,source}.rs, deploy/shape-upload.sh - -## Goal -The bot recovers by itself when the line drops: the gateway reconnects, voice reconnects or leaves cleanly, the music queue resumes or tells the user, and nothing stays stuck. The upload shaping (`dezio-shape`) is checked against real numbers and tuned. PLAN Phase 1, bullets four and five. - -## Read -- `src/main.rs` lines ~520-600 (client and the `shard.next_event` loop) -- `src/commands/music/mod.rs`: the voice join and track-end/error handlers only (grep `songbird`, `Event::`, `disconnect`) -- `deploy/shape-upload.sh` -- Server, read-only first: `ssh root@192.168.1.71 'journalctl -u dezio-bot --since -7d | grep -iE "reconnect|disconnect|gateway|voice" | tail -50; tc -s qdisc show dev wlan0'` - -## Steps -- [x] From the logs, list the drop cases that happened; add them to the test file -- [x] Gateway: errors from `next_event` never end the loop silently; fatal ones are logged and the process exits so systemd restarts it (Restart=always) -- [x] Voice/music: on a voice driver disconnect, try to reconnect a named number of times, then leave and tell the channel; no queue or "now playing" state left stuck -- [x] Shaping: measure upload once on the server (small timed upload, no external speed sites besides what the script already uses), adjust the cap in `shape-upload.sh` if the measure says so, with the number and date in a comment. Tell the orchestrator before reinstalling `dezio-shape` on the server; back up `/usr/local/bin/dezio-shape` first (D-005) -- [x] `docs/tests/S003-recovery-and-shaping.md` -- [x] PROGRESS entry, INDEX line, commit `S003: …` - -## End criteria -- `cargo build` compiles. -- `ssh root@192.168.1.71 systemctl is-active dezio-shape` says active (if it was reinstalled). -- `ls docs/tests/S003-*` exists. - -## Pitfalls -- Never run the bot with the real token on this PC. -- Do not deploy the bot binary in this plan; S011 does it. -- Never connect to Tor or proxies. - -## Handoff (→ PROGRESS.md) -Measured upload speed and the new cap, if changed. diff --git a/Plans/02 Image commands/S004-remove-image-add-caption.md b/Plans/02 Image commands/S004-remove-image-add-caption.md deleted file mode 100644 index e389bdf..0000000 --- a/Plans/02 Image commands/S004-remove-image-add-caption.md +++ /dev/null @@ -1,34 +0,0 @@ -# S004 — Remove /image, add /caption - -> Category 02 Image commands · Model: Sonnet · Effort: medium · Depends on: — · Size: M · Human: no -> Files touched: src/commands/media/images.rs, src/commands/media/mod.rs, src/commands/help.rs (if it lists /image), web pages that list commands - -## Goal -`/image` and `D!fx` are removed with every effect and filter (D-003). New `/caption` and `D!caption` put a white band with the text above the picture, Assyst style. Inputs: PNG, JPG, WebP (still and animated), GIF, MP4/WebM/MOV (D-008); animated input stays animated, video comes back in a format Discord plays. Options: `source-attachment`, `source-link`, `text`; with no source it uses the replied/latest chat picture (D-007). `/petpet` and `/convert` stay. `convert.rs` imports `images::pick_opt`: keep it working. - -## Read -- `src/commands/media/images.rs` lines 160-200 (`speech_bubble`, `caption`), 240-320 (frames, GIF, `process`), 320-560 (`pick_opt`, `pick`, `run_job`, `image_cmd`, `petpet`, `commands`) -- `src/commands/media/ffmpeg.rs` only the parts for decoding video to frames and encoding back (grep `fn `) -- `docs/DECISIONS.md` D-003, D-007, D-008 -- `grep -rn "D!fx\|/image\|\"fx\"" src web` for help and website mentions - -## Steps -- [x] Remove `/image`, `D!fx`, `apply_filter`, `apply_effect`, effects/filters and their tests; keep `pick_opt`, `pick`, frame and GIF helpers, `petpet` -- [x] Caption drawing: white band sized to the wrapped text (fonts in `assets/`), text centred, black; band width = picture width; pure function with a unit test on band height for 1 and 3 lines -- [x] Media: still → PNG/JPG kept; GIF/animated WebP → GIF with every frame captioned; video → ffmpeg frames out, caption each, encode back (or ffmpeg `pad` + `drawtext` if simpler and the font is available); size limits through S001's budget helper if it exists, else `media::upload_limit` -- [x] Register `/caption` (slash + `D!caption`), help page entry, remove `/image` from help and website lists -- [x] `docs/tests/S004-caption.md` (checks per media type, empty text, very long text, huge input, bad link) -- [x] PROGRESS entry, INDEX line, commit `S004: …` - -## End criteria -- `cargo build` compiles. -- `grep -rn "D!fx\|apply_filter\|apply_effect" src web` returns nothing. -- `ls docs/tests/S004-*` exists. - -## Pitfalls -- Help pages must stay within Discord's limits (the help-limits test runs in the test phase). -- Video frames can be huge: cap frame count and size with named constants. -- No test runs here. - -## Handoff (→ PROGRESS.md) -Names of the shared media in/out helpers S005 reuses. diff --git a/Plans/02 Image commands/S005-speechbubble.md b/Plans/02 Image commands/S005-speechbubble.md deleted file mode 100644 index fada414..0000000 --- a/Plans/02 Image commands/S005-speechbubble.md +++ /dev/null @@ -1,33 +0,0 @@ -# S005 — /speechbubble - -> Category 02 Image commands · Model: Sonnet · Effort: medium · Depends on: S004 · Size: M · Human: no -> Files touched: src/commands/media/images.rs (or a new speechbubble.rs next to it), src/commands/help.rs - -## Goal -`/speechbubble` and `D!speechbubble` as in D-007, D-008 and D-009: a wide ellipse hanging off the top (or bottom) edge with a tail pointing into the picture. Options `source-attachment`, `source-link`, `position` top|bottom, `flip` (tail to the other side), `solid` (white fill with black outline, BSM style); without `solid` the bubble is cut out transparent (Assyst style) where the format allows. Same media types as `/caption`, through the helpers S004 left. - -## Read -- `docs/DECISIONS.md` D-007, D-008, D-009 -- S004's PROGRESS entry (helper names) -- `src/commands/media/images.rs`: the old `speech_bubble` (if S004 kept it) and the caption command as the pattern -- Look at a few frames of `assets/reference/speechbubble-bsm.gif` and `speechbubble-assyst.gif` (extract 2 frames with ffmpeg to the scratchpad and view them) - -## Steps -- [x] Bubble shape as a pure function: ellipse + tail mask for (width, height, position, flip); unit test that the tail side flips and that the mask touches the chosen edge -- [x] Draw: transparent cutout (alpha 0 inside the mask) or solid (white fill + black outline); the picture's edge follows the bubble's curve -- [x] Media: PNG out for still transparent; GIF with transparency for animated; video → GIF (transparency) or same format when `solid` -- [x] Register command (slash + `D!`), help entry -- [x] `docs/tests/S005-speechbubble.md` (checks per option and media type, compare with both reference GIFs on a contact sheet) -- [x] PROGRESS entry, INDEX line, commit `S005: …` - -## End criteria -- `cargo build` compiles. -- `ls docs/tests/S005-*` exists. - -## Pitfalls -- GIF transparency is one colour index: pick a key colour no frame uses. -- JPG cannot be transparent: output PNG. -- No test runs here; one quick render of a sample to the scratchpad to look at the shape is fine. - -## Handoff (→ PROGRESS.md) -What the owner should try in Discord (🧑 in S011). diff --git a/Plans/03 fm commands/S006-fm-on-metabrainz.md b/Plans/03 fm commands/S006-fm-on-metabrainz.md deleted file mode 100644 index d78819c..0000000 --- a/Plans/03 fm commands/S006-fm-on-metabrainz.md +++ /dev/null @@ -1,36 +0,0 @@ -# S006 — fm logic fully on ListenBrainz and MusicBrainz - -> Category 03 fm commands · Model: Sonnet · Effort: medium · Depends on: — · Size: M · Human: no -> Files touched: src/commands/lastfm/{api,mod,views,extras,art,covers}.rs, src/web/api.rs (fm link), web/ dashboard text if needed - -## Goal -The owner moved the fm commands from the Last.fm API to ListenBrainz (D-010) with covers from a fallback chain (D-011). Check over all the old fm logic: everything that used Last.fm data must now get it from ListenBrainz and MusicBrainz (plus the D-011 cover/photo fallbacks), with no hidden reliance on Last.fm-only fields. Only song links may still point to the Last.fm website (D-010). - -## Read -- `docs/DECISIONS.md` D-010, D-011 -- The two 2026-12-01 entries in `docs/PROGRESS.md` (known differences) -- `src/commands/lastfm/api.rs` (whole, 401 lines: the ListenBrainz → old Last.fm shape adapter) -- `grep -n "fn \|\[\"" src/commands/lastfm/{mod,views,extras,art}.rs` to find every field read from the adapter's JSON; read only the call sites -- `src/web/api.rs` lines ~155-240 (dashboard fm link) - -## Steps -- [x] List every fm feature (top lists, recent, profile, now playing, Who Knows, chart, Pixel Jumble, lyrics, dashboard link, any other user of `lastfm::`) and, for each, the JSON fields it reads; put the list in the test file's Built section -- [x] For every field, check the adapter fills it from ListenBrainz/MusicBrainz; fields Last.fm used to give that the adapter leaves empty (listeners, global playcount, user registered date, artist bio, tags, images) either get a MusicBrainz/ListenBrainz source or are removed from the card with no empty labels left -- [x] Remove dead Last.fm-only code (API key reads, method names, `audioscrobbler` leftovers, unused shapes); keep song links to the Last.fm website -- [x] User-facing text (help, error cards, dashboard, website, privacy) says ListenBrainz where it means the data source; fm errors (unknown ListenBrainz user, stats not ready yet) give plain cards -- [x] New pure logic (field mapping) gets a unit test with a saved ListenBrainz JSON sample, no network -- [x] `docs/tests/S006-fm-on-metabrainz.md` (one check per feature, live checks marked `cargo test listenbrainz_live -- --ignored`) -- [x] PROGRESS entry, INDEX line, commit `S006: …` - -## End criteria -- `cargo build` compiles. -- `grep -rni "audioscrobbler\|api_key\|LASTFM_API" src` returns nothing (or the test file says why a line stays). -- `ls docs/tests/S006-*` exists. - -## Pitfalls -- Do not touch `data/lastfm.json` (kept untouched, D-010); links live in `data/listenbrainz.json`. -- MusicBrainz needs the `Dezio/ (Discord bot)` user agent and about 1 request per second; don't add calls in loops without the existing rate handling. -- Keep the git tag `lastfm-api-backup` as is. No test runs here besides a compile check. - -## Handoff (→ PROGRESS.md) -Fields dropped from cards, and any fm feature that still can't match its Last.fm behaviour. diff --git a/Plans/03a Website path/S006a-dezio-path.md b/Plans/03a Website path/S006a-dezio-path.md deleted file mode 100644 index 0216f75..0000000 --- a/Plans/03a Website path/S006a-dezio-path.md +++ /dev/null @@ -1,38 +0,0 @@ -# S006a — Website under /dezio/, landing page at the root - -> Category 03a Website path · Model: Sonnet · Effort: medium · Depends on: — · Size: M · Human: 🧑 Discord Developer Portal (OAuth redirect, Activity URL mapping) -> Files touched: src/web/{mod,activity}.rs, src/hosted.rs, src/commands/gameboy.rs, web/**/*.{html,js,css}, docs/topgg.md, deploy/landing/index.html (new) - -## Goal -Move all of Dezio's website (site, dashboard, API, OAuth, Game Boy Activity, hosted `/f/` files) from the root of https://astar76.com to https://astar76.com/dezio/ (D-013). The root `/` becomes a very simple static landing page with links to `/dezio/` and `/git/`; the owner will improve it later, so keep it minimal. `/git` (Forgejo) stays as is. - -## Read -- `src/web/mod.rs` lines 1–70 (config, `DASHBOARD_URL`) and 280–320 (router) -- `src/web/activity.rs` lines 1–30 and 485–510 (routes) -- `src/hosted.rs` lines 15–35, `src/commands/gameboy.rs` lines 1–40 -- `grep -rn '"/' web` for absolute paths in pages, JS and CSS -- `docs/topgg.md` URL lines - -## Steps -- [x] Base path: derive it from the path part of `DASHBOARD_URL` (e.g. `https://…ts.net/dezio` → `/dezio`; none → `/`). Check with `tailscale serve --help` / docs whether `--set-path /dezio` strips the prefix before proxying (it is believed to strip it). Make the router work both ways: nest all routes under the base path and also accept un-prefixed paths, OR rely on stripping — pick one, say which in DECISIONS (D-013 addition). Cookie `Path` must match the base path. -- [x] Pages: every absolute link in `web/site`, `web/dashboard`, `web/activity` (`href="/…"`, `src="/…"`, `fetch("/api…")`, `/login`, `/assets`, `/images`, `/dashboard`, `/activity/api/…`) works under `/dezio/`. Prefer relative paths; where a page needs the base, inject it from the server once (no per-page copy-paste). OAuth `redirect_uri` stays `DASHBOARD_URL + "/callback"`. Redirects the server sends (login, logout, `slash_redirect`) carry the base path. -- [x] Hosted links (`hosted::store`) and `/gameboy` links come from `DASHBOARD_URL`, so they follow; check nothing else hard-codes `/f/` or `/activity` at the root. -- [x] Landing page: `deploy/landing/index.html`, one small static page (title, two links: Dezio → `/dezio/`, Source → `/git/`), plain inline CSS, no JS. Write the deploy commands into the plan's test file for S011, do not run them: copy to `/srv/landing/` on the server, `tailscale serve --bg --set-path / /srv/landing` (static files), `tailscale serve --bg --set-path /dezio http://127.0.0.1:8080`, set `DASHBOARD_URL=https://astar76.com/dezio` in `/root/Dezio/.env` (back it up first). Keep Funnel on. -- [x] Docs: `docs/topgg.md` website URL → `/dezio/`; the module comments in `src/web/mod.rs`, `src/web/activity.rs`, `src/commands/gameboy.rs` that name the portal setup. 🧑 list for the owner in the test file: Discord Developer Portal → OAuth2 Redirects add `https://astar76.com/dezio/callback`; Activities → URL Mappings `/` → `astar76.com/dezio/activity`; top.gg website field. -- [x] Unit test for the base-path parsing (pure function). -- [x] Test file `docs/tests/S006a-dezio-path.md`: local checks with `DASHBOARD_URL=http://127.0.0.1:8099/dezio --web-dev` (every page, asset, API call, login redirect, `/f/` link, activity page under the prefix; root of the local server does not serve Dezio pages), the deploy commands above, and the 🧑 portal list. -- [x] PROGRESS entry, INDEX line, commit `S006a: …` - -## End criteria -- `cargo check` passes; the new base-path unit test passes (`cargo test base_path`). -- `grep -rnE '(href|src|action)="/[a-z]|fetch\("/' web` shows no root-absolute path left (or each one is explained in the test file). -- `deploy/landing/index.html` exists. - -## Pitfalls -- Do not change the live server or Tailscale config in this plan; deploying is S011. -- The Game Boy Activity is loaded by Discord through its URL mapping; Discord's proxy prefixes paths itself (`/.proxy/`), so check how the page builds its API URLs before changing them. -- `--web-dev` without a path in `DASHBOARD_URL` must still work at `/` (base `/`). -- Old root links (`/dashboard`, `/f/…`) will no longer reach Dezio after the move; that is accepted (owner chose the landing page). - -## Handoff (→ PROGRESS.md) -Base-path rule, the server commands for S011, and the 🧑 portal changes. diff --git a/Plans/04 Security/S007-website-security.md b/Plans/04 Security/S007-website-security.md deleted file mode 100644 index 610e297..0000000 --- a/Plans/04 Security/S007-website-security.md +++ /dev/null @@ -1,33 +0,0 @@ -# S007 — Website and dashboard security - -> Category 04 Security · Model: Opus (hostile input, auth) · Effort: medium · Depends on: — · Size: L · Human: no -> Files touched: src/web/{mod,api,activity}.rs, web/ pages if needed - -## Goal -Find and fix security faults in the website, dashboard API, OAuth sign-in and Game Boy Activity (D-004). Attack traffic only against the local copy on 127.0.0.1:8099 (`--web-dev`), never the live site. - -## Read -- `src/web/mod.rs` (whole, 512 lines: sessions, cookies, `check_write`, OAuth, headers middleware, router) -- `src/web/api.rs` routes and the handlers that write -- `src/web/activity.rs` routes only (grep `route`, `fn `) -- CLAUDE.md §2 (local website command) - -## Steps -- [x] Review against a checklist written into the test file: auth on every API route, guild permission checks (user must manage the guild he edits), CSRF on writes (`check_write`), OAuth state, cookie flags, session expiry, input size limits, path traversal in static files, security headers, error leaks, rate limits on login and writes, WebSocket/activity input -- [x] Probe the local copy with curl for each item (start `--web-dev`, stop it at the end); write findings with severity in the test file -- [x] Fix every HIGH and MED finding in the code; each fix gets a unit test when it is pure logic, otherwise a check in the test file -- [x] LOW findings: fix if under a few lines, else PROGRESS "Later" -- [x] `docs/tests/S007-website-security.md` (checklist, findings, checks) -- [x] PROGRESS entry, INDEX line, commit `S007: …` - -## End criteria -- `cargo build` compiles. -- The test file lists every checklist item with a finding or "fine because …". - -## Pitfalls -- Never send traffic to https://astar76.com or Discord. No Tor or proxies. -- Never run the bot with the real token; `--web-dev` uses `DISCORD_BOT_TOKEN=dev-placeholder`. -- Don't break the existing web tests in `src/web/mod.rs`. - -## Handoff (→ PROGRESS.md) -Open findings not fixed, with severity. diff --git a/Plans/04 Security/S008-media-commands-deps.md b/Plans/04 Security/S008-media-commands-deps.md deleted file mode 100644 index 6f4e9da..0000000 --- a/Plans/04 Security/S008-media-commands-deps.md +++ /dev/null @@ -1,34 +0,0 @@ -# S008 — Media inputs, commands and dependencies - -> Category 04 Security · Model: Opus (hostile input) · Effort: medium · Depends on: S002 · Size: M · Human: no -> Files touched: src/commands/media/**, src/commands/music/{source,ytdl}.rs, src/cmd.rs, Cargo.toml/Cargo.lock if a dependency must move - -## Goal -Make media inputs, commands and dependencies safe against hostile users (D-004): links and files fed to yt-dlp, ffmpeg, gallery-dl and curl; decoding bombs; private-network fetches; command spam; known-vulnerable crates. - -## Read -- `src/commands/media/mod.rs` (`safe_redirects`, media fetch, line ~40-130) -- S002's PROGRESS entry (process helper) and the call-site list in `docs/tests/S002-outbound-timeouts.md` -- `src/commands/music/source.rs` the private-network check (grep `private\|loopback`) -- `src/cmd.rs` the dispatch and any cooldown code (grep `cooldown\|rate`) - -## Steps -- [x] Child processes: every user link goes after `--`, scheme limited to http(s), no `file:`/`data:`/local paths; ffmpeg protocol whitelist on inputs -- [x] Private network: every fetch (reqwest, yt-dlp, gallery-dl, ffmpeg, curl) blocks loopback/LAN/Tailscale ranges, including after redirects and DNS rebinding where it can be checked -- [x] Decode bombs: image and GIF decoding has limits on width, height, frame count and memory (`image` crate `Limits`); named constants -- [x] Abuse: per-user cooldown or concurrency limit on heavy commands (media, download, caption, speechbubble) if none exists -- [x] Dependencies: install and run `cargo audit` and `cargo deny check advisories`; update crates with fixes where it is a patch/minor bump, list the rest -- [x] `docs/tests/S008-media-commands-deps.md` (hostile inputs list, audit output summary) -- [x] PROGRESS entry, INDEX line, commit `S008: …` - -## End criteria -- `cargo build` compiles. -- `cargo audit` output saved in the test file; no unfixed HIGH advisory without a reason. - -## Pitfalls -- No attack traffic outside 127.0.0.1. Never connect to Tor or proxies. -- Don't loosen the existing checks while refactoring them. -- No test runs here. - -## Handoff (→ PROGRESS.md) -Advisories left open. diff --git a/Plans/05 Test and release/S009-test-runs-and-network.md b/Plans/05 Test and release/S009-test-runs-and-network.md deleted file mode 100644 index 86d7874..0000000 --- a/Plans/05 Test and release/S009-test-runs-and-network.md +++ /dev/null @@ -1,28 +0,0 @@ -# S009 — Test: it runs, and network - -> Category 05 Test and release · Model: Sonnet · Effort: medium · Depends on: S001, S002, S003 · Phase: test · Human: no -> Files touched: tests and fixes in src/**, docs/tests/S001-*, S002-*, S003-*, docs/TEST-REPORT.md - -## Goal -First make sure everything builds and the existing suite passes (fix breakage first). Then run the checks of `docs/tests/S001-upload-by-speed.md`, `S002-outbound-timeouts.md`, `S003-recovery-and-shaping.md`, fix what fails, and fill in every Result. - -## Read -- those three test files, all in one command; code only where a check needs it -- CLAUDE.md §2 and §5 for the build and test commands - -## Steps -- [x] It runs: `cargo build --release`, `cargo test` once (worktree-only failures from missing `assets/data` and ROMs are known, see PROGRESS), `target/debug/dezio` lists commands and exits; fix breakage first -- [x] Doubts first: read the code behind each doubt in the three files and add a check, or write why it is fine -- [x] Write the tests for all HIGH and MED checks in one go; share fixtures (a local slow HTTP server on 127.0.0.1, a stuck child process); no test for what the compiler already proves -- [x] Run them once, all together, short output; save the log to a file and read only the failures -- [x] Sort the failures by cause, then fix all causes in one go; a wrong test is corrected, never weakened to pass -- [x] Rerun only what failed; three rounds at most, then `KNOWN BUG` with the cause -- [x] Results filled in, `docs/TEST-REPORT.md` line, PROGRESS entry, INDEX line, commit `S009: …` - -## End criteria -- `cargo test` green, except listed known bugs and worktree-only asset failures -- no `—` left in the Result column of the three files: `pass`, `fixed`, `KNOWN BUG`, or `not run: why` - -## Pitfalls -- Never run with the real token; never call Discord. Discord-only checks are `not run: needs Discord`. -- Live-internet tests stay `#[ignore]`. diff --git a/Plans/05 Test and release/S010-test-images-security-app.md b/Plans/05 Test and release/S010-test-images-security-app.md deleted file mode 100644 index 6e2cb06..0000000 --- a/Plans/05 Test and release/S010-test-images-security-app.md +++ /dev/null @@ -1,29 +0,0 @@ -# S010 — Test: images, fm, security, whole app - -> Category 05 Test and release · Model: Sonnet · Effort: medium · Depends on: S004, S005, S006, S007, S008, S009 · Phase: test · Human: no -> Files touched: tests and fixes in src/**, docs/tests/S004-* to S008-*, docs/TEST-REPORT.md - -## Goal -Run the checks of `docs/tests/S004-caption.md`, `S005-speechbubble.md`, `S006-fm-on-metabrainz.md`, `S007-website-security.md`, `S008-media-commands-deps.md`, fix what fails, fill in every Result. Then the whole-app pass: help limits, command registry, website journeys, hostile input on everything that listens or parses, restart with old data. - -## Read -- those five test files, all in one command; code only where a check needs it -- CLAUDE.md §2 and §5 - -## Steps -- [x] Doubts first: read the code behind each doubt and add a check, or write why it is fine -- [x] Write the tests for all HIGH and MED checks in one go; share fixtures (sample PNG, JPG, GIF, animated WebP, short MP4/WebM/MOV generated with ffmpeg into the scratchpad) -- [x] Run them once, all together, short output; save the log and read only the failures -- [x] Sort the failures by cause, fix all causes in one go; rerun only what failed; three rounds at most, then `KNOWN BUG` -- [x] Screen checks: one contact sheet of caption and speechbubble outputs (every option, every media type) next to both reference GIFs, looked at once, faults fixed in one go, one more sheet -- [x] Whole app: `cargo test` (help-limits and registry tests included); `--web-dev` journey (pages, sign-in gate, dashboard API refuses without session); hostile input replay from S007/S008; start with a copy of old-format data files from the repo fixtures if any -- [x] Results filled in, `docs/TEST-REPORT.md` lines, PROGRESS entry, INDEX line, commit `S010: …` - -## End criteria -- `cargo test` green, except listed known bugs -- no `—` left in the Result column of the five files -- `rg -n "\| — \||KNOWN BUG|not run" docs/tests` shows no open HIGH - -## Pitfalls -- Local copy only for security replays; never the live site, Discord, Tor or proxies. -- Discord rendering is checked by the owner in S011 (🧑), not here. diff --git a/Plans/05 Test and release/S011-deploy-and-owner-check.md b/Plans/05 Test and release/S011-deploy-and-owner-check.md deleted file mode 100644 index 4ceaecd..0000000 --- a/Plans/05 Test and release/S011-deploy-and-owner-check.md +++ /dev/null @@ -1,48 +0,0 @@ -# S011 — Deploy and owner check - -> Category 05 Test and release · Model: Sonnet · Effort: medium · Depends on: S010 · Phase: test · Human: 🧑 owner tries /speechbubble and /caption in Discord -> Files touched: server /root/Dezio (binary, assets/, web/), docs/PROGRESS.md, docs/TEST-REPORT.md - -## Goal -Deploy the finished bot to the Chromebook, check it starts cleanly, and have the owner check the two image commands in Discord (D-006). PLAN Phase 4. - -## Read -- CLAUDE.md §2 (deploy steps) -- `docs/TEST-REPORT.md` and `rg -n "\| — \||KNOWN BUG|not run" docs/tests` (gate: no open HIGH) -- S005's PROGRESS entry (what the owner should try) - -## Steps -- [x] Gate: no open HIGH check or HIGH known bug; otherwise stop and report to the orchestrator (open HIGH are only "not run" Discord/voice/browser checks; owner accepted: "Yes, deploy") -- [x] Tell the orchestrator before deploying; `cargo build --release`; scp to `dezio.new`; on the server back up `dezio` as `dezio.bak-`, move in, `rsync -a` changed `assets/` and `web/`, `systemctl restart dezio-bot` -- [x] Check `systemctl status dezio-bot` and `journalctl -u dezio-bot -n 50`: logged in, commands registered, no errors; `curl -sI https://astar76.com` (plain GET, not attack traffic) returns 200 -- [ ] 🧑 Owner tries `/caption` and `/speechbubble` (every option, a GIF and a video) and `/download` of a ~9 MB video; record the answers in the test report -- [ ] PROGRESS entry, INDEX line, commit `S011: …` and push to `origin` - -## End criteria -- `ssh root@192.168.1.71 systemctl is-active dezio-bot` says active -- Owner's answers recorded in `docs/TEST-REPORT.md` - -## Pitfalls -- Never run the bot with the real token on this PC. -- Never touch `/root/Dezio/data` or `.env`; back up any server file before changing it. -- A restart drops music for a few seconds. - -## Deployed 2026-12-01 -Binary + `web/` deployed (backups on server: `dezio.bak-2026-12-01`, `web.bak-2026-12-01`). Server has no rsync; web copied with tar. Service active, 208 commands, 71 slash synced, ready in 9 guilds, site GET `/` and `/dezio/` return 200. The S006a tailscale/`.env` DASHBOARD_URL changes were NOT done (not in steps 1-3). - -## Owner must try in Discord/browser (step 4, HIGH first) -HIGH -1. `/download` of a clip that compresses to ~8-9 MB: arrives as attachment, one attempt, no long wait (S001-3). -2. `/download` of a source too big for 8.5 MB: gets a website link with 24 h notice, no attachment (S001-4). -3. Slow upload: link replaces attachment after one timeout, no 3x retry (S001-5, if you can force it). -4. Voice: play a song, check stays smooth during an upload; cut network ~60 s then restore: playback resumes; 3+ min: bot leaves with "Lost the voice connection" notice, `/play` works again (S003-1,2). -5. Stalled stream while playing: moves on after ~20 s (S002-1); `/convert` of a hanging host link answers within ~60 s (S002-2). -6. Server network cut 12 min: bot exits and systemd restarts it (S003-3) (optional, disruptive). -7. Browser: open a `/f//` hosted link in Firefox/Chrome: video plays inline (S007-4). -8. `/caption` and `/speechbubble`: every option, on an image, a GIF and a video (S004, S005, S008-13). -9. `/download` of a ~9 MB video (S011 step 4). -MED -10. `/convert` result over 8.5 MB gives a link (S001-8); `/convert` and caption on a normal mp4 work (S008-13). -11. Start `/caption` on a long video, then another at once: "You already have a media job running" (S008-14). -12. fm commands with a linked account (S006); `/convert` timeout and `/play` lookup timeout messages (S002-10,11). -13. Open `https://astar76.com/dezio/` (S007-10; works only after the S006a tailscale/.env change, still pending). diff --git a/Plans/INDEX.md b/Plans/INDEX.md index 0e52d45..132987d 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -6,30 +6,8 @@ Tracker: https://claude.ai/artifact/PRAT4HSkqn44d6QFDJeovp ## 01 Network -- [x] [S001 — Uploads timed by line speed](01%20Network/S001-upload-by-speed.md) -- [x] [S002 — Timeouts on every outbound call](01%20Network/S002-outbound-timeouts.md) -- [x] [S003 — Gateway, voice and music recovery; shaping](01%20Network/S003-recovery-and-shaping.md) - ## 02 Image commands -- [x] [S004 — Remove /image, add /caption](02%20Image%20commands/S004-remove-image-add-caption.md) -- [x] [S005 — /speechbubble](02%20Image%20commands/S005-speechbubble.md) +## 03 Security -## 03 fm commands - -- [x] [S006 — fm logic fully on ListenBrainz and MusicBrainz](03%20fm%20commands/S006-fm-on-metabrainz.md) - -## 03a Website path - -- [x] [S006a — Website under /dezio/, landing page at the root](03a%20Website%20path/S006a-dezio-path.md) 🧑 - -## 04 Security - -- [x] [S007 — Website and dashboard security](04%20Security/S007-website-security.md) -- [x] [S008 — Media inputs, commands and dependencies](04%20Security/S008-media-commands-deps.md) - -## 05 Test and release - -- [x] [S009 — Test: it runs, and network](05%20Test%20and%20release/S009-test-runs-and-network.md) -- [x] [S010 — Test: images, fm, security, whole app](05%20Test%20and%20release/S010-test-images-security-app.md) -- [ ] [S011 — Deploy and owner check](05%20Test%20and%20release/S011-deploy-and-owner-check.md) 🧑 +## 04 Deploy diff --git a/README.md b/README.md index 857b935..9e32a24 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

➕ Add to your server · - Website · + Website · Support server

diff --git a/deploy/landing/index.html b/deploy/landing/index.html deleted file mode 100644 index 01cc90d..0000000 --- a/deploy/landing/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - -Astar Hub - - - -
-

Astar Hub

-

Dezio Source

-
- - diff --git a/deploy/shape-upload.sh b/deploy/shape-upload.sh index cdbfb46..aacfbb8 100755 --- a/deploy/shape-upload.sh +++ b/deploy/shape-upload.sh @@ -11,8 +11,6 @@ # It turns itself off again after 2 minutes unless `keep` is the second word, so a mistake can't lock anyone out. set -eu DEV=wlan0 -# 800 kbit = 100 KB/s, 88% of the 114 KB/s measured on this line (CLAUDE.md). Checked 2026-12-01 against `tc -s qdisc`: -# 247 of 121k packets dropped in the capped class, none in the voice class, so the cap is kept. RATE=800kbit off() { tc qdisc del dev "$DEV" root 2>/dev/null || true; } diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 7fbae84..e6dbc52 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -13,6 +13,3 @@ - D-009 — 2026-11-12 — The Assyst-style output described in D-007 (transparent cutout, no outline, tail toward the right) is saved as `assets/reference/speechbubble-assyst.gif`, next to the BSM-style `speechbubble-bsm.gif` (D-008). Compare the drawn bubbles against both. — Owner request. — 02 Image commands. - D-010 — 2026-12-01 — The fm commands read ListenBrainz (free, no key) instead of the Last.fm API, which needs Pro for everything but scrobbling from 2026-12-01. Same commands and cards; links are stored separately in `data/listenbrainz.json` (`data/lastfm.json` is kept, untouched); song links still go to the Last.fm website (free, and the Listen button reads them). Lyrics song search uses Deezer (popularity-ranked, no key). The Last.fm version is the git tag `lastfm-api-backup`. — Owner request. — all fm commands. - D-011 — 2026-12-01 — Covers come from a chain (`src/commands/lastfm/covers.rs`): the release ID in the player's own tags (Cover Art Archive) → ListenBrainz's match → the release group → Deezer → iTunes; Deezer/iTunes results count only when artist and title match. Artist photos: Deezer → MusicBrainz/Wikimedia. Play counts match by MusicBrainz ID before names. — MusicBrainz art alone left many covers blank; owner asked for the most reliable sources with fallbacks. — fm commands. -- D-012 — 2026-12-01 — All fm logic must get its data from ListenBrainz and MusicBrainz (plus the D-011 cover/photo fallbacks); leftover Last.fm API logic and Last.fm-only fields are replaced or removed. Song links to the Last.fm website stay. — Owner request after the Last.fm API change. — S006, S010. -- D-013 — 2026-12-01 — All of Dezio's website (site, dashboard, API, OAuth, Game Boy Activity, hosted `/f/` files) moves to https://astar76.com/dezio/. The root `/` serves a minimal static landing page (links to `/dezio/` and `/git/`), which the owner will improve in a later session; old root links to Dezio are not redirected. `/git` stays Forgejo. — Owner request. — S006a, S007, S011. -- D-013 addition — 2026-12-01 — Base path = path part of `DASHBOARD_URL` (`/dezio`, none → root). The router serves every route both under the base and un-prefixed, so it works whether `tailscale serve --set-path` strips the prefix or not. HTML pages carry `__BASE__` (server replaces it); dashboard JS reads ``; site pages use relative paths; the Activity derives its base from `location.pathname` (so it also works at `/` inside Discord). Cookie `Path` = base. — Avoids guessing tailscale's behaviour. — S006a, S011. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index fa59ebe..992092b 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -14,68 +14,5 @@ One entry per session, newest last, ≤ 15 lines: done, verified how, not done, - Verified: `cargo test` (same 8 worktree-only asset failures); `cargo test covers_live -- --ignored` and `listenbrainz_live` pass. - Not done: not deployed at commit time; not checked in Discord 🧑. -## 2026-12-01 — S001 uploads by speed -- Done: `media::budget_for` / `upload_budget(ctx)` with `UPLOAD_SECONDS`=75 and `UPLOAD_BYTES_PER_SEC`=114_000 (reuse in S002, S008). Real limit 10 MiB. `/download` plans by budget, retries only reset/429/5xx, timeout becomes a website link. Convert and /media use the budget. -- Verified: `cargo check` only. /download video still over budget after compress goes out as a link. Music card already drops to a still on a slow line; quote/games send small images, left as is. Not done: link for audio/gallery over budget; per-call HTTP timeout (twilight sets one timeout per client). - ## Later -- Per-request shorter timeout for plain Discord API calls: not done in S001. - -## 2026-12-01 — S002 outbound timeouts -- Done: audit found most spawns and HTTP calls already limited. Fixed: `ffmpeg::probe` (no limit), `ffmpeg::inspect` (no kill), music stream and peaks (ffmpeg `-rw_timeout` 20 s idle, peaks read idle 30 s). Helper stays `download::tools::run_lines`. -- Verified: `cargo check` only. Not done: `bail_user!` rewrite of the plain timeout strings; not tested. -- S002 follow-up: timeout texts reworded in plain words (`ffmpeg::run`, `ytdl::extract`, VirusTotal wait). They are NOT `bail_user!`: those helpers return `Result<_, String>` (bail_user needs the command error type), and every caller already shows the string as a "❌ ..." reply. `download/tools.rs` already uses `DlError::user` cards. Turning the helpers into `UserError` would touch many callers; left for later. - -## 2026-12-01 — S003 recovery and shaping -- Done: gateway exits (systemd restarts) after 10 min of failed reconnects or when all shards stop; voice driver retries 8, watcher rejoins 3 times then leaves with a notice and clears the player. Shaping cap kept at 800 kbit (comment with numbers). -- Verified: `cargo check` only. Not tested, not deployed, `dezio-shape` not reinstalled, no upload measured. - -## 2026-12-01 — S004 /image removed, /caption added -- Done: `/image` + `D!fx` and all effects/filters gone. `/caption` + `D!caption` (options `source-attachment`, `source-link`, `text`; no source = latest media in channel via `convert::last_chat_media`). Still → PNG (JPEG if too big); GIF/animated WebP → GIF; video → MP4 (no sound, 10 s, 12 fps, 480 px max). Help and website text updated. -- Shared helpers for S005: `images::pick_opt`, `convert::last_chat_media`, `images::frames_of`, `encode_gif`, `caption_image` / `caption_video` pattern (band + `stack`), `ffmpeg::Scratch` + `ffmpeg::run`. `/speechbubble` is not added yet (S005). -- Verified: `cargo check` only. Not tested, not checked in Discord 🧑. - -## 2026-12-01 — S005 /speechbubble -- Done: `/speechbubble` + `D!speechbubble` (alias `bubble`; options `source-attachment`, `source-link`, `position`, `flip`, `solid`; prefix words `bottom flip solid`). Pure `bubble_mask` + `draw_bubble` in `images.rs`. Still → PNG, GIF/WebP → GIF (transparent), video → transparent GIF, or MP4 with `solid`. Video frame loop shared as `map_frames` (caption uses it too). -- Verified: `cargo check` only. Not tested, shape not compared with the reference GIFs, not checked in Discord 🧑 (S011). See `docs/tests/S005-speechbubble.md` doubts (GIF transparency, no anti-aliasing). - -## 2026-12-01 — S006 fm on ListenBrainz -- Done: audit of every fm feature; code was already fully on ListenBrainz/MusicBrainz, no Last.fm API leftovers in src. Only fix: `docs/topgg.md` wording. Test list in `docs/tests/S006-fm.md`. -- Dropped from cards: listeners, global plays, bio, tags (none were shown). Profile realname/country are skipped when empty. -- Verified: grep and `cargo check` only. Not tested in Discord 🧑. No new unit test (no new logic; api.rs already has sample-JSON tests). - -## 2026-12-01 — S006a website under /dezio/ -- Done: `Cfg.base` from `DASHBOARD_URL` path (`base_path`, unit test); routes nested under base and also un-prefixed; cookie Path, redirects, login link carry base; pages use `__BASE__`/relative paths; `deploy/landing/index.html` (minimal). topgg + module comments updated. -- Not done: nothing deployed. Static copy of web/dashboard/index.html now has `__BASE__` placeholders (only the bot serves it). -- Verified: `cargo check`, `cargo test base_path`. No browser check. Server commands + 🧑 portal list in `docs/tests/S006a-dezio-path.md`. - -## 2026-12-01 — S007 website security -- Done: review + local curl probes (findings table in `docs/tests/S007-website-security.md`). Fixed: sign-in rate limit (20/min) on `/callback` and Activity token; `/f/` files sandboxed by CSP; `/dezio` → `/dezio/` and `/dezio/` serves the site; ServeDir folder redirects off; Activity dev sessions refuse forwarded or non-local requests; `--web-dev` honours DASHBOARD_URL's path. -- Verified: `cargo test web::` (10/11; ROM test needs assets/roms), curl probes. Not checked in a browser (sandboxed video), not deployed. -- Later (LOW): role menus can offer a cosmetic role above the editor's own rank; `/api/places` and `web-session` have no rate limit. - -## 2026-12-01 — S008 media inputs and dependencies -- Done: one public-address check (`media::is_public_ip`, adds Tailscale 100.64/10, IPv4-in-IPv6, NAT64); `PublicDns` resolver on `state.web` (private DNS answers dropped, covers redirects/rebinding); ffmpeg/ffprobe protocol whitelists on local and stream inputs; playlists refused in /convert and video caption; gallery-dl `--`; decode limits (`pix::limits`, GIF/WebP frame memory cap); one convert/caption/speechbubble job per user; `url` 2.5.9. -- Verified: `cargo check` only. Not tested. Audit summary and test list in `docs/tests/S008-media-commands-deps.md`. -- Advisories left open: libcrux-* (davey, DAVE voice; 4 high), crypto-bigint, curve25519-dalek, ringbuf (songbird): need upstream major bumps. rustls 0.22/webpki 0.102 only in Cargo.lock, not built. -- Later: ffmpeg/yt-dlp/gallery-dl redirects and rebinding can't be checked from inside; an egress firewall for the bot's user on the server would close it. - -## 2026-12-01 — S009 test: it runs, network -- Done: release build ok; `cargo test` 249 pass, 8 worktree-only asset failures; binary lists commands. Added 2 child-process tests (timeout kill, cancel). Results filled in S001-S003 test files; `docs/TEST-REPORT.md` started. -- Not done: Discord, voice, network-cut and timed-upload checks (`not run`, need live bot/server). Nothing deployed. - -## 2026-12-01 — S010 test: images, fm, security, app -- Done: 6 new tests (S008 checks 2-8) pass; web-dev probes pass offline (S007 7 incl.); contact sheet of caption/speechbubble ok; Results filled in S004-S008 test files. -- Not done: Discord checks, video path via bot, browser check of `/f/` sandbox, `one_job` unit test, old-data restart. -- No bug found, no source fix. Nothing deployed. - -## 2026-12-01 — S011 deploy -- Done: gate ok (owner: "Yes, deploy"); release build; binary + `web/` on the Chromebook (backups `dezio.bak-2026-12-01`, `web.bak-2026-12-01`; no rsync there, used tar). Service active, 208 commands, 71 slash synced, 9 guilds; site `/` and `/dezio/` 200. -- Not done: step 4 (owner list in the S011 plan), INDEX tick, S006a tailscale/`.env` DASHBOARD_URL change, TEST-REPORT answers. - -## S006a server path change applied (2026-12-01) -- Backups on server: /root/tailscale-serve.bak-2026-12-01.json, /root/Dezio/.env.bak-2026-12-01. -- Landing page in /srv/landing; `/` serves it, `/dezio` proxies 127.0.0.1:8080, `/git` kept, Funnel on (use `tailscale funnel --bg --set-path`, plain `serve` turns Funnel off). -- .env DASHBOARD_URL now ends in /dezio; dezio-bot restarted, active, no errors. GET /, /dezio/, /dezio/dashboard, /dezio/terms, /git/ all 200. -- Owner still must do the Developer Portal steps (redirect URL, activity mapping, top.gg field). -- Fix (2026-12-01): Tailscale strips the `/dezio` prefix, so `/dezio` (no slash) served the page and relative CSS/images broke. Mapping is now `tailscale funnel --bg --set-path /dezio http://127.0.0.1:8080/dezio`; `/dezio` gives 308 to `/dezio/`. Backup: /root/tailscale-serve.bak-2026-12-01b.json. Use `funnel`, not `serve` (serve turns Funnel off). +- (none yet) diff --git a/docs/TEST-REPORT.md b/docs/TEST-REPORT.md deleted file mode 100644 index 88813ad..0000000 --- a/docs/TEST-REPORT.md +++ /dev/null @@ -1,4 +0,0 @@ -# Test report - -- S009 (2026-12-01): release build ok; `cargo test` 249 pass, 8 fail (all need `assets/data` or ROMs missing in this worktree: fun actions/animals, cookie, hangman, words x2, rolemenus preset, web ROM test); binary lists commands with a placeholder token. New unit tests: `stuck_child_is_killed_at_the_limit`, `cancel_ends_a_running_child` (pass). S001-S003 checks needing Discord, live voice or a network cut are `not run`. -- S010 (2026-12-01): 6 new tests (private DNS + redirect, playlist via ffmpeg bytes and local probe, playlist in frame cutting, 60 000 px PNG header, big-canvas GIF cap) all pass; `cargo test` 255 pass + 8 known worktree failures. `--web-dev` probes under `unshare -rn` (no network): sign-in gate 401, CSRF/Origin/content-type 403/403/415, 200 KB body 413, traversal 404, 21st sign-in 429, `/dezio?a=//evil.test` 308 same host. Contact sheet of caption/speechbubble looked at: shapes match references, no GIF ghosting. Not run: all Discord checks (S004 5-16, S005 6-15, S006 1-11), browser check of `/f/` sandbox, `one_job` test, live `fetch_limited`, cargo audit repeat, restart with old data (no old-format fixtures in repo). diff --git a/docs/tests/S001-upload-by-speed.md b/docs/tests/S001-upload-by-speed.md deleted file mode 100644 index 57dcd02..0000000 --- a/docs/tests/S001-upload-by-speed.md +++ /dev/null @@ -1,31 +0,0 @@ -# S001 — Uploads timed by line speed: test file - -Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. - -## Built -`src/commands/media/mod.rs` · `UPLOAD_SECONDS` (75), `UPLOAD_BYTES_PER_SEC` (114_000), `budget_for(limit)` pure, `upload_budget(ctx)`; `upload_limit` now 10/50/100 MiB. -`src/commands/media/download/mod.rs` · `/download` limit = budget; `upload()` retries only RequestError, 429, 5xx; timeout gives `DlError::UploadTimedOut`; `publish_link` hosts the files and shows links. -`convert.rs`, `images.rs` · use `upload_budget` (convert already hosts oversize via ffmpeg::convert_to). - -## Checks -| # | Risk | Do this | Expect | How | Result | -|---|---|---|---|---|---| -| 1 | MED | `cargo test budget_is_the_smaller` | passes | unit | pass (cargo test budget_is) | -| 2 | MED | Tier 0/1 guild: read `upload_limit` | 10 MiB; tier 2 50, tier 3 100 | unit/by hand | not run: needs Discord (tier mapping read in code: 0/1 10, 2 50, 3 100 MiB) | -| 3 | HIGH | `/download` of a clip that compresses to ~8 MB | uploads as attachment, no retry loop | by hand | not run: needs Discord | -| 4 | HIGH | `/download` source whose smallest encode is above 8.5 MB | message shows a website link (24 h notice), no attachment; `VideoResult.oversize` path | by hand | not run: needs Discord | -| 5 | HIGH | Force upload timeout (shape line to a few KB/s or shorten client timeout locally) | one attempt only, message becomes hosted link(s) | by hand | not run: needs Discord | -| 6 | MED | Simulate 502 or connection reset on upload | retried up to 3 times | by hand | not run: needs Discord (code read: RequestError and 429/5xx retry) | -| 7 | MED | Simulate 400/403 on upload | no retry, "Discord refused" card | by hand | not run: needs Discord (code read: other statuses give 'Discord refused' card) | -| 8 | MED | `/convert` to a result over 8.5 MB | link with 24 h notice, no attachment | by hand | not run: needs Discord and a real video | -| 9 | LOW | `/media` effect with result over budget | "too big to upload" error with MB values | by hand | not run: needs Discord | -| 10 | LOW | `rg UPLOAD_RETRIES src` | retry loop only continues on retryable errors | by hand | pass (code read: loop returns on 413, timeout, non-retryable; continues only on RequestError, 429, 5xx) | - -## Needs -Discord test server and the Chromebook line; never the real token on this PC. - -## Doubts -- Timeout detection assumes twilight reports `RequestTimedOut` for the 180 s client timeout. -- Only video results fall back to a link; audio and gallery results over budget still show "Too large". -- Music card already falls back to a still when the line is slow (SLOW_UPLOAD); quote, games, cmd.rs not changed (small images); per-request shorter timeout for API calls not done (see PROGRESS Later). -- `FALLBACK_UPLOAD_LIMIT` is now unused in download/mod.rs; may warn. diff --git a/docs/tests/S002-outbound-timeouts.md b/docs/tests/S002-outbound-timeouts.md deleted file mode 100644 index ef8a3ba..0000000 --- a/docs/tests/S002-outbound-timeouts.md +++ /dev/null @@ -1,37 +0,0 @@ -# S002 — Timeouts on every outbound call: test file - -Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. - -## Built -Audit of child processes and their limit (all kill on drop or on timeout): -- yt-dlp / ffmpeg / gallery-dl in `download/tools.rs` `run_lines` (shared helper: limit, cancel, kill; probe 120 s). Unchanged. -- `ffmpeg::run` 60 s+ per caller, `kill_on_drop`. Unchanged. -- `ffmpeg::inspect` (ffprobe): 60 s, now `kill_on_drop` (before, the timeout dropped the future and left ffprobe running). -- `ffmpeg::probe` (ffprobe local file): had NO limit; now `PROBE_SECONDS` 60 s + `kill_on_drop`, returns None on timeout. -- Music stream ffmpeg (`source::spawn_pipe`) and `peaks`: no total limit (songs run for hours); now `-rw_timeout` 20 s (`STREAM_IDLE_MICROS`) = cut when no data for 20 s. `peaks` also gives up when a read stalls 30 s (`PEAKS_IDLE`). -- `music/ytdl.rs` lookup, `lastfm/extras.rs` yt-dlp and ffmpeg: already 120 s timeout + `kill_on_drop`. Aki curl: `-m 15` + `kill_on_drop`. -- Tests-only spawns (`std::process::Command` in test modules) left alone. -HTTP: shared client `state.web` 20 s total (covers body); per-call timeouts set in search, covers, lastfm api, virus, translate, actions, animals, activity; `fetch_limited` 60 s + size cap + `safe_url`. `covers.rs` own client has timeout. Discord client 180 s (S001). Test-only clients without timeout left. -Not changed: timeouts keep their existing card text ("took too long" strings); no `bail_user!` rewrite. - -## Checks -| # | Risk | Do this | Expect | How | Result | -|---|---|---|---|---|---| -| 1 | HIGH | Play a song, then block the stream host (firewall rule or pause the server) | ffmpeg ends after about 20 s without data; player moves on or shows an error, no hung process | by hand | not run: needs live voice and a firewall | -| 2 | HIGH | `/convert` a URL to a host that accepts and never answers | ffprobe killed within ~60 s (`pgrep ffprobe` empty), card appears | by hand | not run: needs a hanging host; kill path covered by unit test stuck_child_is_killed_at_the_limit | -| 3 | MED | Run ffmpeg::probe on a FIFO/blocked path | returns None after 60 s, process gone | by hand | not run: needs a FIFO and 60 s; code read: timeout + kill_on_drop | -| 4 | MED | `/play` song, let the loudness pass run with a stalled link | peaks returns None after 30 s idle; playback unaffected | by hand | not run: needs live music | -| 5 | MED | Start `/download` of a slow link, cancel | yt-dlp child gone | by hand | pass (unit test cancel_ends_a_running_child) | -| 6 | MED | Serve a page that sends one byte per second to `/search`, `/image` fetch | gives up by the 20 s client timeout | by hand | not run: needs a slow server; code read: reqwest client timeout 20 s | -| 7 | MED | `fetch_limited` against a 50 MB file | returns None at the size cap | by hand | pass (code read: fetch_limited checks content-length and running size) | -| 8 | LOW | `rg "Command::new" src` | every non-test spawn has a timeout or idle limit | by hand | pass (rg: non-test spawns are ffmpeg.rs, tools.rs run_lines, aki curl -m 15, music source with -rw_timeout) | -| 9 | LOW | Normal song plays with `-rw_timeout` | plays, seek works | by hand | not run: needs live music | -| 10 | MED | Make `/convert` run past its limit | reply says "The conversion took too long ..." | by hand | not run: needs Discord | -| 11 | LOW | Make a `/play` lookup time out | reply says "The song lookup took too long ..." | by hand | not run: needs Discord | - -## Needs -A test server or local slow HTTP server (python), a Discord test guild; never the real token on this PC. - -## Doubts -- `-rw_timeout` on HTTP inputs: assumed supported by the server's ffmpeg build (HTTP protocol option, µs). Verify song playback and that a stall really ends the process. -- Timeout messages from string-returning helpers (`ffmpeg::run`, `ytdl::extract`, `make_song`, VirusTotal wait) are plain strings that callers show as a "❌ ..." reply, not `bail_user!`: the helpers can't return `UserError`. Check the text reads well in each (checks 10-11). diff --git a/docs/tests/S003-recovery-and-shaping.md b/docs/tests/S003-recovery-and-shaping.md deleted file mode 100644 index fc59a46..0000000 --- a/docs/tests/S003-recovery-and-shaping.md +++ /dev/null @@ -1,27 +0,0 @@ -# S003 — Gateway, voice and music recovery; shaping: test file - -Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. - -## Built -- Drops seen in the server log (30 days): gateway "zombied" then 5 failed reconnects with backoff (2026-11-24); one failed reconnect (11-26); one "unrequested heartbeat ack" (11-30). Twilight recovered each time. No voice drops in the log. -- `src/main.rs`: gateway errors are logged; failed reconnects for over `GATEWAY_DOWN_LIMIT` (10 min) exit the process (systemd restarts it). If every shard loop ends (fatal close) the bot logs an error and exits 1 instead of exiting silently with 0. Songbird voice retries set to `VOICE_DRIVER_RETRIES` (8). -- `music/mod.rs`: `VoiceWatcher` on each call listens for `DriverDisconnect`; `recover_voice` waits `VOICE_GRACE` (20 s), rejoins up to `VOICE_REJOIN_TRIES` (3), then `teardown` with a notice in the text channel (queue, panel, loading task cleared). -- `deploy/shape-upload.sh`: cap kept at 800 kbit, comment with the 2026-12-01 numbers. No timed upload measured (no safe target besides external sites). Not reinstalled on the server. - -## Checks -| # | Risk | Do this | Expect | How | Result | -|---|---|---|---|---|---| -| 1 | HIGH | Bot in voice playing; block the voice UDP/WS (firewall) for 60 s, then unblock | Log shows "voice driver disconnect"; playback resumes after rejoin | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 2 | HIGH | Same, block for 3+ minutes | Bot leaves, channel gets "Lost the voice connection..." (deleted after 15 s), `/play` works again | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 3 | HIGH | Cut the network for 12 minutes, restore | Log "gateway: down for ..., exiting"; systemd restarts; bot online | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 4 | MED | Cut the network for 30 s, restore | No exit; gateway reconnects by itself | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 5 | MED | Kick the bot from voice while playing | One teardown, no rejoin attempts (player gone) | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 6 | MED | `/leave` while a recovery wait is pending | No rejoin, no notice | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 7 | MED | Start with an invalid token or bad intents (dev token only, never the live one) | Log "every shard stopped", exit code 1 | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 8 | LOW | Leave and `/play` again in the same guild | Watcher registers again (disconnect after the second join still recovers) | by hand | not run: needs live voice/network cut on the server (not allowed here) | -| 9 | LOW | `tc -s qdisc show dev wlan0` during a big upload with voice playing | Voice class has no drops; voice stays smooth | by hand | not run: needs live voice/network cut on the server (not allowed here) | - -## Doubts -- Songbird may fire `DriverDisconnect` for harmless reasons; the grace + "connected" check should absorb that. Check the log for false alarms. -- Rejoin keeps the playing track in the mixer; unverified that audio resumes without restarting the song. -- Upload cap not re-measured; if the line changed, measure with a timed upload to a host you control. diff --git a/docs/tests/S004-caption.md b/docs/tests/S004-caption.md deleted file mode 100644 index 23fb615..0000000 --- a/docs/tests/S004-caption.md +++ /dev/null @@ -1,32 +0,0 @@ -# S004 — /caption checks - -Run in Discord (owner) unless noted. Bot must have the S004 build. - -## Doubts -- Video path never run: needs ffmpeg with libx264 on the server; check `ffmpeg -encoders | grep libx264` there. -- Band height unit test depends on the font in `assets/` (missing in worktrees). -- Slash option names with hyphens (`source-attachment`) never registered with Discord yet. - -## Checks -1. `/image` and `D!fx` no longer exist (slash list, `D!help`). -2. `/caption text:hello` with a PNG attached: PNG back, white band with centred black text above, same width. -3. Same with a JPG and a still WebP: works. -4. GIF attached: GIF back, still animated, every frame has the band. -5. Animated WebP: comes back as an animated GIF. -6. MP4, WebM and MOV: MP4 back that plays in Discord, band on top, no sound, at most about 10 s. -7. `/caption source-link: text:hi`: works. -8. `D!caption hi` replying to a picture: works. `D!caption hi `: works. -9. `/caption text:hi` with no source after someone posted a picture: uses that picture. -10. Empty text (`D!caption` alone, `/caption text:` blank): clear error card, no upload. -11. Text of 600 characters: "too long" error. Text of about 200 characters: band grows, still readable. -12. Multi-line text: band is as tall as the lines need (3 lines taller than 1). -13. Huge input (over 15 MB): "couldn't download" card, no hang. -14. Bad link (`http://127.0.0.1/x`, `not a link`): error card, no crash. -15. Non-media file (a PDF or audio only): "none of those" error. -16. Result over the upload budget: smaller retry, else "too big" card. -17. `cargo test band_height caption_keeps` passes where assets exist; help-limits test passes. - -## Results (S010, 2026-12-01) -- 1 pass (no `fx` command; `cargo test` registry/help tests pass). 2 pass, 4 pass (rendered by a test: PNG gets a white band + text, GIF keeps 2+ frames, contact sheet looked at). 12, 17 pass (`band_height_grows_with_lines_and_is_even`, `caption_keeps_picture_kind`, help limits). -- 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 3: not run: need Discord or a live bot (owner, S011). Video path not run here either. -- Doubt libx264: ffmpeg on this PC has the same helper tests passing (`ffmpeg.rs` mp4 tests); the server's ffmpeg not checked. diff --git a/docs/tests/S005-speechbubble.md b/docs/tests/S005-speechbubble.md deleted file mode 100644 index c39efed..0000000 --- a/docs/tests/S005-speechbubble.md +++ /dev/null @@ -1,36 +0,0 @@ -# S005 — /speechbubble checks - -Run in Discord (owner) unless noted. Bot must have the S005 build. - -## Doubts -- GIF transparency: the `image` crate's GIF encoder decides which colour index is transparent and the frame disposal. If cut-out areas show old frames or a black/odd colour in an animated result, fix the encoder (key colour, disposal Background). -- Bubble edges are not anti-aliased (hard pixels); check this looks acceptable next to the references. -- Shape numbers (`BUBBLE_HEIGHT` 0.2, `BUBBLE_WIDTH` 0.62, tail at 0.12 to 0.28 of the width) are a guess from the reference GIFs; compare and tune. -- Video path never run (ffmpeg and libx264 on the server). Odd video widths under 480 px may break MP4 encoding (same as /caption). -- Prefix option words (`bottom`, `flip`, `solid`) are plain words in the text; a link containing them is fine, other text is ignored. - -## Checks -1. Contact sheet: extract 2 frames of `assets/reference/speechbubble-bsm.gif` and `speechbubble-assyst.gif`; put the bot's `solid` and plain results of the same picture next to them. Shape and tail direction match. -2. `/speechbubble` with a PNG attached: PNG back, transparent wide ellipse cut from the top, tail pointing down toward the right third. -3. Same with `solid:true`: white fill, black outline, tail points into the picture, picture edge follows the curve. -4. `position:bottom`: bubble hangs from the bottom edge, tail points up. -5. `flip:true`: tail on the left third instead (also with bottom and with solid). -6. JPG and still WebP input: PNG out, transparent (not JPG). -7. GIF input: GIF out, still animated, bubble on every frame, transparent area stays clear (no ghost of earlier frames). -8. Animated WebP input: GIF out. -9. MP4, WebM, MOV without `solid`: GIF out with transparent bubble, at most about 10 s. -10. Video with `solid:true`: MP4 out that plays, no sound, bubble on every frame. -11. `source-link:`: works. `D!speechbubble `: works. -12. `D!speechbubble bottom flip solid` replying to a picture: all three options applied. -13. No source: uses the latest picture in the channel; nothing in the channel: clear error card. -14. Big result (large PNG or GIF over the upload limit): retried smaller; if still too big, clear "too big" error. A solid still may come out as JPG; a transparent one never does. -15. Bad link (`http://127.0.0.1/x`) and non-media file (PDF): error card, no crash. -16. `/help` lists `speechbubble` (alias `bubble`); `cargo test help` limits test passes. -17. Unit tests `bubble_tail_flips_and_touches_chosen_edge` and `bubble_cuts_transparent_or_paints_solid` pass (`cargo test bubble`). -18. `/caption` still works on a picture and a video (its video code was refactored into `map_frames`). - -## Results (S010, 2026-12-01) -- 1 pass by eye: contact sheet (reference GIF frames next to plain, solid, bottom, flip, GIF). Shape and tail direction match; edges are hard pixels but acceptable at Discord size. No tuning done. -- 2, 3, 4, 5 pass (rendered by test on a PNG: transparent cut-out, solid white with outline, bottom hangs with tail up, flip moves the tail). 7 pass (GIF: transparent top stays clear, no ghost of earlier frames in frame 2). 16, 17 pass; 18 pass for the still and GIF path (`caption_keeps_picture_kind`). -- 6, 8, 9, 10, 11, 12, 13, 14, 15: not run: Discord or video path (owner, S011). -- Doubt GIF transparency: looked fine in ImageMagick; Discord rendering not checked. diff --git a/docs/tests/S006-fm.md b/docs/tests/S006-fm.md deleted file mode 100644 index ec5c79d..0000000 --- a/docs/tests/S006-fm.md +++ /dev/null @@ -1,32 +0,0 @@ -# S006 fm commands on ListenBrainz - -## Built -Audit only; code was already on ListenBrainz (api.rs, covers.rs). Features and the fields they read from the adapter: -- Top lists (`fm top`, ta/tab/tt): name, artist.name, playcount, url, image. -- Recent / now playing: name, artist, album, `@attr.nowplaying`, image, date. -- Profile: name, playcount, artist/album/track counts, `registered.unixtime` (first listen), week favourites. realname/country are absent and skipped silently (no empty labels). -- Who Knows (wk/wkt/wka): `plays()` by MBID first, then name; top 1000 only. -- Chart, Pixel Jumble: album image via covers.rs chain. Lyrics: track name/artist, Deezer title search. -- Dashboard link (src/web/api.rs): link_account / unlink / linked_name. -- Dropped: listeners, global playcount, bio, tags (never shown by any card). Last.fm site only used for "Go to song" links. -- Text: topgg.md now says ListenBrainz. `grep -rni "audioscrobbler\|api_key\|LASTFM_API" src` finds only unrelated keys (ZENSERP, STEAMGRIDDB, VIRUSTOTAL). - -## Checks -1. `/fm` with a linked user shows now playing or last listen with cover. -2. `/fm top artists weekly`, `monthly`, `yearly`, `overall` each show a list or "no stats yet" card. -3. `fm profile` shows listens, counts, "Listening since" date, no empty labels. -4. `fm recent` lists 50 listens. -5. `wk` in a server with 2 linked users ranks both. -6. `chart 3x3` makes a collage with covers. -7. `px` starts Pixel Jumble with a pixelated cover. -8. `lyrics` with no args uses the current song. -9. `fmset nosuchuserxyz` gives "There's no ListenBrainz user with that name." -10. Dashboard: set and clear ListenBrainz name works. -11. Live: `cargo test listenbrainz_live -- --ignored`. - -## Doubts -- Not run anywhere; only compile-checked. Fresh users with 204 (stats not ready) show an empty list, not a dedicated card message (not verified). - -## Results (S010, 2026-12-01) -- 1-10: not run: need Discord and linked accounts (owner, S011). 11: not run: needs internet (`listenbrainz_live`, owner say-so). -- Checked here: `rg -i "audioscrobbler|LASTFM_API" src` finds no Last.fm API use; api.rs sample-JSON tests pass in `cargo test`. diff --git a/docs/tests/S006a-dezio-path.md b/docs/tests/S006a-dezio-path.md deleted file mode 100644 index aff10da..0000000 --- a/docs/tests/S006a-dezio-path.md +++ /dev/null @@ -1,38 +0,0 @@ -# S006a — website under /dezio/ (tests) - -## Local checks -Run: `DASHBOARD_URL=http://127.0.0.1:8099/dezio DISCORD_BOT_TOKEN=dev-placeholder target/debug/dezio --web-dev`, cookie `dezio_session=devtoken`. -1. `/dezio/` shows the site with fonts and images; `/dezio/terms`, `/dezio/privacy` load and their Home link goes to `/dezio/`. -2. `/dezio/assets/site.css`, `/dezio/images/dezio.png` return 200. -3. Site: the Dashboard button appears (fetch of `/dezio/api/me` works). -4. `/dezio/dashboard` loads styled; its scripts load from `/dezio/dashboard/static/`; settings load and save (`/dezio/api/user`). -5. Dashboard URL bar after navigating stays `/dezio/dashboard#...`; Sign out returns to `/dezio/dashboard`. -6. Signed out (no cookie): "Sign in with Discord" links to `/dezio/login`; `/dezio/login` redirects to Discord with `redirect_uri=http://127.0.0.1:8099/dezio/callback`. -7. Set-Cookie headers from login have `Path=/dezio`. -8. `/dezio/activity` redirects to `/dezio/activity/`; the page loads, `/dezio/activity/api/config` works, the 401 from web-session has `login` = `/dezio/login?next=/activity/`. -9. A hosted link from `hosted::store` is `http://127.0.0.1:8099/dezio/f//` and downloads. -10. Without a path (`DASHBOARD_URL=http://127.0.0.1:8099`) everything still works at `/`. -11. `cargo test base_path` passes. - -## Deploy commands for S011 (do not run before) -- Back up: `ssh root@192.168.1.71 cp /root/Dezio/.env /root/Dezio/.env.bak-`. -- Landing: `scp deploy/landing/index.html root@192.168.1.71:/srv/landing/index.html` (mkdir `/srv/landing` first). -- `tailscale serve --bg --set-path / /srv/landing` -- `tailscale serve --bg --set-path /dezio http://127.0.0.1:8080` (keep Funnel on; keep the `/git` mapping). -- In `/root/Dezio/.env`: `DASHBOARD_URL=https://astar76.com/dezio`, then restart `dezio-bot`. -- Check `https://astar76.com/`, `/dezio/`, `/git/`. The router accepts the prefix stripped or not. - -## Owner checklist 🧑 -- Developer Portal → OAuth2 → Redirects: add `https://astar76.com/dezio/callback`. -- Activities → URL Mappings: `/` → `astar76.com/dezio/activity`. -- top.gg website field: `https://astar76.com/dezio/`. - -## Doubts -- Whether tailscale strips `/dezio` (both handled, not verified). -- `web/dashboard/index.html` has `__BASE__` placeholders, so opening it as a plain file shows broken links. -- Root-absolute paths left in web/: none outside `__BASE__` placeholders (grep `(href|src|action)="/[a-z]` in web/site finds none). - -## Results (server, 2026-12-01) -- Server steps applied. `/` = landing 200, `/dezio/` 200, `/dezio/dashboard` 200, `/dezio/terms` 200, `/git/` 200, Funnel on. dezio-bot active, journal clean, log shows Dashboard on .../dezio. -- Note: `tailscale serve --set-path` turns Funnel off; `tailscale funnel --bg --set-path / /srv/landing` restored it (brief outage, about 5 min). -- Not checked: OAuth login and Activity (need owner portal changes). diff --git a/docs/tests/S007-website-security.md b/docs/tests/S007-website-security.md deleted file mode 100644 index 79ebd21..0000000 --- a/docs/tests/S007-website-security.md +++ /dev/null @@ -1,56 +0,0 @@ -# S007 — Website and dashboard security: test file - -Written by the worker that built it, run by the test phase. Probes below were run once against the local `--web-dev` -copy (`DASHBOARD_URL=http://127.0.0.1:8099/dezio`); a Result of `pass` means it was seen there, `—` means not run yet. - -## Built -- `src/web/mod.rs` · `RateLimit` + `SIGN_INS_PER_MINUTE` (20/min, all users) on `/callback`; `HOSTED_CSP` (sandbox) on `/f/`; bare base `/dezio` redirects to `/dezio/`; `/dezio/` serves the site; ServeDir folders no longer redirect; `start_dev` keeps DASHBOARD_URL's path. -- `src/web/activity.rs` · same sign-in limit on `/activity/api/token` (429); `dev_mode` also needs a local Host and no `X-Forwarded-For`. -- `web/dashboard/static/app.js` · text for `?error=busy`. - -## Review checklist (findings) -| Item | Finding | Severity / state | -|---|---|---| -| Auth on every API route | All `/api/*` except `/api/me` call `need_session`; Activity routes need a Bearer session (`library`, `rom`, `save`, `state`, `legacy`); `art` is public (cover pictures only). Probed: forged cookie → 401. | fine | -| Guild permission checks | `guild_for`: guild in cache, user is a member, Manage Server or Admin, live from the cache. Probed: unknown guild → 404. Role menus can list an existing non-power role by name, so a Manage Server user can let members self-assign a cosmetic role ranked above his own (same as the Discord editor). | LOW, Later | -| CSRF on writes | `check_write` on every PATCH/POST (user, guild, rolemenus, quote preview, logout): Origin (or Referer) must match, `x-csrf-token` constant-time compare, JSON content type. `web-session` checks Origin. Probed: no token, evil Origin, no Origin, text/plain all refused. Host+Origin both `evil.test` passes the origin check, but the browser sends no cookie for that host, so no session: fine. | fine | -| OAuth state | 24 random bytes in an HttpOnly cookie, compared on callback, cleared after success. `next` only from a whitelist (`/dashboard`, `/activity/`). Probed: wrong state → `error=state`; `next=//evil.test` not stored; forged `dezio_next=//evil.test` cookie ignored. | fine | -| Cookie flags | `HttpOnly; SameSite=Lax; Path=/dezio`, `Secure` on https. Probed. | fine | -| Session expiry | Dashboard 7 days, Activity 24 h, both checked on every use; expired ones pruned on sign-in. Every `web-session` call writes a new Activity session (only signed-in users). | LOW, Later | -| Input size limits | 64 KiB body limit (probed: 200 KB → 413), text fields capped, serde depth limit (probed: 5000-deep JSON refused), saves/states capped (unit test). | fine | -| Path traversal in static files | ServeDir refuses `..` (probed `/assets/../../.env`, `/f/../../.env`, `/dashboard/static/../../../Cargo.toml` → 404); ROM ids are looked up in the library map, never joined to a path. | fine | -| Folder redirects (base path) | ServeDir answered `/dezio/assets/fonts` with `Location: /fonts/` (base and prefix lost; not attacker-controlled). Fixed: folders now 404. | LOW, fixed | -| Open redirect / path tricks | Every redirect is base + fixed path; `/activity?x=…` keeps the query after `?` only. Probed `//evil.test/…`, `/dezio/dezio/…`, `/dezioX/…`, `/dezio/activity/../dashboard` → 404. | fine | -| Bare base path | `/dezio/` gave 404 while `/dezio` served the page with relative links that escape the base. Fixed: `/dezio` → 308 `/dezio/`, `/dezio/` serves the site. | MED (broken page), fixed | -| Hosted files `/f/` | Files from `/download` (internet content) were served on the site's origin with the normal CSP: an HTML/SVG plus a hosted `.js` could run script as the site (`script-src 'self'`). Fixed: `/f/` gets `sandbox; default-src 'none'` CSP. | MED, fixed | -| Security headers | nosniff, HSTS, CSP, X-Frame-Options DENY (site), frameable CSP for Activity only, Referrer-Policy. No Permissions-Policy (nothing to restrict). | fine | -| Error leaks | API errors are fixed texts. Bad JSON returns axum's parser message (position only, no secrets). | fine | -| Rate limits | No limit on `/callback` and `/activity/api/token`, each costs a Discord OAuth call; hammering could get the bot's address limited by Discord. Fixed: 20 per minute together. Writes need a session + CSRF; quote preview has 2 slots; `/api/places` (signed in) calls the geocoder with no limit. | MED fixed; places LOW, Later | -| Activity input | Uploads capped, slot 0–3 only, ROM id from the library map. Dev sessions: `DEZIO_ACTIVITY_DEV=1` + loopback was enough, and behind `tailscale serve` every request is loopback. Fixed: also needs a local Host and no `X-Forwarded-For`. No WebSocket. | LOW, fixed | - -## Checks -| # | Risk | Do this | Expect | How | Result | -|---|---|---|---|---|---| -| 1 | HIGH | `cargo test web::` | all pass except `the_game_boy_activity_…` in a worktree without `assets/roms` | unit | pass (10/11, ROM test needs assets/roms) | -| 2 | HIGH | `sign_ins_are_limited_per_minute` | 3rd call in a minute refused, next minute allowed | unit | pass | -| 3 | HIGH | `base_path_routes_and_redirects` (base `/dezio`) | `/dezio/`, `/`, `/dezio/dashboard`, assets 200; `/dezio?x=1` → `/dezio/?x=1`; folder 404; cookie `Path=/dezio`; callback error stays under base | unit | pass | -| 4 | HIGH | GET a `/f//` link | header `content-security-policy` starts with `sandbox;`; video still plays inline in Firefox and Chrome | unit + by hand | unit pass; browser not run (needs a browser, S011) | -| 5 | HIGH | PATCH `/dezio/api/user` with cookie `dezio_session=devtoken` and: no `x-csrf-token`; `Origin: http://evil.test`; no Origin; `Content-Type: text/plain` | 403, 403, 403, 415 | integration (curl) | pass | -| 6 | HIGH | `curl --path-as-is` `/dezio/assets/../../.env`, `/dezio/f/../../.env` | 404 | integration | pass | -| 7 | MED | 21 POSTs to `/dezio/activity/api/token` with `{"code":"x"}` in one minute (use a stub: do NOT let these reach Discord, e.g. run without network) | 21st → 429 "Too many sign-ins" | integration | pass (no network: 20 x 401, 21st and 22nd 429) | -| 8 | MED | `DEZIO_ACTIVITY_DEV=1`, POST `/dezio/activity/api/dev-session` plain; with `X-Forwarded-For: 1.2.3.4`; with `Host: astar76.com` | session; 404; 404 | integration | pass | -| 9 | MED | GET `/dezio` and `/dezio?a=//evil.test` | 308 to `/dezio/` and `/dezio/?a=//evil.test` (relative, same host) | integration | pass | -| 10 | MED | Open the site at `https://…/dezio` on the live server after deploy | lands on `/dezio/`, CSS and images load | by hand 🧑 | not run: live site, owner | -| 11 | MED | Dashboard with `?error=busy` | shows "Too many sign-ins right now…" | screen | pass (text present in app.js; page not looked at) | -| 12 | LOW | GET `/dezio/assets/fonts`, `/dezio/f/`, `/dezio/activity/static` | 404, no Location header | integration | pass | - -## Needs -- `cargo build`, then `DASHBOARD_URL=http://127.0.0.1:8099/dezio DISCORD_BOT_TOKEN=dev-placeholder target/debug/dezio --web-dev`; cookie `dezio_session=devtoken`, CSRF `devcsrf`. -- Never probe the live site or Discord. `/callback` and `/activity/api/token` with a valid-looking state/code DO call discord.com: block the network or stop before that point. - -## Doubts -- `HOSTED_CSP` sandbox: not checked in a browser that video/GIF/PNG still show inline (check 4). If a browser refuses media under `sandbox`, drop `sandbox` and keep `default-src 'none'`. -- The `/dezio` → `/dezio/` redirect assumes `tailscale serve` passes `/dezio` unchanged; if it strips the prefix the redirect never fires (harmless). -- `dev_mode` assumes `tailscale serve` sets `X-Forwarded-For` or keeps the public Host; the Host check alone should cover it. -- The limit is global: during an attack real users also get "busy" for up to a minute. Accepted for a small bot. -- One probe in this session sent a bogus code to Discord's token endpoint (forged state cookie on `/callback`), before the rule was noticed. One request, refused. diff --git a/docs/tests/S008-media-commands-deps.md b/docs/tests/S008-media-commands-deps.md deleted file mode 100644 index e5140b1..0000000 --- a/docs/tests/S008-media-commands-deps.md +++ /dev/null @@ -1,56 +0,0 @@ -# S008 — Media inputs, commands and dependencies: test file - -Written by the worker that built it, run by the test phase. Nothing here has been tested until its Result says so. - -## Built -- `src/commands/media/mod.rs` · `is_public_ip` (one address check for links and DNS answers: loopback, LAN, link-local, 100.64/10 Tailscale, multicast, reserved, IPv4-in-IPv6, NAT64), `safe_url` uses it and refuses `.lan`, `.home.arpa`, `.localdomain` names too. -- `src/commands/media/mod.rs` · `PublicDns`: DNS resolver of the shared `state.web` client (`src/state.rs`); drops private answers at connect time (covers redirects and DNS rebinding for every reqwest fetch). -- `src/commands/media/mod.rs` · `is_playlist(head)`: spots HLS/DASH/ffconcat/PLS/SMIL text; `/convert` (`open_source`) and caption/speechbubble video (`images::map_frames`) refuse them. -- `src/commands/media/mod.rs` · `one_job(ctx)` / `Busy`: one convert/caption/speechbubble job per user at a time ("You already have a media job running"). `/download` keeps its own one-per-user check. -- `src/commands/media/ffmpeg.rs` · `LOCAL_ONLY` (`-protocol_whitelist file`) on local ffmpeg/ffprobe inputs (`convert_to`, `inspect`, `probe`, caption frame cut); download `tools.rs` local inputs too; yt-dlp stream inputs in `tools.rs` get the http(s) whitelist. -- `src/commands/media/convert.rs` · `fetch_head` returns the address after (checked) redirects; ffmpeg gets that address, after a fresh `url_is_safe` DNS check. -- `src/commands/media/download/tools.rs` · gallery-dl link now after `--`. -- `src/pix.rs` · `limits()` + `decode` with `MAX_DECODE_SIDE` 10 000 px and `MAX_DECODE_BYTES` 256 MiB; `images::frames_of` sets the same limits on GIF/WebP decoders and caps frames with `MAX_ANIMATION_BYTES` 256 MiB (`frame_cap`). `colors::pick` uses `pix::decode`. -- `Cargo.lock` · `url` 2.5.8 → 2.5.9 (RUSTSEC-2026-0592). - -## Checks -| # | Risk | Do this | Expect | How | Result | -|---|---|---|---|---|---| -| 1 | HIGH | `cargo test private_addresses` and `cargo test playlists_are_spotted` | pass (100.101.102.103, `[::ffff:127.0.0.1]`, `2130706433`, `printer.lan`, `[64:ff9b::c0a8:147]` refused; 1.1.1.1 allowed) | unit | pass | -| 2 | HIGH | Build a `reqwest::Client` with `.dns_resolver(PublicDns)` and GET `http://localtest.me:/` (name resolves to 127.0.0.1) against a 127.0.0.1 listener; use a local name from /etc/hosts if offline | request fails, listener gets no connection | unit | pass (test `names_that_resolve_to_this_machine_are_not_reached`) | -| 3 | HIGH | Same client, local listener A answers 302 to `http://localhost:/` | listener B gets no connection | unit | pass (same test) | -| 4 | HIGH | `ffmpeg::convert_to` with `Source::Bytes` of an m3u8 text whose segment is `file:///etc/passwd` | fails; no output contains passwd text | integration | pass (`a_playlist_cannot_make_ffmpeg_open_files_or_addresses`) | -| 5 | HIGH | `ffmpeg::inspect`/`probe` on a local file that is an HLS playlist pointing at `http://127.0.0.1:/x.ts` | the local server gets no request | integration | pass (same test, probe + inspect) | -| 6 | HIGH | `images::map_frames` with bytes `#EXTM3U\n...` | returns the "Playlists and stream lists" error, ffmpeg never runs | unit | pass (`playlists_never_reach_ffmpeg_in_frame_cutting`) | -| 7 | HIGH | `pix::decode` of a PNG header claiming 60 000 × 60 000 (tiny file) | `None`, quick, little memory | unit | pass (`a_huge_declared_picture_is_refused_fast`) | -| 8 | HIGH | `frames_of` on a GIF with a 4000 × 4000 logical screen and 120 one-pixel frames | at most `frame_cap((4000,4000))` = 4 frames decoded, RSS stays under ~400 MB | unit | pass (frame_cap 4, frames <= 4; RSS not measured) | -| 9 | MED | `frames_of` on a normal 10-frame GIF (existing caption test) | still 10 frames | unit | pass (`caption_keeps_picture_kind`) | -| 10 | MED | Call `one_job` twice for the same user, drop the first guard, call again | 2nd call errors, 3rd succeeds; other user always succeeds | unit | not run: needs a Ctx, none can be built in unit tests | -| 11 | MED | `cargo test` full run (about 227 tests; `ffmpeg.rs` and `download/flow.rs` tests use local http servers) | same pass count as before S008 | unit | pass: 257 run, 249 + 6 new pass, 8 known worktree asset failures | -| 12 | MED | Local `--web-dev` / unit: `fetch_limited` of `https://cdn.discordapp.com/...`-style public name (only with `live_` ignored tests) | still works through `PublicDns` | integration | not run: needs the internet, owner say-so | -| 13 | MED | 🧑 In Discord: `/convert` a normal mp4 link, `/caption` a GIF, `/speechbubble` a video | work as before | by hand | not run: Discord, owner | -| 14 | MED | 🧑 Start `/caption` on a long video and at once a second `/caption` | second answers "You already have a media job running" | by hand | not run: Discord, owner | -| 15 | LOW | `cargo audit` | only the advisories listed below remain | by hand | not run: audit done in S008, not repeated | - -## Needs -- Local listeners on 127.0.0.1 only. No traffic to Discord, the live site or outside hosts (check 12 only via existing `live_` ignored tests, on the owner's say). -- ffmpeg/ffprobe installed for 4, 5, 8. - -## Audit (2026-12-01, cargo audit 0.22.2, advisory DB 1594 entries; cargo deny check advisories agrees) -Fixed: `url` 2.5.9 (RUSTSEC-2026-0592, stack overflow on nested blob: URLs). -Left open, no compatible fix (all need a major or 0.0.x bump inside songbird/davey; wait for upstream): -- libcrux-* 0.0.5–0.0.8 via `davey` (Discord DAVE voice encryption): RUSTSEC-2026-0124, -0207, -0208, -0212 (8.2 high), -0331 (8.7 high), -0330, -0209, -0211 (medium). Panics/wrong output in post-quantum and AEAD code; reached only through the voice E2EE handshake with Discord, not user input. Worst case a panic in the voice task. -- crypto-bigint 0.5.5 (RUSTSEC-2026-0387), curve25519-dalek 4.1.3 (RUSTSEC-2026-0620, AVX-512 only; the Chromebook CPU has none) via davey/openmls. -- ringbuf 0.4.8 via songbird (RUSTSEC-2026-0293, needs an element's Drop to panic; songbird stores plain samples). -- rustls 0.22.4 / rustls-webpki 0.102.8 (RUSTSEC-2026-0346, -0349, -0049, -0098, -0099, -0104, -0382): only in Cargo.lock through songbird's optional serenity feature; `cargo tree -i rustls-webpki@0.102.8` prints nothing, so they are not built. -- Warnings (unmaintained/unsound): chrono, derivative, instant, pin-utils, proc-macro-error2, ttf-parser, libcrux-aesgcm (renamed), rustix xattr (unsound, unused path). - -## Doubts -- ffmpeg follows HTTP redirects itself and resolves names again: `/convert` checks the landed address and its DNS just before, but a redirect issued later or a rebinding between the check and ffmpeg's connect is not caught. Same for yt-dlp and gallery-dl (only the first link is checked, `url_is_safe`). A real fix needs a network namespace or egress firewall on the server (Later). -- `url_is_safe` still says "safe" when DNS lookup fails or times out (kept as it was, so yt-dlp shows the real error). -- `PublicDns` now applies to every `state.web` call, not only media. Any feature that fetched a LAN/Tailscale host through `state.web` would now fail; grep found none. Tests that point `state.web` at 127.0.0.1 would fail too (none found, not run). -- `-protocol_whitelist file` on yt-dlp outputs: a legit local HLS-style output would fail; yt-dlp writes merged files, so it should not happen. Encrypted local files needing `crypto` would also fail. -- Stream inputs in `tools.rs` now carry `http,https,tcp,tls,crypto`; an HLS stream whose segments use another protocol (e.g. `data:`) would fail. Music already used the same whitelist. -- `is_playlist` sniff only looks at the first 512 bytes, after BOM and whitespace. -- `src/web/activity.rs:309`, `src/commands/lastfm/extras.rs:654`, cookie/emoji asset decodes still use unlimited `load_from_memory` / unwhitelisted ffmpeg (out of this plan's files). -- No per-user limit added to quote/petpet (small, cheap) and no global cap on heavy jobs across users. diff --git a/docs/topgg.md b/docs/topgg.md index 805eb39..47621c7 100644 --- a/docs/topgg.md +++ b/docs/topgg.md @@ -8,23 +8,23 @@ Copy each block into the matching field on the bot's Top.gg edit page. |---|---| | Invite URL | https://discord.com/oauth2/authorize?client_id=1387839600017412106&scope=bot%20applications.commands&permissions=8 | | Support server | https://discord.gg/UnSga5DmR7 | -| Website | https://astar76.com/dezio/ | -| GitHub / source | https://astar76.com/git/astar76/Dezio | +| Website | https://archlinux.tail7c4f5e.ts.net | +| GitHub / source | https://archlinux.tail7c4f5e.ts.net/git/astar76/Dezio | | Prefix | `D!` (every command is also a slash command) | | Library | Rust (twilight + songbird) | ## Tags -`Music` · `Moderation` · `Fun` · `Utility` · `Games` · `Logging` · `Social` · `Music stats` +`Music` · `Moderation` · `Fun` · `Utility` · `Games` · `Logging` · `Social` · `Last.fm` ## Short description (headline) -Music with a live player, ListenBrainz stats, video downloads, games, AI chat, moderation and logs — one bot, set up in minutes. +Music with a live player, Last.fm stats, video downloads, games, AI chat, moderation and logs — one bot, set up in minutes. ## Long description ```markdown -# Dezio — music, ListenBrainz stats, downloads, games and moderation in one bot +# Dezio — music, Last.fm, downloads, games and moderation in one bot **Dezio** is an all-in-one Discord bot that does the everyday jobs of a server without needing six different bots. Everything works as a **slash command** and most things also work with the **`D!` prefix**. Type `/help` to see every command. @@ -36,7 +36,7 @@ Play songs and playlists from a search or a link (YouTube, SoundCloud, Bandcamp - Leaves by itself when everyone is gone or nothing is playing - Music chat cleans itself up — only the player stays -## 📊 ListenBrainz stats +## 📊 Last.fm Now-playing cards, top artists / albums / tracks, album collages, server **"Who knows?"** leaderboards, lyrics, and **Pixel Jumble** — a server-wide guess-the-album game anyone can join by typing. ## ⬇️ Downloads @@ -55,9 +55,9 @@ Chess, Connect 4, tic-tac-toe, Wordle, hangman, minesweeper, 2048, Akinator, Coo AI chat with a personality you can change per server, anime GIF actions, confessions, a phone-call system between servers, quotes you can style, emoji tools, weather, translation, wikipedia / web / image search, a calculator and a **Game Boy you can play inside Discord** (Activity). ## Links -- **Website & dashboard:** https://astar76.com/dezio/ +- **Website & dashboard:** https://archlinux.tail7c4f5e.ts.net - **Support server:** https://discord.gg/UnSga5DmR7 -- **Source code:** https://astar76.com/git/astar76/Dezio +- **Source code:** https://archlinux.tail7c4f5e.ts.net/git/astar76/Dezio - Privacy policy and terms are on the website. Written in **Rust** for speed. Add it, type `/help`, and you're done. diff --git a/src/cmd.rs b/src/cmd.rs index a232c3d..4f48df9 100644 --- a/src/cmd.rs +++ b/src/cmd.rs @@ -94,7 +94,7 @@ pub struct Command { pub usage: &'static str, pub options: Vec, pub slash: bool, - /// The slash command's name when it differs from the text command's. + /// The slash command's name when it differs from the text command's (`D!fx` is `/image`). pub slash_name: Option<&'static str>, pub guild_only: bool, /// Bot-owner tools: only listed in help for the owner. diff --git a/src/colors.rs b/src/colors.rs index aa91b61..b8a3010 100644 --- a/src/colors.rs +++ b/src/colors.rs @@ -146,7 +146,7 @@ fn hls_to_rgb(h: f32, l: f32, s: f32) -> (f32, f32, f32) { /// The colour that best represents an image: frequent *and* vivid, made readable on Discord. pub fn pick(data: &[u8]) -> Option { - let img = image::DynamicImage::ImageRgba8(crate::pix::decode(data)?).thumbnail(64, 64).to_rgba8(); + let img = image::load_from_memory(data).ok()?.thumbnail(64, 64).to_rgba8(); let pixels: Vec<[u8; 3]> = img.pixels().filter(|p| p[3] > 128).map(|p| [p[0], p[1], p[2]]).collect(); if pixels.is_empty() { return None; diff --git a/src/commands/gameboy.rs b/src/commands/gameboy.rs index 6c6cf4d..9f8523d 100644 --- a/src/commands/gameboy.rs +++ b/src/commands/gameboy.rs @@ -8,7 +8,7 @@ //! //! Owner setup, once, in the Developer Portal (app → Activities): //! 1. Settings → enable Activities. -//! 2. URL Mappings → prefix `/` → target `/activity` (…ts.net/dezio/activity). +//! 2. URL Mappings → prefix `/` → target `/activity`. use crate::cmd::{Command, Ctx, Origin}; use crate::state::State; use crate::ui::{button, Card}; diff --git a/src/commands/help.rs b/src/commands/help.rs index d74685e..d6f6e9f 100644 --- a/src/commands/help.rs +++ b/src/commands/help.rs @@ -34,7 +34,7 @@ const fn cat(key: &'static str, emoji: &'static str, name: &'static str, blurb: pub const CATEGORIES: &[Category] = &[ cat("music", "🎵", "Music", "Play music in voice with a live player", 0x9B59B6, ""), cat("lastfm", "📊", "Music stats", "Now playing, top charts, Who Knows, Pixel Jumble and lyrics, from ListenBrainz", 0xEB743B, "Link your ListenBrainz account first: `{p}fmset ` or `/fm mode:link`."), - cat("media", "🎨", "Media", "Downloads, captions, quotes and emojis", 0xE67E22, ""), + cat("media", "🎨", "Media", "Downloads, image effects, quotes and emojis", 0xE67E22, ""), cat("moderation", "🛡️", "Moderation", "Kick, ban, timeout, purge, nicknames and roles", 0xED4245, "Moderation commands also work as a reply to someone's message."), cat("server", "⚙️", "Server setup", "Logging, welcome, role menus, channel tools and the prefix", 0xF1C40F, ""), cat("utility", "🔧", "Utility", "Info cards, web search, weather, calculator, snipe and AFK", 0x607D8B, ""), diff --git a/src/commands/media/convert.rs b/src/commands/media/convert.rs index b2c66a4..97b0487 100644 --- a/src/commands/media/convert.rs +++ b/src/commands/media/convert.rs @@ -11,7 +11,7 @@ //! Text version: `D!convert mp3 128k` (reply to a file, attach one, or add a link / @user). use super::ffmpeg::{self, find_format, parse_quality, Converted, MediaType, Quality, Source, HEIGHTS, KBPS}; use super::images::pick_opt; -use super::{fetch_limited, has_ext, safe_url, upload_budget, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; +use super::{fetch_limited, has_ext, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::state::State; @@ -134,7 +134,7 @@ fn take(rest: &mut String) -> Option { } /// The newest picture, video or sound posted in this channel (what `/convert` uses when you give it nothing). -pub(super) async fn last_chat_media(ctx: &Ctx) -> Option { +async fn last_chat_media(ctx: &Ctx) -> Option { let messages = ctx.state.http.channel_messages(ctx.channel_id).limit(30).await.ok()?.models().await.ok()?; for m in messages.iter().filter(|m| Some(m.id) != ctx.command_message_id()) { for a in &m.attachments { @@ -154,8 +154,8 @@ pub(super) async fn last_chat_media(ctx: &Ctx) -> Option { None } -/// The first few KB of a file, its total size, and its address after redirects, without downloading the rest. -async fn fetch_head(state: &State, url: &str) -> Option<(Vec, Option, String)> { +/// The first few KB of a file and its total size, without downloading the rest. +async fn fetch_head(state: &State, url: &str) -> Option<(Vec, Option)> { let url = safe_url(url)?; let mut r = state.web.get(url).header(reqwest::header::RANGE, "bytes=0-65535").send().await.ok()?; if !r.status().is_success() { @@ -167,7 +167,6 @@ async fn fetch_head(state: &State, url: &str) -> Option<(Vec, Option, S .and_then(|v| v.to_str().ok()) .and_then(|v| v.rsplit('/').next()?.parse::().ok()) .or_else(|| r.content_length()); - let landed = r.url().to_string(); let mut head = Vec::new(); while head.len() < 65536 { match r.chunk().await.ok()? { @@ -176,7 +175,7 @@ async fn fetch_head(state: &State, url: &str) -> Option<(Vec, Option, S } } head.truncate(65536); - Some((head, total, landed)) + Some((head, total)) } /// Pictures come down whole (they're small); anything else is read from its address while ffmpeg works. @@ -184,10 +183,7 @@ async fn open_source(state: &State, url: &str) -> Result { if safe_url(url).is_none() { bail_user!("That doesn't look like a public link."); } - let Some((head, total, landed)) = fetch_head(state, url).await else { bail_user!("I couldn't reach that file.") }; - if super::is_playlist(&head) { - bail_user!("Playlists and stream lists can't be converted, only the file itself."); - } + let Some((head, total)) = fetch_head(state, url).await else { bail_user!("I couldn't reach that file.") }; if image::guess_format(&head).is_ok() { let Some(bytes) = fetch_limited(state, url, MAX_PICTURE_BYTES).await else { bail_user!("I couldn't download that picture ({} MB max).", MAX_PICTURE_BYTES / 1024 / 1024) }; return Ok(Source::Bytes(bytes)); @@ -195,16 +191,10 @@ async fn open_source(state: &State, url: &str) -> Result { if total.is_some_and(|t| t > MAX_STREAM_BYTES) { bail_user!("That file is too big to convert ({} MB max).", MAX_STREAM_BYTES / 1024 / 1024); } - // ffmpeg reads the file itself and resolves the name again: hand it the address the checked client landed on, - // and check that name's DNS once more (ffmpeg's own redirects can't be checked). - if !super::download::url_is_safe(&landed).await { - bail_user!("That doesn't look like a public link."); - } - Ok(Source::Url { url: landed, head }) + Ok(Source::Url { url: url.trim_matches(|c| c == '<' || c == '>').to_string(), head }) } async fn convert_cmd(ctx: Arc) -> Result<()> { - let _busy = super::one_job(&ctx)?; let a = &ctx.args; let mut output = a.str("output").unwrap_or("").to_string(); let mut quality_text = a.str("quality").unwrap_or("").to_string(); @@ -247,7 +237,7 @@ async fn convert_cmd(ctx: Arc) -> Result<()> { None => bail_user!("Attach a file, give a link, or post a picture, video or sound in this channel first — I convert the latest one."), }, }; - let limit = upload_budget(&ctx); + let limit = upload_limit(&ctx); ctx.defer().await?; let source = open_source(&ctx.state, &url).await?; let Some((kind, animated)) = ffmpeg::detect(&source).await else { bail_user!("I can't read that file as a picture, video or sound.") }; diff --git a/src/commands/media/download/flow.rs b/src/commands/media/download/flow.rs index e12d18e..23f8e1e 100644 --- a/src/commands/media/download/flow.rs +++ b/src/commands/media/download/flow.rs @@ -17,8 +17,6 @@ pub struct VideoResult { pub codec: String, pub size: u64, pub url: String, - /// Still over the upload budget after compressing: deliver as a website link. - pub oversize: bool, } pub struct AudioResult { @@ -251,18 +249,11 @@ async fn video_flow(web: &reqwest::Client, job: &Job, cap: i64, workdir: &Path, } // 2) make sure it FITS - one fast encode, only if still over the limit if size_of(&path) as f64 > limit * FINAL_MARGIN { - match tools::compress(job, &path, &meta, false).await { - Ok(p) => { - path = p; - compressed = true; - media = tools::inspect(&path).await.or(media); - } - Err(DlError::TooLarge) => {} // keep the playable file and send it as a link - Err(e) => return Err(e), - } + path = tools::compress(job, &path, &meta, false).await?; + compressed = true; + media = tools::inspect(&path).await.or(media); } let size = size_of(&path); - let oversize = size > job.limit; let nice = path.with_file_name(format!("{}{}", slug(&title, str_of(&info, "id").unwrap_or("video")), path.extension().and_then(|e| e.to_str()).map(|e| format!(".{}", e.to_lowercase())).unwrap_or_default())); if nice != path && std::fs::rename(&path, &nice).is_ok() { path = nice; @@ -277,7 +268,6 @@ async fn video_flow(web: &reqwest::Client, job: &Job, cap: i64, workdir: &Path, codec: codec_label(codec.as_deref()), size, url: str_of(&info, "webpage_url").unwrap_or(&job.url).to_string(), - oversize, }) } diff --git a/src/commands/media/download/job.rs b/src/commands/media/download/job.rs index 9b4e16a..61d91a2 100644 --- a/src/commands/media/download/job.rs +++ b/src/commands/media/download/job.rs @@ -15,8 +15,6 @@ pub enum DlError { /// The stream we started is bigger than the limit; try a smaller one. SizeExceeded, Cancelled, - /// The upload ran out of time; repeating it would time out again → send a link instead. - UploadTimedOut, /// Raw text from yt-dlp, for [`super::plan::friendly_error`]. Ytdlp(String), } diff --git a/src/commands/media/download/mod.rs b/src/commands/media/download/mod.rs index bcd1095..159c3e3 100644 --- a/src/commands/media/download/mod.rs +++ b/src/commands/media/download/mod.rs @@ -36,7 +36,6 @@ use twilight_util::builder::embed::{EmbedBuilder, ImageSource}; const UI_TICK: Duration = Duration::from_secs(5); const PROGRESS_PICTURE: &str = "download.jpg"; -/// Retries only for errors that can work the second time (connection reset, 5xx, rate limit). A timeout is never retried. const UPLOAD_RETRIES: u32 = 3; const BLURPLE: u32 = 0x5865F2; @@ -59,6 +58,13 @@ fn slot() -> &'static Semaphore { // ---- safety --------------------------------------------------------------------------------------------- +fn is_global(ip: std::net::IpAddr) -> bool { + match ip { + std::net::IpAddr::V4(v4) => !(v4.is_private() || v4.is_loopback() || v4.is_link_local() || v4.is_unspecified() || v4.is_broadcast() || v4.octets()[0] == 0 || (v4.octets()[0] == 100 && (64..128).contains(&v4.octets()[1]))), + std::net::IpAddr::V6(v6) => !(v6.is_loopback() || v6.is_unspecified() || (v6.segments()[0] & 0xfe00) == 0xfc00 || (v6.segments()[0] & 0xffc0) == 0xfe80), + } +} + /// Block requests to localhost and private networks (also after DNS lookup). pub(crate) async fn url_is_safe(url: &str) -> bool { let Some(parsed) = super::safe_url(url) else { return false }; @@ -68,7 +74,7 @@ pub(crate) async fn url_is_safe(url: &str) -> bool { return false; } match tokio::time::timeout(Duration::from_secs(8), tokio::net::lookup_host((host.as_str(), 80))).await { - Ok(Ok(addrs)) => addrs.into_iter().all(|a| super::is_public_ip(a.ip())), + Ok(Ok(addrs)) => addrs.into_iter().all(|a| is_global(a.ip())), _ => true, // can't resolve here → let yt-dlp report the real error } } @@ -308,11 +314,7 @@ where if http_status(&e) == Some(413) || api_code(&e) == Some(40005) { return Err(DlError::TooLarge); } - if matches!(e.kind(), twilight_http::error::ErrorType::RequestTimedOut) { - return Err(DlError::UploadTimedOut); - } - let retryable = matches!(e.kind(), twilight_http::error::ErrorType::RequestError) || matches!(http_status(&e), Some(429 | 500..=599)); - if !retryable { + if matches!(http_status(&e), Some(400 | 401 | 403 | 404)) { return Err(DlError::user("Upload failed", format!("Discord refused the upload: {}", e.to_string().chars().take(200).collect::()))); } last = e.to_string(); @@ -346,25 +348,7 @@ async fn publish(job: &Job, live: &Live, paths: &[PathBuf], content: Option publish_link(live, paths, &content, "Discord upload was too slow from here").await, - other => other, - } -} - -/// The upload timed out: keep the files on the website and show links instead. -async fn publish_link(live: &Live, paths: &[PathBuf], content: &Option, why: &str) -> Result<(), DlError> { - let mut text = content.clone().unwrap_or_default(); - text.push_str(&format!("\n📦 {why}, so it's kept for **{} hours**:", crate::hosted::TTL.as_secs() / 3600)); - for p in paths { - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("file"); - match crate::hosted::store(p, name) { - Ok(link) => text.push_str(&format!("\n{link}")), - Err(e) => return Err(DlError::user("Upload failed", format!("The upload timed out and I couldn't keep the file for download ({e})."))), - } - } - let text: String = text.chars().take(1900).collect(); - live.edit(Some(&text), &[], &[], &[]).await.map_err(|e| DlError::user("Upload failed", format!("The upload timed out and the link couldn't be shown: {}", e.to_string().chars().take(100).collect::()))) + result } // ---- running a job ------------------------------------------------------------------------------------------ @@ -383,7 +367,7 @@ async fn download(ctx: Arc) -> Result<()> { if active().lock().unwrap_or_else(|e| e.into_inner()).contains_key(&owner) { return fail(&ctx, "Already busy", "You already have a download running.").await; } - let limit = super::upload_budget(&ctx) as u64; + let limit = super::upload_limit(&ctx).max(FALLBACK_UPLOAD_LIMIT as usize) as u64; let cap = if quality == "best" { DEFAULT_QUALITY_CAP } else { quality.parse().unwrap_or(DEFAULT_QUALITY_CAP) }; let job = Arc::new(Job::new(owner, url.clone(), limit, audio)); let live = Arc::new(Live::create(&ctx, &progress_embed(&job), &cancel_row(owner, false)).await?); @@ -484,9 +468,6 @@ async fn deliver(job: &Job, live: &Live, outcome: Outcome) -> Result<(), DlError let info = vec![format!("-# **{}p** • **{}** • **{}** • **{}**", if v.height > 0 { v.height.to_string() } else { "?".into() }, v.codec, fmt_bytes(v.size as f64), fmt_dur(v.duration))]; job.set("Uploading", "⬆️", &fmt_bytes(v.size as f64), true); let _ = live.edit(None, &[progress_embed(job)], &[], &[]).await; - if v.oversize { - return publish_link(live, &[v.path.clone()], &Some(caption(&v.title, &info)), "Too big for Discord's upload budget here").await; - } publish(job, live, &[v.path.clone()], Some(caption(&v.title, &info)), result_row(owner, &v.url)).await } Outcome::Gallery(g) => { @@ -571,9 +552,9 @@ mod tests { #[test] fn private_addresses_are_not_global() { - assert!(crate::commands::media::is_public_ip("93.184.216.34".parse().unwrap())); + assert!(is_global("93.184.216.34".parse().unwrap())); for bad in ["10.0.0.1", "192.168.1.71", "127.0.0.1", "169.254.1.1", "100.64.0.1", "::1", "fd00::1", "fe80::1"] { - assert!(!crate::commands::media::is_public_ip(bad.parse().unwrap()), "{bad}"); + assert!(!is_global(bad.parse().unwrap()), "{bad}"); } } diff --git a/src/commands/media/download/plan.rs b/src/commands/media/download/plan.rs index f22cc2d..6a683a4 100644 --- a/src/commands/media/download/plan.rs +++ b/src/commands/media/download/plan.rs @@ -11,7 +11,7 @@ pub const MAX_DURATION_SECONDS: f64 = 30.0 * 60.0; pub const DEFAULT_QUALITY_CAP: i64 = 1080; pub const AUDIO_EXT: &str = "opus"; pub const AUDIO_KBPS: i64 = 96; -pub const FALLBACK_UPLOAD_LIMIT: u64 = 10 * 1024 * 1024; +pub const FALLBACK_UPLOAD_LIMIT: u64 = 20 * 1024 * 1024; pub const SAFETY_MARGIN: f64 = 0.95; pub const FINAL_MARGIN: f64 = 0.99; pub const BPP_MIN: f64 = 0.065; diff --git a/src/commands/media/download/tools.rs b/src/commands/media/download/tools.rs index c81dca1..72d2eaa 100644 --- a/src/commands/media/download/tools.rs +++ b/src/commands/media/download/tools.rs @@ -268,7 +268,7 @@ pub struct Media { /// ffprobe the file: is this a real, playable video? None if ffprobe isn't installed. pub async fn inspect(path: &Path) -> Option { - let out = Command::new(tool("ffprobe")).args(["-v", "error", "-protocol_whitelist", "file", "-print_format", "json", "-show_streams", "-show_format"]).arg(path).stdin(Stdio::null()).output().await.ok()?; + let out = Command::new(tool("ffprobe")).args(["-v", "error", "-print_format", "json", "-show_streams", "-show_format"]).arg(path).stdin(Stdio::null()).output().await.ok()?; let data: Value = serde_json::from_slice(&out.stdout).unwrap_or(Value::Null); let streams = data.get("streams").and_then(Value::as_array).cloned().unwrap_or_default(); let is = |s: &Value, kind: &str| str_of(s, "codec_type") == Some(kind); @@ -300,7 +300,7 @@ pub async fn inspect(path: &Path) -> Option { } // a real decode test: how many frames come out of the first 3 seconds? let decode = Command::new(tool("ffprobe")) - .args(["-v", "error", "-protocol_whitelist", "file", "-select_streams", "v:0", "-read_intervals", "%+3", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "json"]) + .args(["-v", "error", "-select_streams", "v:0", "-read_intervals", "%+3", "-count_frames", "-show_entries", "stream=nb_read_frames", "-of", "json"]) .arg(path) .stdin(Stdio::null()) .output() @@ -362,7 +362,7 @@ pub async fn stream_convert(job: &Job, streams: &[Stream], out_args: &[String], if !headers.is_empty() { args.extend([s("-headers"), headers]); } - args.extend([s("-protocol_whitelist"), s("http,https,tcp,tls,crypto"), s("-i"), st.url.clone()]); + args.extend([s("-i"), st.url.clone()]); } let vi = streams.iter().position(|x| x.video).ok_or_else(|| DlError::user("Conversion failed", "No video stream to convert."))?; args.extend([s("-map"), format!("{vi}:v:0")]); @@ -402,7 +402,7 @@ pub async fn compress(job: &Job, src: &Path, meta: &Media, quality_first: bool) let Some((vb, audio, target_h)) = compress_plan(job.limit, meta.duration, meta.width, meta.height, fps, factor) else { return Err(DlError::user("Too long to fit", format!("A {} video can't be compressed under **{}** at watchable quality.", fmt_dur(Some(meta.duration)), fmt_bytes(job.limit as f64)))); }; - let mut args: Vec = vec![s("-protocol_whitelist"), s("file"), s("-i"), src.display().to_string(), s("-map"), s("0:v:0"), s("-map"), s("0:a:0?")]; + let mut args: Vec = vec![s("-i"), src.display().to_string(), s("-map"), s("0:v:0"), s("-map"), s("0:a:0?")]; if !(meta.height > 0 && target_h == meta.height) { args.extend([s("-vf"), format!("scale=-2:{target_h}")]); } @@ -460,7 +460,7 @@ pub async fn ensure_playable(job: &Job, path: PathBuf, media: Option, met if video_ok { let out = path.with_file_name(format!("{}_ok.mp4", path.file_stem().and_then(|x| x.to_str()).unwrap_or("video"))); job.set("Making it playable", "🛠️", "Fixing the container/audio - video untouched", true); - let mut args: Vec = ["-fflags", "+genpts", "-protocol_whitelist", "file", "-i"].map(s).to_vec(); + let mut args: Vec = ["-fflags", "+genpts", "-i"].map(s).to_vec(); args.push(path.display().to_string()); args.extend(["-map", "0:v:0", "-map", "0:a:0?", "-c:v", "copy"].map(s)); if audio_ok { @@ -486,7 +486,7 @@ pub async fn ensure_playable(job: &Job, path: PathBuf, media: Option, met /// Opus at `kbps`, no video. pub async fn encode_opus(job: &Job, src: &Path, dst: &Path, kbps: i64, duration: Option) -> Result<(), DlError> { - let mut args: Vec = vec![s("-protocol_whitelist"), s("file"), s("-i"), src.display().to_string()]; + let mut args: Vec = vec![s("-i"), src.display().to_string()]; args.extend(["-vn", "-map", "0:a:0", "-c:a", "libopus"].map(s)); args.extend([s("-b:a"), format!("{kbps}k")]); args.extend(["-vbr", "on", "-application", "audio", "-threads", "2"].map(s)); @@ -512,7 +512,7 @@ pub async fn gallery(job: &Job, url: &str, dir: &Path, cookie: Option<&Path>) -> if let Some(c) = cookie { cmd.arg("--cookies").arg(c); } - cmd.arg("--").arg(url); + cmd.arg(url); job.set("Downloading images", "🖼️", "gallery-dl", true); let (_code, err) = run_lines(job, cmd, GALLERY_TIMEOUT, |_| Ok(()), || { let n = walk(dir).len(); @@ -606,29 +606,4 @@ mod tests { assert_eq!(names, vec!["img_1.png", "img_2.jpg", "img_10.jpg", "a_3.mp4"]); let _ = std::fs::remove_dir_all(&dir); } - - #[tokio::test] - async fn stuck_child_is_killed_at_the_limit() { - let job = Job::new(1, "u".into(), 1000, false); - let mut cmd = Command::new("sleep"); - cmd.arg("30"); - let start = std::time::Instant::now(); - let r = run_lines(&job, cmd, Duration::from_secs(2), |_| Ok(()), || {}).await; - assert!(r.is_err(), "a stuck child must time out"); - assert!(start.elapsed() < Duration::from_secs(6)); - } - - #[tokio::test] - async fn cancel_ends_a_running_child() { - let job = std::sync::Arc::new(Job::new(1, "u".into(), 1000, false)); - let j2 = job.clone(); - tokio::spawn(async move { - tokio::time::sleep(Duration::from_millis(500)).await; - j2.cancel(); - }); - let mut cmd = Command::new("sleep"); - cmd.arg("30"); - let r = run_lines(&job, cmd, Duration::from_secs(20), |_| Ok(()), || {}).await; - assert!(matches!(r, Err(DlError::Cancelled))); - } } diff --git a/src/commands/media/ffmpeg.rs b/src/commands/media/ffmpeg.rs index 2f7c6fc..2b01f82 100644 --- a/src/commands/media/ffmpeg.rs +++ b/src/commands/media/ffmpeg.rs @@ -24,16 +24,13 @@ impl Drop for Scratch { } } -/// Longest an ffprobe may run. It only reads headers; 60 s covers a slow remote file at ~425 KB/s down. Then it is killed. -const PROBE_SECONDS: Duration = Duration::from_secs(60); - /// Run ffmpeg quietly; on failure give the last words it said. pub async fn run(args: &[String], limit: Duration) -> Result<(), String> { let mut cmd = Command::new("ffmpeg"); cmd.args(["-hide_banner", "-loglevel", "error", "-nostdin", "-y"]).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped()).kill_on_drop(true); let child = cmd.spawn().map_err(|e| format!("ffmpeg isn't installed or can't start ({e})"))?; match tokio::time::timeout(limit, child.wait_with_output()).await { - Err(_) => Err("The conversion took too long (slow connection or a very big file). Try a smaller file or lower quality.".to_string()), + Err(_) => Err("that took too long".to_string()), Ok(Err(e)) => Err(e.to_string()), Ok(Ok(out)) if out.status.success() => Ok(()), Ok(Ok(out)) => { @@ -172,10 +169,6 @@ impl Source { } /// Reading from the web: only http(s), and reconnect when the connection drops. -/// Local files: only the file itself, so a file that is secretly a playlist can't make ffmpeg open other files or -/// addresses. -pub const LOCAL_ONLY: [&str; 2] = ["-protocol_whitelist", "file"]; - const NET_ARGS: [&str; 8] = ["-protocol_whitelist", "http,https,tcp,tls,crypto", "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_delay_max", "5"]; /// What a file really is: its kind, and whether a picture is animated (a GIF or animated WebP). @@ -290,8 +283,10 @@ struct Info { async fn inspect(target: &str, head: &[u8], online: bool) -> Info { let mut cmd = Command::new("ffprobe"); cmd.args(["-v", "error", "-show_entries", "format=duration:stream=codec_type,width,height", "-of", "default=nw=1"]); - cmd.args(["-protocol_whitelist", if online { "http,https,tcp,tls,crypto" } else { "file" }]); - let out = tokio::time::timeout(PROBE_SECONDS, cmd.arg(target).stdin(Stdio::null()).kill_on_drop(true).output()).await.ok().and_then(|r| r.ok()); + if online { + cmd.args(["-protocol_whitelist", "http,https,tcp,tls,crypto"]); + } + let out = tokio::time::timeout(Duration::from_secs(60), cmd.arg(target).stdin(Stdio::null()).output()).await.ok().and_then(|r| r.ok()); let text = out.map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); let num = |key: &str| text.lines().find_map(|l| l.strip_prefix(key)?.parse::().ok()).unwrap_or(0.0); Info { @@ -519,9 +514,7 @@ pub async fn convert_to(input: &Source, fmt: &Format, quality: Quality, limit: u Source::Bytes(b) => { let src = scratch.path("input.bin"); std::fs::write(&src, b).map_err(|e| e.to_string())?; - let mut a: Vec = LOCAL_ONLY.iter().map(|x| x.to_string()).collect(); - a.extend([s("-i"), src.display().to_string()]); - (a, src.display().to_string(), false) + (vec![s("-i"), src.display().to_string()], src.display().to_string(), false) } Source::Url { url, .. } => { let mut a: Vec = NET_ARGS.iter().map(|x| x.to_string()).collect(); @@ -606,9 +599,13 @@ pub fn extension(name: &str) -> Option<&str> { /// ffprobe: length in seconds and whether there's a video stream, or None if it can't be read. pub async fn probe(path: &Path) -> Option<(f64, bool)> { - let mut cmd = Command::new("ffprobe"); - cmd.args(["-v", "error", "-show_entries", "format=duration:stream=codec_type", "-of", "default=nw=1"]).args(LOCAL_ONLY).arg(path).stdin(Stdio::null()).kill_on_drop(true); - let out = tokio::time::timeout(PROBE_SECONDS, cmd.output()).await.ok()?.ok()?; + let out = Command::new("ffprobe") + .args(["-v", "error", "-show_entries", "format=duration:stream=codec_type", "-of", "default=nw=1"]) + .arg(path) + .stdin(Stdio::null()) + .output() + .await + .ok()?; let text = String::from_utf8_lossy(&out.stdout); let duration = text.lines().find_map(|l| l.strip_prefix("duration=")?.parse::().ok()).unwrap_or(0.0); Some((duration, text.contains("codec_type=video"))) @@ -835,47 +832,3 @@ mod tests { assert!(err.contains("no sound"), "{err}"); } } - -#[cfg(test)] -mod hostile_tests { - use super::*; - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - - /// A local listener that records whether anything connected. - async fn spy() -> (u16, std::sync::Arc) { - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let port = listener.local_addr().unwrap().port(); - let hit = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); - let h = hit.clone(); - tokio::spawn(async move { - while let Ok((mut s, _)) = listener.accept().await { - h.store(true, std::sync::atomic::Ordering::SeqCst); - let mut b = [0u8; 512]; - let _ = s.read(&mut b).await; - let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n").await; - } - }); - (port, hit) - } - - #[tokio::test] - async fn a_playlist_cannot_make_ffmpeg_open_files_or_addresses() { - if std::process::Command::new("ffmpeg").arg("-version").output().is_err() { - return; - } - let (port, hit) = spy().await; - // check 4: playlist naming a local file, fed as bytes - let list = b"#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nfile:///etc/passwd\n#EXT-X-ENDLIST\n".to_vec(); - let f = find_format("mp4", Some(MediaType::Video)).unwrap(); - let out = convert_to(&Source::Bytes(list), f, Quality::Adaptive, 20 << 20).await; - assert!(out.is_err(), "playlist must not convert"); - // check 5: probe a local playlist that points at a local server - let scratch = Scratch::new().unwrap(); - let p = scratch.path("list.m3u8"); - std::fs::write(&p, format!("#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-TARGETDURATION:1\n#EXTINF:1,\nhttp://127.0.0.1:{port}/x.ts\n#EXT-X-ENDLIST\n")).unwrap(); - let _ = probe(&p).await; - let _ = inspect(&p.display().to_string(), b"", false).await; - tokio::time::sleep(Duration::from_millis(300)).await; - assert!(!hit.load(std::sync::atomic::Ordering::SeqCst), "the local server got a request"); - } -} diff --git a/src/commands/media/images.rs b/src/commands/media/images.rs index 110e105..dd04eb1 100644 --- a/src/commands/media/images.rs +++ b/src/commands/media/images.rs @@ -1,66 +1,257 @@ -//! `/caption` (`D!caption`): a white band with text above a picture, GIF, WebP or video, and petpet GIFs (`/petpet`). +//! Image effects and filters (`/image`, `D!fx`), converting pictures and videos (`/convert`, or the +//! `convert` option of `/image`), and petpet GIFs (`/petpet`, `D!petpet`). //! -//! `pick_opt` finds the media (attachment, link, reply, avatar, emoji); `/convert` shares it. - -use super::convert::last_chat_media; -use super::ffmpeg::{self, Scratch}; -use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_budget, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; +//! The picture can come from an attachment, the message you reply to, someone's avatar (@mention / +//! name), a custom emoji or a link; with nothing given, your own avatar is used. GIFs keep their +//! animation. Everything is drawn in a worker thread at a sensible size, so a big GIF can't freeze the bot. +use super::{avatar, custom_emojis, emoji_url, fetch_limited, has_ext, replied, safe_url, upload_limit, AUDIO_EXTS, IMAGE_EXTS, VIDEO_EXTS}; use crate::bail_user; use crate::cmd::{Command, Ctx, Opt, OptKind}; use crate::converters::find_member; use crate::pix; use crate::text::{self, Look}; -use crate::ui::{escape, truncate, Card}; +use crate::ui::{escape, file_display, truncate, Card}; use anyhow::Result; use cosmic_text::Align; use futures::FutureExt; use image::codecs::gif::{GifDecoder, GifEncoder, Repeat}; use image::codecs::webp::WebPDecoder; -use image::{imageops, AnimationDecoder, Delay, Frame, ImageDecoder, Rgba, RgbaImage}; +use image::{imageops, AnimationDecoder, Delay, Frame, GrayImage, Rgba, RgbaImage}; use std::io::Cursor; use std::sync::Arc; -use std::time::Duration; const MAX_SIDE: u32 = 1024; const MAX_GIF_SIDE: u32 = 480; const MAX_FRAMES: usize = 120; -/// Longest caption text. A band this tall already eats most of a small picture. -const MAX_CAPTION_CHARS: usize = 500; -/// Video is cut to this many seconds at this frame rate (so at most MAX_FRAMES frames) before captioning. -const VIDEO_SECONDS: u32 = 10; -const VIDEO_FPS: u32 = 12; -/// Widest video frame we caption; the line is slow, so a small clip is also a clip that uploads. -const MAX_VIDEO_SIDE: u32 = 480; -/// Time limits for the two ffmpeg runs of a video caption (cut to frames, encode back). -const VIDEO_DECODE_SECONDS: u64 = 60; -const VIDEO_ENCODE_SECONDS: u64 = 120; const MAX_IMAGE_BYTES: usize = 15 * 1024 * 1024; -/// Memory all decoded frames of one GIF / WebP may take together (each frame is a full RGBA canvas). A small file -/// can declare a huge canvas, so frames are cut to fit this (decode bombs). -const MAX_ANIMATION_BYTES: u64 = 256 * 1024 * 1024; -/// How many frames of a `w`×`h` animation fit in [`MAX_ANIMATION_BYTES`] (at most [`MAX_FRAMES`]). -fn frame_cap((w, h): (u32, u32)) -> usize { - (MAX_ANIMATION_BYTES / (w as u64 * h as u64 * 4).max(1)).min(MAX_FRAMES as u64) as usize +pub const EFFECTS: [&str; 10] = ["speechbubble", "caption", "blur", "pixelate", "flip", "mirror", "deepfry", "vignette", "border", "circle"]; +pub const FILTERS: [&str; 14] = [ + "grayscale", "sepia", "gotham", "invert", "warm", "cold", "vintage", "cyberpunk", "nostalgia", "sunset", "nightvision", "pencil_sketch", "oil_painting", "pop_art", +]; + +#[derive(Clone, Debug)] +pub struct Opts { + pub text: String, + pub bottom: bool, + pub radius: f32, + pub size: u32, + pub level: u32, +} + +impl Default for Opts { + fn default() -> Self { + Self { text: String::new(), bottom: false, radius: 5.0, size: 10, level: 3 } + } +} + +// ---- pixel work (runs in a thread) ---------------------------------------------------------- + +fn noise() -> f32 { + (rand::random::() as f32 + rand::random::() as f32 + rand::random::() as f32) / 765.0 - 0.5 +} + +pub fn vignette(img: &mut RgbaImage) { + let (w, h) = (img.width() as f32, img.height() as f32); + for (x, y, p) in img.enumerate_pixels_mut() { + let d = (((x as f32 - w / 2.0) / (0.7 * w)).powi(2) + ((y as f32 - h / 2.0) / (0.7 * h)).powi(2)).sqrt(); + let keep = 1.0 / (1.0 + ((d - 1.0) / 0.16).exp()); + for c in 0..3 { + p[c] = (p[c] as f32 * keep).round() as u8; + } + } +} + +const SEPIA: [[f32; 3]; 3] = [[0.393, 0.769, 0.189], [0.349, 0.686, 0.168], [0.272, 0.534, 0.131]]; + +fn diag(r: f32, g: f32, b: f32) -> [[f32; 3]; 3] { + [[r, 0.0, 0.0], [0.0, g, 0.0], [0.0, 0.0, b]] +} + +fn oil(img: &RgbaImage) -> RgbaImage { + let (w, h) = img.dimensions(); + let mut out = img.clone(); + for y in 0..h { + for x in 0..w { + for c in 0..3 { + let mut bins = [0u8; 64]; + for ny in y.saturating_sub(3)..(y + 4).min(h) { + for nx in x.saturating_sub(3)..(x + 4).min(w) { + bins[(img.get_pixel(nx, ny)[c] >> 2) as usize] += 1; + } + } + let best = bins.iter().enumerate().max_by_key(|(_, n)| **n).map_or(0, |(i, _)| i); + out.get_pixel_mut(x, y)[c] = (best as u8) * 4 + 2; + } + } + } + out +} + +pub fn apply_filter(img: &mut RgbaImage, name: &str) { + match name { + "grayscale" => pix::grayscale(img), + "sepia" => pix::matrix(img, SEPIA), + "gotham" => { + pix::matrix(img, diag(1.0, 1.0, 1.2)); + pix::contrast(img, 1.3); + } + "invert" => { + for p in img.pixels_mut() { + for c in 0..3 { + p[c] = 255 - p[c]; + } + } + } + "warm" => pix::matrix(img, diag(1.25, 1.0, 0.85)), + "cold" => pix::matrix(img, diag(0.85, 1.0, 1.25)), + "vintage" => { + pix::matrix(img, SEPIA); + vignette(img); + let alpha: Vec = img.pixels().map(|p| p[3]).collect(); + *img = imageops::blur(img, 0.7); + for (p, a) in img.pixels_mut().zip(alpha) { + p[3] = a; + } + } + "cyberpunk" => { + pix::matrix(img, diag(1.3, 1.0, 1.5)); + pix::contrast(img, 1.5); + pix::sharpen(img, 2.0); + } + "nostalgia" => { + pix::matrix(img, diag(1.25, 1.0, 0.85)); + pix::saturate(img, 0.7); + for p in img.pixels_mut() { + let n = 128.0 + noise() * 60.0; + for c in 0..3 { + p[c] = (p[c] as f32 * 0.9 + n * 0.1).clamp(0.0, 255.0).round() as u8; + } + } + } + "sunset" => pix::matrix(img, diag(1.4, 1.1, 0.7)), + "nightvision" => { + pix::grayscale(img); + for p in img.pixels_mut() { + let g = p[0] as f32; + p[0] = (g * 0.3) as u8; + p[1] = (g * 1.3).min(255.0) as u8; + p[2] = (g * 0.3) as u8; + } + } + "pencil_sketch" => { + pix::grayscale(img); + let inverted = GrayImage::from_fn(img.width(), img.height(), |x, y| image::Luma([255 - img.get_pixel(x, y)[0]])); + let blur = pix::blur_mask(&inverted, 4.0); + for (x, y, p) in img.enumerate_pixels_mut() { + let dodge = (p[0] as f32 * 255.0 / (255.0 - blur.get_pixel(x, y)[0] as f32).max(1.0)).clamp(0.0, 255.0) as u8; + p[0] = dodge; + p[1] = dodge; + p[2] = dodge; + } + } + "oil_painting" => *img = oil(img), + _ => { + // pop art + pix::saturate(img, 2.5); + pix::contrast(img, 1.8); + pix::posterize(img, 3); + } + } +} + +fn speech_bubble(img: &mut RgbaImage, bottom: bool) { + let (w, h) = (img.width() as f32, img.height() as f32); + let bh = (h / 5.0).max(24.0); + // y is measured from the edge the bubble hangs off + let edge = |y: f32| if bottom { h - y } else { y }; + let tri = [(0.55 * w, 0.5 * bh), (0.7 * w, 1.8 * bh), (0.65 * w, 0.4 * bh)]; + let in_tri = |px: f32, py: f32| { + let s = |a: (f32, f32), b: (f32, f32)| (px - b.0) * (a.1 - b.1) - (a.0 - b.0) * (py - b.1); + let (d1, d2, d3) = (s(tri[0], tri[1]), s(tri[1], tri[2]), s(tri[2], tri[0])); + !((d1 < 0.0 || d2 < 0.0 || d3 < 0.0) && (d1 > 0.0 || d2 > 0.0 || d3 > 0.0)) + }; + for (x, y, p) in img.enumerate_pixels_mut() { + let (px, py) = (x as f32 + 0.5, edge(y as f32 + 0.5)); + let ellipse = ((px - 0.5 * w) / (0.6 * w)).powi(2) + (py / bh).powi(2) <= 1.0; + if ellipse || in_tri(px, py) { + p[3] = 0; + } + } +} + +fn caption(img: &RgbaImage, words: &str) -> RgbaImage { + let w = img.width(); + let size = (w / 12).max(16) as f32; + let look = Look::new(None, true, [0, 0, 0]); + let para = text::layout(words, size, &look, Some(w as f32 - size), Align::Center); + let pad = (size / 2.0) as u32; + let strip = para.height.ceil() as u32 + pad * 2; + let mut out = RgbaImage::from_pixel(w, img.height() + strip, Rgba([255, 255, 255, 255])); + para.draw(&mut out, (size / 2.0) as i32, pad as i32); + imageops::overlay(&mut out, img, 0, strip as i64); + out +} + +fn deepfry(img: &mut RgbaImage, level: u32) { + let l = level as f32; + pix::saturate(img, 1.0 + l * 0.8); + pix::contrast(img, 1.0 + l * 0.6); + pix::sharpen(img, 1.0 + l * 0.4); + let alpha: Vec = img.pixels().map(|p| p[3]).collect(); + let rgb = image::DynamicImage::ImageRgba8(img.clone()).to_rgb8(); + let mut buf = Cursor::new(Vec::new()); + let quality = (100 - level as i32 * 20).max(5) as u8; + if rgb.write_with_encoder(image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, quality)).is_ok() { + if let Ok(back) = image::load_from_memory_with_format(buf.get_ref(), image::ImageFormat::Jpeg) { + *img = back.to_rgba8(); + } + } + for (p, a) in img.pixels_mut().zip(alpha) { + let n = (rand::random::() as i32 % 100 - 50) * level as i32 / 5; + for c in 0..3 { + p[c] = (p[c] as i32 + n).clamp(0, 255) as u8; + } + p[3] = a; + } +} + +pub fn apply_effect(img: RgbaImage, name: &str, o: &Opts) -> RgbaImage { + let mut img = img; + match name { + "speechbubble" => speech_bubble(&mut img, o.bottom), + "caption" => return caption(&img, &o.text), + "blur" => return imageops::blur(&img, o.radius), + "pixelate" => { + let size = o.size.max(2); + let small = imageops::resize(&img, (img.width() / size).max(1), (img.height() / size).max(1), imageops::FilterType::Nearest); + return imageops::resize(&small, img.width(), img.height(), imageops::FilterType::Nearest); + } + "flip" => imageops::flip_vertical_in_place(&mut img), + "mirror" => imageops::flip_horizontal_in_place(&mut img), + "deepfry" => deepfry(&mut img, o.level), + "vignette" => vignette(&mut img), + "border" => { + let b = (img.width() / 40).max(6); + let mut out = RgbaImage::from_pixel(img.width() + 2 * b, img.height() + 2 * b, Rgba([255, 255, 255, 255])); + imageops::overlay(&mut out, &img, b as i64, b as i64); + return out; + } + _ => pix::circle(&mut img), + } + img } /// Decode every frame of an animated GIF / WebP (None for pictures that don't move). fn frames_of(bytes: &[u8]) -> Option> { let frames: Vec = match image::guess_format(bytes).ok()? { - image::ImageFormat::Gif => { - let mut d = GifDecoder::new(Cursor::new(bytes)).ok()?; - d.set_limits(pix::limits()).ok()?; - let cap = frame_cap(d.dimensions()); - d.into_frames().take(cap).filter_map(|f| f.ok()).collect() - } + image::ImageFormat::Gif => GifDecoder::new(Cursor::new(bytes)).ok()?.into_frames().take(MAX_FRAMES).filter_map(|f| f.ok()).collect(), image::ImageFormat::WebP => { - let mut d = WebPDecoder::new(Cursor::new(bytes)).ok()?; + let d = WebPDecoder::new(Cursor::new(bytes)).ok()?; if !d.has_animation() { return None; } - d.set_limits(pix::limits()).ok()?; - let cap = frame_cap(d.dimensions()); - d.into_frames().take(cap).filter_map(|f| f.ok()).collect() + d.into_frames().take(MAX_FRAMES).filter_map(|f| f.ok()).collect() } _ => return None, }; @@ -89,6 +280,26 @@ pub fn encode_gif(frames: Vec<(RgbaImage, u32)>) -> Option> { Some(out) } +/// (file bytes, extension). `max_gif` is the biggest side for animated results. +pub fn process(bytes: &[u8], effect: Option<&str>, filter: Option<&str>, opts: &Opts, max_gif: u32) -> Option<(Vec, &'static str)> { + let one = |frame: RgbaImage, limit: u32| { + let mut f = pix::thumbnail(&frame, limit); + if let Some(e) = effect { + f = apply_effect(f, e, opts); + } + if let Some(name) = filter { + apply_filter(&mut f, name); + } + f + }; + if let Some(frames) = frames_of(bytes) { + let done: Vec<_> = frames.into_iter().map(|(f, ms)| (one(f, max_gif), ms)).collect(); + return Some((encode_gif(done)?, "gif")); + } + let still = pix::decode(bytes)?; + Some((pix::encode_png(&one(still, MAX_SIDE)), "png")) +} + /// Offline petpet stand-in: the picture squishes like it's being patted. pub fn squish_gif(bytes: &[u8]) -> Option> { let base = pix::thumbnail(&pix::decode(bytes)?, 112); @@ -111,13 +322,13 @@ pub fn squish_gif(bytes: &[u8]) -> Option> { pub(super) async fn pick_opt(ctx: &Ctx, text: &str) -> Result> { let state = &ctx.state; if ctx.is_slash() { - if let Some(a) = ctx.args.id("source-attachment").or_else(|| ctx.args.id("file")).or_else(|| ctx.args.id("image")).and_then(|id| ctx.attachments.iter().find(|a| a.id.get() == id)) { + if let Some(a) = ctx.args.id("file").or_else(|| ctx.args.id("image")).and_then(|id| ctx.attachments.iter().find(|a| a.id.get() == id)) { return Ok(Some((a.url.clone(), text.to_string()))); } if let Some(u) = ctx.args.user("user") { return Ok(Some((avatar(state, u, 512).await, text.to_string()))); } - if let Some(url) = ctx.args.str("source-link").or_else(|| ctx.args.str("url")) { + if let Some(url) = ctx.args.str("url") { if safe_url(url).is_none() { bail_user!("That doesn't look like a public link."); } @@ -165,6 +376,109 @@ pub(super) async fn pick_opt(ctx: &Ctx, text: &str) -> Result Result<(String, String)> { + if let Some(found) = pick_opt(ctx, text).await? { + return Ok(found); + } + let who = if ctx.is_slash() { ctx.user_id } else { replied(ctx).await.map_or(ctx.user_id, |m| m.author.id) }; + Ok((avatar(&ctx.state, who, 512).await, text.to_string())) +} + +// ---- /image, D!fx ------------------------------------------------------------------------------ + +fn resolve_name(name: &str) -> (Option<&'static str>, Option<&'static str>) { + let n = name.to_lowercase().replace('-', "_"); + let n = match n.as_str() { + "bubble" | "speech" => "speechbubble", + "pixel" => "pixelate", + "fry" => "deepfry", + "gray" | "grey" | "bw" => "grayscale", + "sketch" => "pencil_sketch", + "oil" => "oil_painting", + "popart" => "pop_art", + other => other, + } + .to_string(); + (EFFECTS.iter().copied().find(|e| *e == n), FILTERS.iter().copied().find(|f| *f == n)) +} + +/// Effects and filters on a picture or GIF: the shared job behind `/media` and `D!fx`. +async fn run_job(ctx: &Arc, url: &str, effect: Option<&'static str>, filter: Option<&'static str>, opts: Opts) -> Result<()> { + let limit = upload_limit(ctx); + ctx.defer().await?; + let Some(data) = fetch_limited(&ctx.state, url, MAX_IMAGE_BYTES).await else { + bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); + }; + let bytes = data; + let base = effect.or(filter).unwrap_or("image").to_string(); + if !matches!(image::guess_format(&bytes), Ok(image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP | image::ImageFormat::Bmp)) { + bail_user!("Effects and filters work on pictures and GIFs. To change a file's format use `/convert`."); + } + let mut done = None; + for side in [MAX_GIF_SIDE, 320, 220] { + let (b, o) = (bytes.clone(), opts.clone()); + let result = tokio::task::spawn_blocking(move || process(&b, effect, filter, &o, side)).await?; + let Some((out, e)) = result else { bail_user!("That doesn't look like a picture I can read.") }; + let fits = out.len() <= limit; + done = Some((out, e)); + if fits || e == "png" { + break; + } + } + let Some((bytes, ext)) = done else { bail_user!("That didn't work.") }; + if bytes.len() > limit { + bail_user!("The result is too big to upload ({} MB, the limit here is {} MB).", bytes.len() / 1024 / 1024, limit / 1024 / 1024); + } + let name = format!("{base}.{ext}"); + ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, bytes).await +} + +async fn image_cmd(ctx: Arc) -> Result<()> { + let a = &ctx.args; + let mut opts = Opts::default(); + let (effect, filter, rest); + if ctx.is_slash() { + effect = a.str("effect").and_then(|n| resolve_name(n).0); + filter = a.str("filter").and_then(|n| resolve_name(n).1); + opts.text = a.str("text").unwrap_or("").to_string(); + opts.bottom = a.str("bubble_position") == Some("bottom"); + opts.radius = a.int("blur_radius").unwrap_or(5).clamp(1, 20) as f32; + opts.size = a.int("pixel_size").unwrap_or(10).clamp(2, 50) as u32; + opts.level = a.int("deepfry_level").unwrap_or(3).clamp(1, 5) as u32; + rest = String::new(); + if effect.is_none() && filter.is_none() { + bail_user!("Pick an `effect` or a `filter`. To change a file's format use `/convert`."); + } + } else { + let name = a.str("name").unwrap_or(""); + let (e, f) = resolve_name(name); + if e.is_none() && f.is_none() { + bail_user!("`{}` isn't an effect or filter — see `{}help fx`. To change a file's format use `{}convert`.", escape(&truncate(name, 40)), ctx.state.prefix(ctx.guild_id), ctx.state.prefix(ctx.guild_id)); + } + (effect, filter) = (e, f); + rest = a.str("rest").unwrap_or("").to_string(); + } + if effect == Some("caption") && ctx.is_slash() && opts.text.is_empty() { + bail_user!("The caption effect needs `text`."); + } + let (url, left) = pick(&ctx, &rest).await?; + if !ctx.is_slash() { + let left = left.trim(); + opts.text = left.to_string(); + opts.bottom = left.to_lowercase().contains("bottom"); + if effect == Some("caption") && left.is_empty() { + bail_user!("What should the caption say? `{}fx caption `", ctx.state.prefix(ctx.guild_id)); + } + if let (Ok(n), Some("blur" | "pixelate" | "deepfry")) = (left.parse::(), effect) { + opts.radius = n.clamp(1, 20) as f32; + opts.size = n.clamp(2, 50) as u32; + opts.level = n.clamp(1, 5) as u32; + } + } + run_job(&ctx, &url, effect, filter, opts).await +} + // ---- petpet --------------------------------------------------------------------------------------- async fn petpet(ctx: Arc) -> Result<()> { @@ -209,395 +523,26 @@ async fn petpet(ctx: Arc) -> Result<()> { ctx.reply_file(Card::new(None).gallery(&["attachment://petpet.gif"]).build(), "petpet.gif", gif).await } -// ---- caption ----------------------------------------------------------------------------------- - -/// The white band with the centred black text, `width` pixels wide. Its height is always even (video needs that). -fn caption_band(width: u32, words: &str) -> RgbaImage { - let size = (width / 12).max(16) as f32; - let look = Look::new(None, true, [0, 0, 0]); - let para = text::layout(words, size, &look, Some(width as f32 - size), Align::Center); - let pad = (size / 2.0) as u32; - let height = (para.height.ceil() as u32 + pad * 2 + 1) & !1; - let mut band = RgbaImage::from_pixel(width, height, Rgba([255, 255, 255, 255])); - para.draw(&mut band, (size / 2.0) as i32, pad as i32); - band -} - -/// The band on top, the picture under it. Transparent pixels of the picture show white. -fn stack(band: &RgbaImage, img: &RgbaImage) -> RgbaImage { - let mut out = RgbaImage::from_pixel(band.width(), band.height() + img.height(), Rgba([255, 255, 255, 255])); - imageops::overlay(&mut out, band, 0, 0); - imageops::overlay(&mut out, img, 0, band.height() as i64); - out -} - -/// (file bytes, extension) for a picture, GIF or animated WebP. None if it isn't one. -fn caption_image(bytes: &[u8], words: &str, max_gif: u32) -> Option<(Vec, &'static str)> { - if let Some(frames) = frames_of(bytes) { - let frames: Vec<_> = frames.into_iter().map(|(f, ms)| (pix::thumbnail(&f, max_gif), ms)).collect(); - let band = caption_band(frames[0].0.width(), words); - return Some((encode_gif(frames.into_iter().map(|(f, ms)| (stack(&band, &f), ms)).collect())?, "gif")); - } - let still = pix::thumbnail(&pix::decode(bytes)?, MAX_SIDE); - let band = caption_band(still.width(), words); - Some((pix::encode_png(&stack(&band, &still)), "png")) -} - -/// A picture too big as PNG goes out as JPEG instead. -fn as_jpeg(png: &[u8]) -> Option> { - let rgb = image::load_from_memory(png).ok()?.to_rgb8(); - let mut out = Vec::new(); - image::DynamicImage::ImageRgb8(rgb).write_to(&mut Cursor::new(&mut out), image::ImageFormat::Jpeg).ok()?; - Some(out) -} - -/// Cut a clip to frames (`f%04d.png` in `scratch`, at most `VIDEO_SECONDS` at `VIDEO_FPS`, `max_side` wide), run `edit` on each, -/// write them back. Returns the frame count. -async fn map_frames(scratch: &Scratch, bytes: &[u8], max_side: u32, mut edit: impl FnMut(&RgbaImage) -> RgbaImage + Send + 'static) -> Result { - if super::is_playlist(bytes) { - return Err("Playlists and stream lists can't be used, only the video itself.".into()); - } - let input = scratch.path("in"); - std::fs::write(&input, bytes).map_err(|e| e.to_string())?; - let pattern = scratch.path("f%04d.png").to_string_lossy().to_string(); - let filter = format!("fps={VIDEO_FPS},scale='min({max_side},iw)':-2"); - let mut cut: Vec = [ffmpeg::LOCAL_ONLY[0], ffmpeg::LOCAL_ONLY[1], "-i", &input.to_string_lossy(), "-t", &VIDEO_SECONDS.to_string(), "-vf", &filter, "-frames:v", &MAX_FRAMES.to_string()].iter().map(|s| s.to_string()).collect(); - cut.push(pattern); - ffmpeg::run(&cut, Duration::from_secs(VIDEO_DECODE_SECONDS)).await?; - let dir = scratch.path(""); - let count = tokio::task::spawn_blocking(move || { - let mut n = 0; - for i in 1..=MAX_FRAMES { - let path = dir.join(format!("f{i:04}.png")); - let Ok(raw) = std::fs::read(&path) else { break }; - let Some(frame) = pix::decode(&raw) else { break }; - if std::fs::write(&path, pix::encode_png(&edit(&frame))).is_err() { - break; - } - n = i; - } - n - }) - .await - .map_err(|e| e.to_string())?; - if count == 0 { - return Err("I couldn't read any frames from that video.".to_string()); - } - Ok(count) -} - -/// A clip: caption each frame, encode back to MP4 (no sound). `crf` is the quality, higher is smaller. -async fn caption_video(bytes: &[u8], words: &str, crf: u32) -> Result, String> { - let scratch = Scratch::new().map_err(|e| e.to_string())?; - let arg = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); - let pattern = scratch.path("f%04d.png").to_string_lossy().to_string(); - let words = words.to_string(); - let mut band: Option = None; - map_frames(&scratch, bytes, MAX_VIDEO_SIDE, move |frame| { - let band = band.get_or_insert_with(|| caption_band(frame.width(), &words)); - stack(band, frame) - }) - .await?; - let out = scratch.path("out.mp4"); - let mut enc = arg(&["-framerate", &VIDEO_FPS.to_string(), "-i"]); - enc.push(pattern); - enc.extend(arg(&["-c:v", "libx264", "-preset", "veryfast", "-crf", &crf.to_string(), "-pix_fmt", "yuv420p", "-movflags", "+faststart"])); - enc.push(out.to_string_lossy().to_string()); - ffmpeg::run(&enc, Duration::from_secs(VIDEO_ENCODE_SECONDS)).await?; - std::fs::read(&out).map_err(|e| e.to_string()) -} - -async fn caption_cmd(ctx: Arc) -> Result<()> { - let _busy = super::one_job(&ctx)?; - let prefix = ctx.state.prefix(ctx.guild_id); - let (found, words) = if ctx.is_slash() { - let words = ctx.args.str("text").unwrap_or("").to_string(); - (pick_opt(&ctx, &words).await?, words) - } else { - let rest = ctx.args.str("rest").unwrap_or("").to_string(); - match pick_opt(&ctx, &rest).await? { - Some((u, left)) => (Some((u, left.clone())), left), - None => (None, rest), - } - }; - let words = words.trim().to_string(); - if words.is_empty() { - bail_user!("What should the caption say? `{prefix}caption ` or `/caption text:`"); - } - if words.chars().count() > MAX_CAPTION_CHARS { - bail_user!("That caption is too long (max {MAX_CAPTION_CHARS} characters)."); - } - let limit = upload_budget(&ctx); - ctx.defer().await?; - let url = match found { - Some((u, _)) => u, - None => match last_chat_media(&ctx).await { - Some(u) => u, - None => bail_user!("Attach a picture, give a link, reply to one, or post one in this channel first."), - }, - }; - let Some(bytes) = fetch_limited(&ctx.state, &url, MAX_IMAGE_BYTES).await else { - bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); - }; - let (out, ext) = if image::guess_format(&bytes).is_ok() { - let mut done = None; - for side in [MAX_GIF_SIDE, 320, 220] { - let (b, w) = (bytes.clone(), words.clone()); - let Some((out, e)) = tokio::task::spawn_blocking(move || caption_image(&b, &w, side)).await? else { - bail_user!("That doesn't look like a picture I can read."); - }; - let fits = out.len() <= limit; - done = Some((out, e)); - if fits || e == "png" { - break; - } - } - let (mut out, mut e) = done.expect("loop runs at least once"); - if e == "png" && out.len() > limit { - if let Some(j) = as_jpeg(&out) { - (out, e) = (j, "jpg"); - } - } - (out, e) - } else { - let probe_dir = Scratch::new()?; - let probe_file = probe_dir.path("probe"); - std::fs::write(&probe_file, &bytes)?; - if !matches!(ffmpeg::probe(&probe_file).await, Some((_, true))) { - bail_user!("I can caption pictures, GIFs, WebP and videos (MP4, WebM, MOV). That file is none of those."); - } - let mut out = Vec::new(); - for crf in [28, 34, 40] { - out = match caption_video(&bytes, &words, crf).await { - Ok(o) => o, - Err(e) => bail_user!("{}", escape(&truncate(&e, 200))), - }; - if out.len() <= limit { - break; - } - } - (out, "mp4") - }; - if out.len() > limit { - bail_user!("The result is too big to upload ({} MB, the limit here is {} MB).", out.len() / 1024 / 1024, limit / 1024 / 1024); - } - let name = format!("caption.{ext}"); - ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, out).await -} - -// ---- speech bubble ----------------------------------------------------------------------------- - -/// Where the bubble hangs and how it looks. -#[derive(Clone, Copy)] -struct Bubble { - bottom: bool, - flip: bool, - solid: bool, -} - -/// Bubble height as a share of the picture height (the ellipse's half-height; the tail reaches 1.6 times further). -const BUBBLE_HEIGHT: f32 = 0.2; -/// The ellipse is wider than the picture so its ends run off the sides and only the curve of the bottom shows. -const BUBBLE_WIDTH: f32 = 0.62; -/// Outline thickness is this share of the picture width (at least 2 px). -const BUBBLE_OUTLINE: f32 = 0.006; - -/// Which pixels belong to the bubble (ellipse plus tail), row by row. -fn bubble_mask(w: u32, h: u32, bottom: bool, flip: bool) -> Vec { - let (wf, hf) = (w as f32, h as f32); - let ry = (hf * BUBBLE_HEIGHT).max(8.0); - let rx = wf * BUBBLE_WIDTH; - let dir = if flip { -1.0 } else { 1.0 }; - // Tail: base inside the ellipse, tip further down and pulled back toward the middle. - let a = (wf / 2.0 + dir * wf * 0.12, ry * 0.7); - let b = (wf / 2.0 + dir * wf * 0.28, ry * 0.7); - let tip = (wf / 2.0 + dir * wf * 0.2, ry * 1.6); - let side = |p: (f32, f32), q: (f32, f32), x: f32, y: f32| (x - q.0) * (p.1 - q.1) - (p.0 - q.0) * (y - q.1); - let mut mask = vec![false; (w * h) as usize]; - for y in 0..h { - // `bottom` mirrors the whole shape top to bottom. - let fy = if bottom { h - 1 - y } else { y } as f32 + 0.5; - for x in 0..w { - let fx = x as f32 + 0.5; - let (dx, dy) = ((fx - wf / 2.0) / rx, fy / ry); - let in_ellipse = dx * dx + dy * dy <= 1.0; - let (d1, d2, d3) = (side(a, b, fx, fy), side(b, tip, fx, fy), side(tip, a, fx, fy)); - let in_tail = !((d1 < 0.0 || d2 < 0.0 || d3 < 0.0) && (d1 > 0.0 || d2 > 0.0 || d3 > 0.0)); - mask[(y * w + x) as usize] = in_ellipse || in_tail; - } - } - mask -} - -/// Cut the bubble out (transparent) or paint it (white fill, black outline). -fn draw_bubble(img: &mut RgbaImage, b: Bubble) { - let (w, h) = img.dimensions(); - let mask = bubble_mask(w, h, b.bottom, b.flip); - let t = ((w as f32 * BUBBLE_OUTLINE) as i64).max(2); - let inside = |x: i64, y: i64| x < 0 || y < 0 || x >= w as i64 || y >= h as i64 || mask[(y as u32 * w + x as u32) as usize]; - for y in 0..h as i64 { - for x in 0..w as i64 { - if !inside(x, y) { - continue; - } - let px = if !b.solid { - Rgba([0, 0, 0, 0]) - } else if [(t, 0), (-t, 0), (0, t), (0, -t), (t, t), (-t, -t), (t, -t), (-t, t)].iter().any(|(dx, dy)| !inside(x + dx, y + dy)) { - Rgba([0, 0, 0, 255]) - } else { - Rgba([255, 255, 255, 255]) - }; - img.put_pixel(x as u32, y as u32, px); - } - } -} - -/// (file bytes, extension) for a picture, GIF or animated WebP: PNG or GIF, both keep the cut-out transparent. -fn bubble_image(bytes: &[u8], b: Bubble, max_still: u32, max_gif: u32) -> Option<(Vec, &'static str)> { - if let Some(frames) = frames_of(bytes) { - let frames = frames - .into_iter() - .map(|(f, ms)| { - let mut f = pix::thumbnail(&f, max_gif); - draw_bubble(&mut f, b); - (f, ms) - }) - .collect(); - return Some((encode_gif(frames)?, "gif")); - } - let mut still = pix::thumbnail(&pix::decode(bytes)?, max_still); - draw_bubble(&mut still, b); - Some((pix::encode_png(&still), "png")) -} - -/// A clip with the bubble on every frame: MP4 when `solid`, otherwise a transparent GIF (video can't be transparent). -async fn bubble_video(bytes: &[u8], b: Bubble, crf: u32, max_side: u32) -> Result<(Vec, &'static str), String> { - let scratch = Scratch::new().map_err(|e| e.to_string())?; - let count = map_frames(&scratch, bytes, max_side, move |f| { - let mut f = f.clone(); - draw_bubble(&mut f, b); - f - }) - .await?; - if !b.solid { - let dir = scratch.path(""); - let frames = tokio::task::spawn_blocking(move || { - (1..=count).filter_map(|i| pix::decode(&std::fs::read(dir.join(format!("f{i:04}.png"))).ok()?)).map(|f| (f, 1000 / VIDEO_FPS)).collect::>() - }) - .await - .map_err(|e| e.to_string())?; - let gif = tokio::task::spawn_blocking(move || encode_gif(frames)).await.map_err(|e| e.to_string())?; - return gif.map(|g| (g, "gif")).ok_or_else(|| "I couldn't make a GIF from that video.".to_string()); - } - let out = scratch.path("out.mp4"); - let mut enc: Vec = ["-framerate", &VIDEO_FPS.to_string(), "-i"].iter().map(|s| s.to_string()).collect(); - enc.push(scratch.path("f%04d.png").to_string_lossy().to_string()); - enc.extend(["-c:v", "libx264", "-preset", "veryfast", "-crf", &crf.to_string(), "-pix_fmt", "yuv420p", "-movflags", "+faststart"].iter().map(|s| s.to_string())); - enc.push(out.to_string_lossy().to_string()); - ffmpeg::run(&enc, Duration::from_secs(VIDEO_ENCODE_SECONDS)).await?; - std::fs::read(&out).map(|v| (v, "mp4")).map_err(|e| e.to_string()) -} - -async fn speechbubble_cmd(ctx: Arc) -> Result<()> { - let _busy = super::one_job(&ctx)?; - let mut b = Bubble { bottom: false, flip: false, solid: false }; - let found = if ctx.is_slash() { - b.bottom = ctx.args.str("position") == Some("bottom"); - b.flip = ctx.args.bool("flip").unwrap_or(false); - b.solid = ctx.args.bool("solid").unwrap_or(false); - pick_opt(&ctx, "").await? - } else { - let rest = ctx.args.str("rest").unwrap_or("").to_string(); - let (found, left) = match pick_opt(&ctx, &rest).await? { - Some((u, left)) => (Some(u), left), - None => (None, rest), - }; - for w in left.split_whitespace() { - match w.to_lowercase().as_str() { - "bottom" => b.bottom = true, - "flip" => b.flip = true, - "solid" => b.solid = true, - _ => {} - } - } - found.map(|u| (u, String::new())) - }; - let limit = upload_budget(&ctx); - ctx.defer().await?; - let url = match found { - Some((u, _)) => u, - None => match last_chat_media(&ctx).await { - Some(u) => u, - None => bail_user!("Attach a picture, give a link, reply to one, or post one in this channel first."), - }, - }; - let Some(bytes) = fetch_limited(&ctx.state, &url, MAX_IMAGE_BYTES).await else { - bail_user!("I couldn't download that ({} MB max).", MAX_IMAGE_BYTES / 1024 / 1024); - }; - let (out, ext) = if image::guess_format(&bytes).is_ok() { - let mut done = None; - // Smaller and smaller until it fits; a still that is still too big goes out as JPEG only when solid (JPEG has no transparency). - for (still, gif) in [(MAX_SIDE, MAX_GIF_SIDE), (720, 320), (480, 220), (320, 160)] { - let (data, bb) = (bytes.clone(), b); - let Some((out, e)) = tokio::task::spawn_blocking(move || bubble_image(&data, bb, still, gif)).await? else { - bail_user!("That doesn't look like a picture I can read."); - }; - let fits = out.len() <= limit; - done = Some((out, e)); - if fits { - break; - } - } - let (mut out, mut e) = done.expect("loop runs at least once"); - if e == "png" && out.len() > limit && b.solid { - if let Some(j) = as_jpeg(&out) { - (out, e) = (j, "jpg"); - } - } - (out, e) - } else { - let probe_dir = Scratch::new()?; - let probe_file = probe_dir.path("probe"); - std::fs::write(&probe_file, &bytes)?; - if !matches!(ffmpeg::probe(&probe_file).await, Some((_, true))) { - bail_user!("I can work on pictures, GIFs, WebP and videos (MP4, WebM, MOV). That file is none of those."); - } - let mut out = (Vec::new(), "mp4"); - for (crf, side) in [(28, MAX_VIDEO_SIDE), (34, 320), (40, 220)] { - out = match bubble_video(&bytes, b, crf, side).await { - Ok(o) => o, - Err(e) => bail_user!("{}", escape(&truncate(&e, 200))), - }; - if out.0.len() <= limit { - break; - } - } - out - }; - if out.len() > limit { - bail_user!("The result is too big to upload ({} MB, the limit here is {} MB).", out.len() / 1024 / 1024, limit / 1024 / 1024); - } - let name = format!("speechbubble.{ext}"); - ctx.reply_file(Card::new(None).gallery(&[&format!("attachment://{name}")]).build(), &name, out).await -} - pub fn commands() -> Vec { + let fx_help = format!("Edit a picture or GIF: reply to one, attach one, or give a @user / link / emoji (default: your avatar). Effects: {}. Filters: {}. To change a file's format use `convert`.", EFFECTS.join(", "), FILTERS.join(", ")); + let fx_help: &'static str = Box::leak(fx_help.into_boxed_str()); vec![ - Command::new("caption", "fun", "Put a white band with your text above a picture, GIF, WebP or video (reply to one, attach one, give a link, or it uses the latest in the channel)", |c| caption_cmd(c).boxed()) - .usage("") - .opt(Opt::opt("rest", "Text, and optionally a link", OptKind::String).prefix_only()) - .opt(Opt::opt("text", "The caption text", OptKind::String).slash_only()) - .opt(Opt::opt("source-attachment", "A picture, GIF or video (default: the latest in this channel)", OptKind::Attachment).slash_only()) - .opt(Opt::opt("source-link", "…or a link to one", OptKind::String).slash_only()), - Command::new("speechbubble", "fun", "Cut a speech bubble out of the top of a picture, GIF, WebP or video (reply to one, attach one, give a link, or it uses the latest in the channel)", |c| speechbubble_cmd(c).boxed()) - .aliases(&["bubble"]) - .usage("[bottom] [flip] [solid] [link]") - .opt(Opt::opt("rest", "Optional link, and the words bottom, flip, solid", OptKind::String).prefix_only()) - .opt(Opt::opt("source-attachment", "A picture, GIF or video (default: the latest in this channel)", OptKind::Attachment).slash_only()) - .opt(Opt::opt("source-link", "…or a link to one", OptKind::String).slash_only()) - .opt(Opt::opt("position", "Which edge the bubble hangs from (default: top)", OptKind::String).choices(&["top", "bottom"]).slash_only()) - .opt(Opt::opt("flip", "Tail on the other side", OptKind::Bool).slash_only()) - .opt(Opt::opt("solid", "White bubble with a black outline instead of a see-through cut-out", OptKind::Bool).slash_only()), + Command::new("fx", "fun", fx_help, |c| image_cmd(c).boxed()) + .aliases(&["effect", "filter", "imagefx"]) + .slash_as("image") + .usage(" [text]") + .opt(Opt::opt("name", "Effect or filter", OptKind::String).prefix_only()) + .opt(Opt::opt("rest", "Text, a link, a @user…", OptKind::String).prefix_only()) + .opt(Opt::opt("image", "A picture or GIF to edit", OptKind::Attachment).slash_only()) + .opt(Opt::opt("user", "…or use someone's avatar", OptKind::User).slash_only()) + .opt(Opt::opt("url", "…or a link", OptKind::String).slash_only()) + .opt(Opt::opt("effect", "Speech bubble, caption, blur, deepfry…", OptKind::String).choices(&EFFECTS).slash_only()) + .opt(Opt::opt("filter", "Colour filter: sepia, gotham, cyberpunk…", OptKind::String).choices(&FILTERS).slash_only()) + .opt(Opt::opt("text", "Text for the caption effect", OptKind::String).slash_only()) + .opt(Opt::opt("bubble_position", "Where the speech bubble goes", OptKind::String).choices(&["top", "bottom"]).slash_only()) + .opt(Opt::opt("blur_radius", "Blur strength (1–20)", OptKind::Integer).range(1, 20).slash_only()) + .opt(Opt::opt("pixel_size", "Pixelate block size (2–50)", OptKind::Integer).range(2, 50).slash_only()) + .opt(Opt::opt("deepfry_level", "Deepfry strength (1–5)", OptKind::Integer).range(1, 5).slash_only()), Command::new("petpet", "fun", "Petpet GIF of someone's avatar or a custom emoji (reply to a message for its author)", |c| petpet(c).boxed()) .aliases(&["patpat", "pet"]) .usage("[@user | emoji]") @@ -610,108 +555,57 @@ pub fn commands() -> Vec { mod tests { use super::*; - #[test] - fn band_height_grows_with_lines_and_is_even() { - let one = caption_band(400, "hello"); - let three = caption_band(400, "one\ntwo\nthree"); - assert_eq!(one.width(), 400); - assert!(three.height() > one.height() * 2 - 40, "{} vs {}", three.height(), one.height()); - assert!(three.height() > one.height()); - assert_eq!(one.height() % 2, 0); - assert_eq!(three.height() % 2, 0); + fn sample() -> RgbaImage { + RgbaImage::from_fn(160, 120, |x, y| Rgba([(x * 255 / 160) as u8, (y * 255 / 120) as u8, 90, 255])) } #[test] - fn caption_keeps_picture_kind() { - let png = pix::encode_png(&RgbaImage::from_pixel(160, 120, Rgba([10, 20, 30, 255]))); - let (out, ext) = caption_image(&png, "hi", 480).unwrap(); - assert_eq!(ext, "png"); - assert!(image::load_from_memory(&out).unwrap().height() > 120); - let gif = squish_gif(&png).unwrap(); - let (out, ext) = caption_image(&gif, "hi", 480).unwrap(); - assert_eq!(ext, "gif"); - assert!(frames_of(&out).is_some_and(|f| f.len() == 10)); - assert!(caption_image(b"not an image", "hi", 480).is_none()); - } - - #[test] - fn bubble_tail_flips_and_touches_chosen_edge() { - let (w, h) = (200u32, 100u32); - // mean x of the tail pixels (below the ellipse's lowest row, 0.2 * h = 20) - let tail_x = |bottom: bool, flip: bool| { - let m = bubble_mask(w, h, bottom, flip); - let (mut sum, mut n) = (0u32, 0u32); - for y in 0..h { - let dist = if bottom { h - 1 - y } else { y }; - for x in 0..w { - if dist > 22 && m[(y * w + x) as usize] { - sum += x; - n += 1; - } - } - } - assert!(n > 0); - sum / n - }; - assert!(tail_x(false, false) > w / 2); - assert!(tail_x(false, true) < w / 2); - assert!(tail_x(true, false) > w / 2); - let top = bubble_mask(w, h, false, false); - assert!((0..w).any(|x| top[x as usize]) && !(0..w).any(|x| top[((h - 1) * w + x) as usize])); - let bot = bubble_mask(w, h, true, false); - assert!((0..w).any(|x| bot[((h - 1) * w + x) as usize]) && !(0..w).any(|x| bot[x as usize])); - } - - #[test] - fn bubble_cuts_transparent_or_paints_solid() { - let base = RgbaImage::from_pixel(200, 100, Rgba([10, 20, 30, 255])); - let mut cut = base.clone(); - draw_bubble(&mut cut, Bubble { bottom: false, flip: false, solid: false }); - assert_eq!(cut.get_pixel(100, 0)[3], 0); - assert_eq!(cut.get_pixel(100, 99)[3], 255); - let mut solid = base; - draw_bubble(&mut solid, Bubble { bottom: false, flip: false, solid: true }); - assert_eq!(solid.get_pixel(100, 5), &Rgba([255, 255, 255, 255])); - assert!((0..100).any(|y| solid.get_pixel(100, y) == &Rgba([0, 0, 0, 255]))); - } - - #[test] - fn a_huge_declared_picture_is_refused_fast() { - // check 7: PNG header only, claims 60 000 x 60 000 - let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, b'I', b'H', b'D', b'R']; - png.extend_from_slice(&60_000u32.to_be_bytes()); - png.extend_from_slice(&60_000u32.to_be_bytes()); - png.extend_from_slice(&[8, 6, 0, 0, 0, 0, 0, 0, 0]); - let t = std::time::Instant::now(); - assert!(pix::decode(&png).is_none()); - assert!(t.elapsed() < Duration::from_secs(2)); - } - - #[test] - fn a_big_canvas_gif_is_cut_to_the_frame_cap() { - // check 8: 4000 x 4000 screen, 120 one-pixel frames - assert_eq!(frame_cap((4000, 4000)), 4); - let mut out = Vec::new(); - { - let mut enc = gif::Encoder::new(&mut out, 4000, 4000, &[0, 0, 0, 255, 255, 255]).unwrap(); - for _ in 0..120 { - let mut f = gif::Frame::default(); - f.width = 1; - f.height = 1; - f.buffer = std::borrow::Cow::Owned(vec![1]); - enc.write_frame(&f).unwrap(); + fn every_filter_and_effect_runs() { + let opts = Opts { text: "when the code works 🧼".into(), ..Opts::default() }; + for name in FILTERS { + let mut img = sample(); + apply_filter(&mut img, name); + assert_eq!(img.dimensions(), (160, 120), "{name}"); + } + for name in EFFECTS { + let out = apply_effect(sample(), name, &opts); + assert!(out.width() >= 160 && out.height() >= 120, "{name}"); + if std::env::var("DEZIO_DUMP").is_ok() { + out.save(format!("/tmp/dezio_fx_{name}.png")).unwrap(); } } - let frames = frames_of(&out).expect("frames"); - assert!(frames.len() <= 4, "{}", frames.len()); + assert!(apply_effect(sample(), "caption", &opts).height() > 120); + assert_eq!(apply_effect(sample(), "border", &opts).width(), 160 + 2 * 6); } - #[tokio::test] - async fn playlists_never_reach_ffmpeg_in_frame_cutting() { - // check 6 - let scratch = ffmpeg::Scratch::new().unwrap(); - let err = map_frames(&scratch, b"#EXTM3U\n#EXTINF:1,\nfile:///etc/passwd\n", 480, |f| f.clone()).await.unwrap_err(); - assert!(err.starts_with("Playlists and stream lists"), "{err}"); + #[test] + fn names_and_aliases_resolve() { + assert_eq!(resolve_name("Pencil-Sketch").1, Some("pencil_sketch")); + assert_eq!(resolve_name("bw").1, Some("grayscale")); + assert_eq!(resolve_name("fry").0, Some("deepfry")); + assert_eq!(resolve_name("nonsense"), (None, None)); } + #[test] + fn pictures_and_gifs_keep_their_kind() { + let png = pix::encode_png(&sample()); + let (out, ext) = process(&png, Some("mirror"), Some("sepia"), &Opts::default(), 480).unwrap(); + assert_eq!(ext, "png"); + assert!(image::load_from_memory(&out).is_ok()); + let gif = squish_gif(&png).unwrap(); + let (out, ext) = process(&gif, Some("blur"), None, &Opts::default(), 480).unwrap(); + assert_eq!(ext, "gif"); + assert!(frames_of(&out).is_some_and(|f| f.len() == 10)); + assert!(process(b"not an image", None, Some("sepia"), &Opts::default(), 480).is_none()); + } + + #[test] + fn sepia_and_invert_math() { + let mut img = RgbaImage::from_pixel(2, 2, Rgba([100, 150, 200, 255])); + apply_filter(&mut img, "invert"); + assert_eq!(img.get_pixel(0, 0).0, [155, 105, 55, 255]); + let mut img = RgbaImage::from_pixel(1, 1, Rgba([255, 255, 255, 255])); + apply_filter(&mut img, "sepia"); + assert_eq!(img.get_pixel(0, 0).0, [255, 255, 239, 255]); + } } diff --git a/src/commands/media/mod.rs b/src/commands/media/mod.rs index 521d464..5ecef79 100644 --- a/src/commands/media/mod.rs +++ b/src/commands/media/mod.rs @@ -1,4 +1,4 @@ -//! Pictures: quotes, captions and conversion, emoji tools, downloads. +//! Pictures: quotes, image effects and conversion, emoji tools, downloads. use crate::bail_user; use crate::cmd::{Command, Ctx}; use crate::state::State; @@ -33,91 +33,13 @@ pub fn safe_url(text: &str) -> Option { match url.host()? { url::Host::Domain(d) => { let d = d.to_lowercase(); - let local = [".localhost", ".local", ".internal", ".lan", ".home.arpa", ".localdomain"]; - (d != "localhost" && !local.iter().any(|end| d.ends_with(end))).then_some(url) + (d != "localhost" && !d.ends_with(".localhost") && !d.ends_with(".local") && !d.ends_with(".internal")).then_some(url) } - url::Host::Ipv4(ip) => is_public_ip(ip.into()).then_some(url), - url::Host::Ipv6(ip) => is_public_ip(ip.into()).then_some(url), + url::Host::Ipv4(ip) => (!(ip.is_private() || ip.is_loopback() || ip.is_link_local() || ip.is_unspecified() || ip.is_broadcast())).then_some(url), + url::Host::Ipv6(ip) => (!(ip.is_loopback() || ip.is_unspecified() || (ip.segments()[0] & 0xfe00) == 0xfc00 || (ip.segments()[0] & 0xffc0) == 0xfe80)).then_some(url), } } -/// Addresses a link may reach: the public internet only. Refused: loopback, LAN, link-local, Tailscale/CGNAT -/// (100.64.0.0/10, fd7a:… is inside fc00::/7), multicast and reserved ranges. IPv4 carried inside IPv6 (mapped, -/// compatible or NAT64) is checked as the IPv4 address. -pub fn is_public_ip(ip: std::net::IpAddr) -> bool { - use std::net::{IpAddr, Ipv4Addr}; - match ip { - IpAddr::V4(v4) => { - let [a, b, c, _] = v4.octets(); - !(v4.is_private() || v4.is_loopback() || v4.is_link_local() || v4.is_unspecified() || v4.is_broadcast() || v4.is_multicast() - || a == 0 - || a >= 240 - || (a == 100 && (64..128).contains(&b)) - || (a == 198 && (b == 18 || b == 19)) - || (a == 192 && b == 0 && c == 0)) - } - IpAddr::V6(v6) => { - let s = v6.segments(); - if let Some(v4) = v6.to_ipv4() { - return is_public_ip(IpAddr::V4(v4)); - } - if s[0] == 0x64 && s[1] == 0xff9b && s[2..6] == [0, 0, 0, 0] { - return is_public_ip(IpAddr::V4(Ipv4Addr::from(((s[6] as u32) << 16) | s[7] as u32))); - } - !(v6.is_loopback() || v6.is_unspecified() || v6.is_multicast() || (s[0] & 0xfe00) == 0xfc00 || (s[0] & 0xffc0) == 0xfe80 || (s[0] & 0xffc0) == 0xfec0) - } - } -} - -/// DNS for the shared web client: private answers are dropped, so a public name that points (or re-points, DNS -/// rebinding) at the home network can't be reached. It runs at connect time, so redirects are covered too. -pub struct PublicDns; - -impl reqwest::dns::Resolve for PublicDns { - fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { - let host = name.as_str().to_string(); - Box::pin(async move { - let addrs: Vec = tokio::net::lookup_host((host.as_str(), 0)).await?.filter(|a| is_public_ip(a.ip())).collect(); - if addrs.is_empty() { - return Err(format!("{host} has no public address").into()); - } - let addrs: reqwest::dns::Addrs = Box::new(addrs.into_iter()); - Ok(addrs) - }) - } -} - -/// Playlists and stream lists (HLS, DASH, ffconcat, PLS) make ffmpeg open more addresses or files named inside them, -/// which we can't check. Media we work on must be the media itself. -pub fn is_playlist(head: &[u8]) -> bool { - let text = String::from_utf8_lossy(&head[..head.len().min(512)]).trim_start_matches('\u{feff}').trim_start().to_lowercase(); - ["#extm3u", "#ext-x-", "ffconcat", " &'static std::sync::Mutex> { - static BUSY: std::sync::OnceLock>> = std::sync::OnceLock::new(); - BUSY.get_or_init(Default::default) -} - -impl Drop for Busy { - fn drop(&mut self) { - busy_users().lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0); - } -} - -/// Claim this person's media slot until the returned guard is dropped. -pub fn one_job(ctx: &Ctx) -> Result { - let user = ctx.user_id.get(); - if !busy_users().lock().unwrap_or_else(|e| e.into_inner()).insert(user) { - bail_user!("⏳ You already have a media job running. Wait for it to finish."); - } - Ok(Busy(user)) -} - /// Download at most `max` bytes (None if it's not reachable, not OK, or bigger). /// Links are checked before they're fetched; this checks every address they redirect to as well, so a link can't /// bounce the bot onto the home network. @@ -204,32 +126,17 @@ pub fn emoji_url(id: u64, animated: bool, size: u32) -> String { format!("https://cdn.discordapp.com/emojis/{id}.{}?size={size}", if animated { "gif" } else { "png" }) } -/// Upload limit for files in this server: Discord's real bot limit, 10 MiB by default, more with boosts. +/// Upload limit for files in this server: Discord's default is 20 MiB since September 2026, more with boosts. pub fn upload_limit(ctx: &Ctx) -> usize { let tier = ctx.guild_id.and_then(|g| ctx.state.cache.guild(g).map(|g| u8::from(g.premium_tier()))).unwrap_or(0); let mb: usize = match tier { 2 => 50, 3 => 100, - _ => 10, + _ => 20, }; mb * 1024 * 1024 } -/// How long one upload may take. Under the 180 s Discord client timeout, with room for voice traffic. -pub const UPLOAD_SECONDS: usize = 75; -/// Upload speed of the server's line: measured 114 KB/s on 2026-11-12 (CLAUDE.md section 2). -pub const UPLOAD_BYTES_PER_SEC: usize = 114_000; - -/// Pure budget math: the smaller of Discord's limit and what the line can send in [`UPLOAD_SECONDS`]. -pub fn budget_for(discord_limit: usize) -> usize { - discord_limit.min(UPLOAD_SECONDS * UPLOAD_BYTES_PER_SEC) -} - -/// Bytes one upload may have in this server. Bigger results go to the website as a link. -pub fn upload_budget(ctx: &Ctx) -> usize { - budget_for(upload_limit(ctx)) -} - #[allow(dead_code)] pub fn need(value: Option, text: &str) -> Result { match value { @@ -242,13 +149,6 @@ pub fn need(value: Option, text: &str) -> Result { mod tests { use super::*; - #[test] - fn budget_is_the_smaller_of_limit_and_line() { - assert_eq!(budget_for(10 * 1024 * 1024), UPLOAD_SECONDS * UPLOAD_BYTES_PER_SEC); - assert_eq!(budget_for(1000), 1000); - assert!(budget_for(100 * 1024 * 1024) <= 10 * 1024 * 1024); - } - #[test] fn private_addresses_are_refused() { assert!(safe_url("https://example.com/a.png").is_some()); @@ -257,20 +157,6 @@ mod tests { assert!(safe_url("http://192.168.1.71:3000/").is_none()); assert!(safe_url("http://[::1]/").is_none()); assert!(safe_url("file:///etc/passwd").is_none()); - assert!(safe_url("http://100.101.102.103/").is_none()); - assert!(safe_url("http://[::ffff:127.0.0.1]/").is_none()); - assert!(safe_url("http://2130706433/").is_none()); - assert!(safe_url("http://printer.lan/").is_none()); - assert!(safe_url("http://[64:ff9b::c0a8:147]/").is_none()); - assert!(is_public_ip("1.1.1.1".parse().unwrap()) && is_public_ip("2606:4700::1111".parse().unwrap())); - } - - #[test] - fn playlists_are_spotted() { - assert!(is_playlist(b"#EXTM3U\n#EXTINF:1,\nfile:///etc/passwd\n")); - assert!(is_playlist(b"\xef\xbb\xbf ffconcat version 1.0")); - assert!(is_playlist(b"")); - assert!(!is_playlist(b"\x89PNG\r\n\x1a\n") && !is_playlist(b"\x00\x00\x00\x18ftypmp42")); } #[test] @@ -300,40 +186,3 @@ mod redirect_tests { assert_eq!(answer.status(), 302, "stopped at the redirect instead of following it"); } } - -#[cfg(test)] -mod dns_tests { - use super::PublicDns; - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - - async fn listener() -> (u16, std::sync::Arc, tokio::net::TcpListener) { - let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - (l.local_addr().unwrap().port(), Default::default(), l) - } - - /// Checks 2 and 3: names that resolve to loopback are never connected, directly or through a redirect. - #[tokio::test] - async fn names_that_resolve_to_this_machine_are_not_reached() { - let client = reqwest::Client::builder().dns_resolver(PublicDns).timeout(std::time::Duration::from_secs(5)).build().unwrap(); - let (port_b, hit_b, lb) = listener().await; - let h = hit_b.clone(); - tokio::spawn(async move { - if lb.accept().await.is_ok() { - h.store(true, std::sync::atomic::Ordering::SeqCst); - } - }); - assert!(client.get(format!("http://localhost:{port_b}/")).send().await.is_err(), "localhost must fail"); - // redirect from an allowed (IP literal, no DNS) listener A to a name for B - let (port_a, _, la) = listener().await; - tokio::spawn(async move { - let (mut s, _) = la.accept().await.unwrap(); - let mut b = [0u8; 512]; - let _ = s.read(&mut b).await; - let _ = s.write_all(format!("HTTP/1.1 302 Found\r\nLocation: http://localhost:{port_b}/\r\nContent-Length: 0\r\n\r\n").as_bytes()).await; - }); - let r = client.get(format!("http://127.0.0.1:{port_a}/")).send().await; - assert!(r.map(|r| r.status() != 200).unwrap_or(true)); - tokio::time::sleep(std::time::Duration::from_millis(300)).await; - assert!(!hit_b.load(std::sync::atomic::Ordering::SeqCst), "listener B got a connection"); - } -} diff --git a/src/commands/music/mod.rs b/src/commands/music/mod.rs index 98d47a8..e7709d0 100644 --- a/src/commands/music/mod.rs +++ b/src/commands/music/mod.rs @@ -51,10 +51,6 @@ const SLOW_UPLOAD: f64 = 12.0; /// How long a new picture takes to reach people, until a real one has been measured. const FIRST_LEAD: f64 = 3.0; /// A playing song whose position hasn't moved for this long has lost its voice connection. -/// After the voice driver reports a disconnect, wait this long for songbird's own retries before stepping in. -const VOICE_GRACE: Duration = Duration::from_secs(20); -/// Rejoin attempts after the grace, then leave and tell the channel (3 x 15 s join limit is under a minute). -const VOICE_REJOIN_TRIES: u32 = 3; const STALL_LIMIT: Duration = Duration::from_secs(45); /// Songs longer than this aren't measured: the analysis reads the whole file. Their bars move at a steady level. const WAVEFORM_LIMIT: u64 = 30 * 60; @@ -292,12 +288,10 @@ async fn connect(state: &Arc, p: &Arc, channel: Id for attempt in 0..2 { if attempt > 0 { let _ = sb.remove(p.guild).await; - watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&p.guild.get()); tokio::time::sleep(Duration::from_millis(1500)).await; } match tokio::time::timeout(Duration::from_secs(15), sb.join(p.guild, channel)).await { Ok(Ok(call)) => { - watch_voice(state, p.guild, channel, &call).await; let _ = call.lock().await.deafen(true).await; become_speaker(state, p.guild, channel).await; return Ok(call); @@ -310,69 +304,9 @@ async fn connect(state: &Arc, p: &Arc, channel: Id // Discord's answer can still arrive after we gave up. Forget the call, or the next /play would see a half-made // connection, believe it, and play into nothing. let _ = sb.remove(p.guild).await; - watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&p.guild.get()); Err(format!("Couldn't connect to <#{channel}> ({last}). Try again in a moment.")) } -/// Guilds whose call already has the disconnect watcher (a call is created once per join, handlers live as long as it). -fn watched() -> &'static Mutex> { - static W: OnceLock>> = OnceLock::new(); - W.get_or_init(Default::default) -} - -struct VoiceWatcher { - state: Arc, - guild: Guild, - channel: Id, -} - -#[async_trait::async_trait] -impl EventHandler for VoiceWatcher { - async fn act(&self, ctx: &EventContext<'_>) -> Option { - if let EventContext::DriverDisconnect(d) = ctx { - tracing::warn!("voice driver disconnect in {}: {:?} {:?}", self.guild, d.kind, d.reason); - let (state, guild, channel) = (self.state.clone(), self.guild, self.channel); - tokio::spawn(async move { recover_voice(&state, guild, channel).await }); - } - None - } -} - -async fn watch_voice(state: &Arc, guild: Guild, channel: Id, call: &Arc>) { - if watched().lock().unwrap_or_else(|e| e.into_inner()).insert(guild.get()) { - call.lock().await.add_global_event(Event::Core(songbird::CoreEvent::DriverDisconnect), VoiceWatcher { state: state.clone(), guild, channel }); - } -} - -/// The voice driver lost its connection. Songbird retries by itself; if it is still down after [`VOICE_GRACE`], rejoin -/// [`VOICE_REJOIN_TRIES`] times, then leave and say so, so no queue or panel stays stuck on a dead connection. -async fn recover_voice(state: &Arc, guild: Guild, channel: Id) { - tokio::time::sleep(VOICE_GRACE).await; - let Some(sb) = voice(state) else { return }; - for attempt in 1..=VOICE_REJOIN_TRIES { - let Some(p) = existing(guild) else { return }; // kicked or stopped meanwhile: nothing to save - let Some(call) = sb.get(guild) else { return }; - let (connected, now_channel) = { - let c = call.lock().await; - (c.current_connection().is_some(), c.current_channel().map(|c| Id::new(c.0.get()))) - }; - if connected { - return; - } - let target = now_channel.unwrap_or(channel); - tracing::warn!("voice rejoin {attempt}/{VOICE_REJOIN_TRIES} in {guild} to {target}"); - if let Ok(Ok(_)) = tokio::time::timeout(Duration::from_secs(15), sb.join(guild, target)).await { - let _ = p; - return; - } - tokio::time::sleep(VOICE_GRACE).await; - } - if existing(guild).is_some() { - teardown(state, guild, true, Some("⚠️ Lost the voice connection and couldn't get it back, so I left. Use `/play` to start again.")).await; - } - watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&guild.get()); -} - /// On a stage, step up to speak (or ask to, without the permission). async fn become_speaker(state: &State, guild: Guild, channel: Id) { use twilight_model::channel::ChannelType; @@ -561,7 +495,6 @@ async fn teardown(state: &Arc, guild: Guild, disconnect: bool, notice: Op if let Some(sb) = voice(state) { let _ = sb.remove(guild).await; } - watched().lock().unwrap_or_else(|e| e.into_inner()).remove(&guild.get()); } } diff --git a/src/commands/music/source.rs b/src/commands/music/source.rs index 8b672fb..4e323b8 100644 --- a/src/commands/music/source.rs +++ b/src/commands/music/source.rs @@ -171,13 +171,6 @@ impl Drop for BufferedPipe { /// What ffmpeg may open for a song: the web, never a local file a crafted page or playlist points it at. const WEB_ONLY: &str = "http,https,tcp,tls,crypto"; -/// A song stream may run for hours, so it has no total limit; it is cut when the server sends no data for this long -/// (ffmpeg `-rw_timeout`, in microseconds). 20 s: longer than the 5 s reconnect delay, shorter than a listener's patience. -const STREAM_IDLE_MICROS: &str = "20000000"; - -/// The loudness pass must see data this often, or it gives up (it reads at 10x speed, so a stall means a dead link). -const PEAKS_IDLE: std::time::Duration = std::time::Duration::from_secs(30); - /// Start ffmpeg on a stream (optionally from `start` seconds in) and give back the voice input and its position. pub fn spawn(stream: &Stream, start: f64) -> Result<(Input, Position), String> { let (pipe, position) = spawn_pipe(stream, start)?; @@ -188,7 +181,7 @@ pub fn spawn(stream: &Stream, start: f64) -> Result<(Input, Position), String> { pub fn spawn_pipe(stream: &Stream, start: f64) -> Result<(BufferedPipe, Position), String> { let mut cmd = Command::new(crate::commands::media::download::tool("ffmpeg")); cmd.args(["-nostdin", "-loglevel", "error", "-reconnect", "1", "-reconnect_streamed", "1", "-reconnect_on_network_error", "1", "-reconnect_on_http_error", "4xx,5xx", "-reconnect_delay_max", "5"]); - cmd.args(["-protocol_whitelist", WEB_ONLY, "-rw_timeout", STREAM_IDLE_MICROS]); + cmd.args(["-protocol_whitelist", WEB_ONLY]); if start > 0.0 { cmd.args(["-ss", &format!("{start:.2}")]); } @@ -217,7 +210,7 @@ pub async fn peaks(stream: &Stream, per_second: usize) -> Option> { const RATE: usize = 2000; let mut cmd = tokio::process::Command::new(crate::commands::media::download::tool("ffmpeg")); // reading at ten times playing speed leaves the slow home line to the song itself - cmd.args(["-nostdin", "-loglevel", "error", "-protocol_whitelist", WEB_ONLY, "-rw_timeout", STREAM_IDLE_MICROS, "-readrate", "10"]); + cmd.args(["-nostdin", "-loglevel", "error", "-protocol_whitelist", WEB_ONLY, "-readrate", "10"]); if !stream.headers.is_empty() { cmd.arg("-headers").arg(stream.headers.iter().map(|(k, v)| format!("{k}: {v}\r\n")).collect::()); } @@ -228,7 +221,7 @@ pub async fn peaks(stream: &Stream, per_second: usize) -> Option> { let mut sums: Vec<(f64, u64)> = Vec::new(); let (mut buf, mut index, mut odd) = (vec![0u8; 16 * 1024], 0usize, None::); loop { - let n = tokio::time::timeout(PEAKS_IDLE, out.read(&mut buf)).await.ok()?.ok()?; + let n = out.read(&mut buf).await.ok()?; if n == 0 { break; } diff --git a/src/commands/music/ytdl.rs b/src/commands/music/ytdl.rs index 831d539..86dcd44 100644 --- a/src/commands/music/ytdl.rs +++ b/src/commands/music/ytdl.rs @@ -184,7 +184,7 @@ pub async fn extract(query: &str, mode: Mode) -> Result { } }; cmd.arg("--").arg(query).stdin(Stdio::null()).kill_on_drop(true); - let out = tokio::time::timeout(Duration::from_secs(limit), cmd.output()).await.map_err(|_| "The song lookup took too long (YouTube or the connection is slow). Try again in a bit.".to_string())?.map_err(|e| format!("yt-dlp can't start ({e})"))?; + let out = tokio::time::timeout(Duration::from_secs(limit), cmd.output()).await.map_err(|_| "That took too long — try again.".to_string())?.map_err(|e| format!("yt-dlp can't start ({e})"))?; if !out.status.success() { return Err(clean_error(&String::from_utf8_lossy(&out.stderr))); } diff --git a/src/commands/tools/virus.rs b/src/commands/tools/virus.rs index 0bd2715..b09630c 100644 --- a/src/commands/tools/virus.rs +++ b/src/commands/tools/virus.rs @@ -70,7 +70,7 @@ async fn wait(state: &State, key: &str, analysis: &str, after: &str) -> Result Result { diff --git a/src/main.rs b/src/main.rs index b75ef7f..b1a89bd 100644 --- a/src/main.rs +++ b/src/main.rs @@ -38,13 +38,6 @@ use std::sync::Arc; use std::time::Duration; use twilight_gateway::{create_recommended, Config, EventTypeFlags, Intents, StreamExt as _}; use twilight_http::Client; - -/// Gateway reconnects that keep failing this long mean the line is dead or the shard is wedged; exit and let systemd -/// (Restart=always) start fresh. Twilight's own backoff covers short drops; the 2026-11 logs show drops of seconds. -const GATEWAY_DOWN_LIMIT: Duration = Duration::from_secs(10 * 60); -/// How often songbird retries a failed voice connection before it gives up (its default is 5; the music code then -/// rejoins a few times and finally leaves, see `VOICE_REJOIN_TRIES`). -const VOICE_DRIVER_RETRIES: u8 = 8; use twilight_model::application::command::{Command as ApiCommand, CommandOptionChoice, CommandOptionChoiceValue, CommandType}; use twilight_model::application::interaction::{InteractionContextType, InteractionData, InteractionType}; use twilight_model::application::interaction::application_command::CommandOptionValue; @@ -569,27 +562,16 @@ async fn main() -> Result<()> { let shards: Vec<_> = create_recommended(&http, config, |_, b| b.build()).await?.collect(); let _ = state.senders.set(shards.iter().map(|s| s.sender()).collect()); let senders = shards.iter().map(|s| (s.id().number(), s.sender())).collect(); - let _ = state.voice.set(Arc::new(songbird::Songbird::twilight_from_config(Arc::new(songbird::shards::TwilightMap::new(senders)), state.bot_id(), songbird::Config::default().driver_retry(songbird::driver::retry::Retry { retry_limit: std::num::NonZeroU8::new(VOICE_DRIVER_RETRIES), ..Default::default() })))); + let _ = state.voice.set(Arc::new(songbird::Songbird::twilight(Arc::new(songbird::shards::TwilightMap::new(senders)), state.bot_id()))); let mut tasks = Vec::new(); for mut shard in shards { let state = state.clone(); tasks.push(tokio::spawn(async move { - // When the first failed reconnect happened; cleared by the next good event. - let mut down_since: Option = None; while let Some(item) = shard.next_event(EventTypeFlags::all()).await { let event = match item { - Ok(e) => { - down_since = None; - e - } + Ok(e) => e, Err(e) => { tracing::warn!("gateway: {e}"); - // twilight retries by itself with backoff; if the line stays dead too long, restart clean - let since = *down_since.get_or_insert_with(std::time::Instant::now); - if matches!(e.kind(), twilight_gateway::error::ReceiveMessageErrorType::Reconnect) && since.elapsed() > GATEWAY_DOWN_LIMIT { - tracing::error!("gateway: down for {:?}, exiting so systemd restarts the bot", since.elapsed()); - std::process::exit(1); - } continue; } }; @@ -729,12 +711,7 @@ async fn main() -> Result<()> { } else { tokio::select! { _ = tokio::signal::ctrl_c() => tracing::info!("shutting down"), - _ = futures::future::join_all(tasks) => { - // a shard loop only ends on a fatal close (bad token, bad intents): say so and fail, systemd restarts us - tracing::error!("gateway: every shard stopped, exiting"); - storage::flush_all(); - std::process::exit(1); - } + _ = futures::future::join_all(tasks) => {} } } storage::flush_all(); diff --git a/src/pix.rs b/src/pix.rs index 4fec70a..ad4ff49 100644 --- a/src/pix.rs +++ b/src/pix.rs @@ -2,25 +2,8 @@ use image::imageops::{self, FilterType}; use image::{GrayImage, Luma, Rgba, RgbaImage}; -/// Longest picture side we decode. Bigger ones are refused before any pixels are read (decode bombs). -pub const MAX_DECODE_SIDE: u32 = 10_000; -/// Most memory one decode may allocate (an 8000 px square RGBA is 256 MB). Below the crate's 512 MB default -/// because the server is a Chromebook. -pub const MAX_DECODE_BYTES: u64 = 256 * 1024 * 1024; - -/// Decode limits for pictures that come from users or the web. -pub fn limits() -> image::Limits { - let mut l = image::Limits::default(); - l.max_image_width = Some(MAX_DECODE_SIDE); - l.max_image_height = Some(MAX_DECODE_SIDE); - l.max_alloc = Some(MAX_DECODE_BYTES); - l -} - pub fn decode(bytes: &[u8]) -> Option { - let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; - reader.limits(limits()); - reader.decode().ok().map(|d| d.to_rgba8()) + image::load_from_memory(bytes).ok().map(|d| d.to_rgba8()) } pub fn encode_png(img: &RgbaImage) -> Vec { diff --git a/src/state.rs b/src/state.rs index d4f2c12..7360492 100644 --- a/src/state.rs +++ b/src/state.rs @@ -47,7 +47,7 @@ impl State { pub fn new(http: Arc, registry: Registry, token: String) -> Self { Self { http, - web: reqwest::Client::builder().user_agent("Dezio").timeout(std::time::Duration::from_secs(20)).redirect(crate::commands::media::safe_redirects()).dns_resolver(crate::commands::media::PublicDns).build().expect("http client"), + web: reqwest::Client::builder().user_agent("Dezio").timeout(std::time::Duration::from_secs(20)).redirect(crate::commands::media::safe_redirects()).build().expect("http client"), token, registry, prefixes: JsonStore::open(paths::data(&["prefixes.json"])), diff --git a/src/web/activity.rs b/src/web/activity.rs index 220ba74..b5be20b 100644 --- a/src/web/activity.rs +++ b/src/web/activity.rs @@ -1,4 +1,4 @@ -//! The Game Boy Discord Activity's web side, served by the dashboard's web server under /activity (below the DASHBOARD_URL path, /dezio). +//! The Game Boy Discord Activity's web side, served by the dashboard's web server under /activity. //! //! The emulator itself (binjgb, WebAssembly) runs in each player's Discord client, so the bot only hands out the page, //! the ROMs (once — the client keeps them in IndexedDB) and the saves. @@ -16,7 +16,7 @@ //! GET /activity/api/art/ the game's cover (public): an image next to the ROM wins, else SteamGridDB //! (STEAMGRIDDB_API_KEY), cached in data/gameboy/art //! -//! Developer Portal setup (once): Activities → Settings → enable; Activities → URL Mappings → `/` → `/activity` (e.g. astar76.com/dezio/activity) +//! Developer Portal setup (once): Activities → Settings → enable; Activities → URL Mappings → `/` → `/activity` //! (no https://); OAuth2 → Redirects needs at least one entry (the dashboard's /callback is there already). //! DEZIO_ACTIVITY_DEV=1 adds POST /activity/api/dev-session, a test sign-in for requests from 127.0.0.1. //! Everything else under /api needs the session from /api/token (`Authorization: Bearer …`). @@ -340,24 +340,20 @@ async fn page() -> Response { ([(header::CONTENT_TYPE, "text/html; charset=utf-8"), (header::CACHE_CONTROL, "no-cache")], page_html()).into_response() } -async fn slash_redirect(AxState(w): AxState, uri: axum::http::Uri) -> Redirect { - Redirect::to(&format!("{}/activity/{}", w.cfg.base, uri.query().map(|q| format!("?{q}")).unwrap_or_default())) +async fn slash_redirect(uri: axum::http::Uri) -> Redirect { + Redirect::to(&format!("/activity/{}", uri.query().map(|q| format!("?{q}")).unwrap_or_default())) } -/// Dev sessions only for a browser on this machine. Behind `tailscale serve` every request comes from 127.0.0.1 too, -/// so a forwarded request (X-Forwarded-For) or a non-local Host never counts, even if DEZIO_ACTIVITY_DEV is left on. -fn dev_mode(addr: &SocketAddr, headers: &HeaderMap) -> bool { - let host = headers.get(header::HOST).and_then(|v| v.to_str().ok()).unwrap_or(""); - let local_host = ["127.0.0.1", "localhost", "[::1]"].iter().any(|h| host == *h || host.starts_with(&format!("{h}:"))); - std::env::var("DEZIO_ACTIVITY_DEV").as_deref() == Ok("1") && addr.ip().is_loopback() && local_host && !headers.contains_key("x-forwarded-for") +fn dev_mode(addr: &SocketAddr) -> bool { + std::env::var("DEZIO_ACTIVITY_DEV").as_deref() == Ok("1") && addr.ip().is_loopback() } -async fn config(AxState(w): AxState, ConnectInfo(addr): ConnectInfo, headers: HeaderMap) -> Response { - ([(header::CACHE_CONTROL, "no-store")], Json(json!({"client_id": w.state.app_id().to_string(), "dev": dev_mode(&addr, &headers)}))).into_response() +async fn config(AxState(w): AxState, ConnectInfo(addr): ConnectInfo) -> Response { + ([(header::CACHE_CONTROL, "no-store")], Json(json!({"client_id": w.state.app_id().to_string(), "dev": dev_mode(&addr)}))).into_response() } -async fn dev_session(AxState(w): AxState, ConnectInfo(addr): ConnectInfo, headers: HeaderMap) -> Result, ApiError> { - if !dev_mode(&addr, &headers) { +async fn dev_session(AxState(w): AxState, ConnectInfo(addr): ConnectInfo) -> Result, ApiError> { + if !dev_mode(&addr) { return Err(ApiError::new(404, "Not found")); } Ok(Json(json!({"session": w.activity.new_session(1, "Tester"), "user": {"id": "1", "name": "Tester"}}))) @@ -370,7 +366,7 @@ async fn web_session(AxState(w): AxState, headers: HeaderMap) -> Respons if origin != w.cfg.origin && origin != format!("{}://{host}", if w.cfg.secure { "https" } else { "http" }) { return ApiError::new(403, "Cross-site request refused").into_response(); } - let Some(s) = w.session(&headers) else { return (StatusCode::UNAUTHORIZED, Json(json!({"error": "Sign in with Discord first", "login": format!("{}/login?next=/activity/", w.cfg.base)}))).into_response() }; + let Some(s) = w.session(&headers) else { return (StatusCode::UNAUTHORIZED, Json(json!({"error": "Sign in with Discord first", "login": "/login?next=/activity/"}))).into_response() }; Json(json!({"session": w.activity.new_session(s.user_id, &s.name), "user": {"id": s.user_id.to_string(), "name": s.name}})).into_response() } @@ -379,9 +375,6 @@ async fn token(AxState(w): AxState, Json(v): Json) -> Result = async { web.post(format!("{}/oauth2/token", super::DISCORD)).form(&[("client_id", app.as_str()), ("client_secret", w.cfg.client_secret.as_str()), ("grant_type", "authorization_code"), ("code", code)]).send().await.ok()?.json().await.ok() }.await; @@ -509,7 +502,7 @@ pub fn routes() -> Router { .route("/activity/api/legacy/{id}", get(legacy)) .route("/activity/api/save/{id}", get(save_get).merge(put(save_put).layer(big.clone()))) .route("/activity/api/state/{id}/{slot}", get(state_get).merge(put(state_put).layer(big)).delete(state_delete)) - .nest_service("/activity/static", ServeDir::new(paths::web(&["activity", "static"])).append_index_html_on_directories(false)) + .nest_service("/activity/static", ServeDir::new(paths::web(&["activity", "static"]))) } #[allow(dead_code)] diff --git a/src/web/mod.rs b/src/web/mod.rs index 3f116e3..dc8603d 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -1,7 +1,5 @@ //! The web dashboard: Dezio's website plus per-user and per-server settings, served by the bot itself. //! -//! Everything below lives under the path of DASHBOARD_URL (https://astar76.com/dezio → /dezio; D-013). -//! Un-prefixed paths work too. HTML pages get that path in place of `__BASE__`. //! / the website (web/site/: index, terms, privacy, assets/, images/) //! /dashboard the settings app (web/dashboard/), which talks to /api/… //! /login → Discord → /callback sign in with Discord (OAuth2, "identify" only) @@ -10,7 +8,7 @@ //! Settings in .env: //! DASHBOARD_CLIENT_SECRET the app's OAuth2 client secret (Developer Portal → OAuth2) — sign-in is off without it //! DASHBOARD_URL the address people open, default http://192.168.1.71:8080; -//! add DASHBOARD_URL + "/callback" (…/dezio/callback) under OAuth2 → Redirects in the Developer Portal +//! add DASHBOARD_URL + "/callback" under OAuth2 → Redirects in the Developer Portal //! DASHBOARD_HOST / _PORT where to listen (default 0.0.0.0 and the port from DASHBOARD_URL) //! //! Security: sessions are random server-side tokens in an HttpOnly, SameSite=Lax cookie; every change needs the @@ -43,19 +41,10 @@ const SESSION_DAYS: u64 = 7; const DISCORD: &str = "https://discord.com/api/v10"; const SECURITY_CSP: &str = "default-src 'self'; img-src 'self' data: blob: https://cdn.discordapp.com; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; -/// Files under /f/ come from the internet (/download results). Sandboxed so an HTML or SVG file there can never run -/// script on the site's origin; pictures and video still show. -const HOSTED_CSP: &str = "sandbox; default-src 'none'; img-src 'self'; media-src 'self'; style-src 'unsafe-inline'"; -/// Discord sign-ins (dashboard /callback and the Activity's token swap) started per minute, all users together. Each -/// one costs a call to Discord's OAuth API, so someone hammering those URLs must not get the bot's address limited -/// by Discord. Real people sign in a few times a day; 20 a minute is far above that. -const SIGN_INS_PER_MINUTE: u32 = 20; const ACTIVITY_CSP: &str = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://cdn.discordapp.com; connect-src 'self' https://discord.com; media-src 'self' blob:; frame-ancestors https://discord.com https://*.discord.com https://*.discordsays.com; base-uri 'none'; form-action 'none'"; pub struct Cfg { pub url: String, - /// Path part of `url` without a trailing slash (`/dezio`), empty when the site lives at the root. - pub base: String, pub origin: String, pub secure: bool, pub host: String, @@ -63,12 +52,6 @@ pub struct Cfg { pub client_secret: String, } -/// The path part of the public address, without a trailing slash: `https://x.ts.net/dezio/` → `/dezio`, no path → ``. -pub fn base_path(url: &str) -> String { - let path = reqwest::Url::parse(url).map(|u| u.path().trim_end_matches('/').to_string()).unwrap_or_default(); - if path.is_empty() { String::new() } else { path } -} - impl Cfg { pub fn from_env() -> Self { let url = std::env::var("DASHBOARD_URL").ok().filter(|u| !u.is_empty()).unwrap_or_else(|| "http://192.168.1.71:8080".into()).trim_end_matches('/').to_string(); @@ -77,7 +60,6 @@ impl Cfg { let origin = parsed.as_ref().map(|u| format!("{}://{}", u.scheme(), u.host_str().unwrap_or("localhost").to_string() + &u.port().map(|p| format!(":{p}")).unwrap_or_default())).unwrap_or_else(|| url.clone()); let default_port = parsed.as_ref().and_then(|u| u.port_or_known_default()).unwrap_or(8080); Self { - base: base_path(&url), origin, secure, host: std::env::var("DASHBOARD_HOST").ok().filter(|h| !h.is_empty()).unwrap_or_else(|| "0.0.0.0".into()), @@ -94,36 +76,10 @@ pub struct Web { pub sessions: Arc, pub activity: Arc, pub preview: tokio::sync::Semaphore, - pub sign_ins: RateLimit, } pub type Shared = Arc; -/// A fixed-window counter: at most `per_minute` calls to `allow` succeed in each wall-clock minute. -pub struct RateLimit { - per_minute: u32, - window: std::sync::Mutex<(u64, u32)>, -} - -impl RateLimit { - pub fn new(per_minute: u32) -> Self { - Self { per_minute, window: std::sync::Mutex::new((0, 0)) } - } - - pub fn allow(&self, now_secs: u64) -> bool { - let mut g = self.window.lock().unwrap_or_else(|e| e.into_inner()); - let minute = now_secs / 60; - if g.0 != minute { - *g = (minute, 0); - } - if g.1 >= self.per_minute { - return false; - } - g.1 += 1; - true - } -} - #[derive(Clone, Debug)] pub struct Session { pub user_id: u64, @@ -181,7 +137,7 @@ impl Web { } fn set_cookie(&self, resp: &mut Response, name: &str, value: &str, max_age: u64) { - let c = format!("{name}={value}; Max-Age={max_age}; Path={}; HttpOnly; SameSite=Lax{}", if self.cfg.base.is_empty() { "/" } else { &self.cfg.base }, if self.cfg.secure { "; Secure" } else { "" }); + let c = format!("{name}={value}; Max-Age={max_age}; Path=/; HttpOnly; SameSite=Lax{}", if self.cfg.secure { "; Secure" } else { "" }); if let Ok(v) = HeaderValue::from_str(&c) { resp.headers_mut().append(header::SET_COOKIE, v); } @@ -241,7 +197,7 @@ impl Web { async fn login(AxState(w): AxState, axum::extract::Query(q): axum::extract::Query>) -> Response { if !w.sign_in_ready() { - return Redirect::to(&format!("{}/dashboard?error=setup", w.cfg.base)).into_response(); + return Redirect::to("/dashboard?error=setup").into_response(); } let state = random_token(24); let params = [("client_id", w.state.app_id().to_string()), ("redirect_uri", format!("{}/callback", w.cfg.url)), ("response_type", "code".into()), ("scope", "identify".into()), ("state", state.clone()), ("prompt", "none".into())]; @@ -255,15 +211,12 @@ async fn login(AxState(w): AxState, axum::extract::Query(q): axum::extra } async fn callback(AxState(w): AxState, headers: HeaderMap, axum::extract::Query(q): axum::extract::Query>) -> Response { - let fail = |why: &str| Redirect::to(&format!("{}/dashboard?error={why}", w.cfg.base)).into_response(); + let fail = |why: &str| Redirect::to(&format!("/dashboard?error={why}")).into_response(); let (state, code) = (q.get("state").cloned().unwrap_or_default(), q.get("code").cloned().unwrap_or_default()); let expected = cookie_value(&headers, STATE_COOKIE).unwrap_or_default(); if code.is_empty() || expected.is_empty() || state != expected { return fail("state"); } - if !w.sign_ins.allow(now()) { - return fail("busy"); - } let web = &w.state.web; let app = w.state.app_id().to_string(); let form = [("client_id", app.as_str()), ("client_secret", w.cfg.client_secret.as_str()), ("grant_type", "authorization_code"), ("code", code.as_str()), ("redirect_uri", &format!("{}/callback", w.cfg.url))]; @@ -285,7 +238,7 @@ async fn callback(AxState(w): AxState, headers: HeaderMap, axum::extract })); tracing::info!("Dashboard sign-in: {} ({})", me["username"], me["id"]); let after = cookie_value(&headers, NEXT_COOKIE).filter(|a| AFTER_LOGIN.contains(&a.as_str())).unwrap_or_else(|| "/dashboard".into()); - let mut resp = Redirect::to(&format!("{}{after}", w.cfg.base)).into_response(); + let mut resp = Redirect::to(&after).into_response(); w.set_cookie(&mut resp, SESSION_COOKIE, &raw, SESSION_DAYS * 86400); w.set_cookie(&mut resp, STATE_COOKIE, "", 0); w.set_cookie(&mut resp, NEXT_COOKIE, "", 0); @@ -305,15 +258,8 @@ async fn logout(AxState(w): AxState, headers: HeaderMap) -> ApiResult { // ---- headers + pages -------------------------------------------------------------------------------------------- -async fn headers_mw(AxState(base): AxState, request: Request, next: Next) -> Response { - let full = request.uri().path().to_string(); - // `/dezio` → `/dezio/`: the site's pages use relative links, which only stay under the base with the slash. - if !base.is_empty() && full == base { - let query = request.uri().query().map(|q| format!("?{q}")).unwrap_or_default(); - return Redirect::permanent(&format!("{base}/{query}")).into_response(); - } - // Rules below match the path without the base, so they hold under /dezio/ and without it. - let path = if base.is_empty() { full } else { full.strip_prefix(base.as_str()).unwrap_or(&full).to_string() }; +async fn headers_mw(request: Request, next: Next) -> Response { + let path = request.uri().path().to_string(); let mut resp = next.run(request).await; let h = resp.headers_mut(); h.insert("x-content-type-options", HeaderValue::from_static("nosniff")); @@ -325,7 +271,7 @@ async fn headers_mw(AxState(base): AxState, request: Request, next: Next } else { h.insert("x-frame-options", HeaderValue::from_static("DENY")); h.insert("referrer-policy", HeaderValue::from_static("same-origin")); - h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(if path.starts_with("/f/") { HOSTED_CSP } else { SECURITY_CSP })); + h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(SECURITY_CSP)); } // Pages and their scripts change together on an update, so a browser must ask before reusing a stale copy. if path.starts_with("/dashboard/static/") || path.starts_with("/assets/") { @@ -340,56 +286,38 @@ async fn headers_mw(AxState(base): AxState, request: Request, next: Next pub fn router(w: Shared) -> Router { let site = paths::web(&["site"]); let app = paths::web(&["dashboard"]); - let base = w.cfg.base.clone(); - // HTML pages carry `__BASE__` where a root-absolute path would go; it becomes the base path here. - let page = |dir: &std::path::Path, name: &str| { - let file = dir.join(name); - let base = base.clone(); - get(move || { - let (file, base) = (file.clone(), base.clone()); - async move { - let html = tokio::fs::read_to_string(&file).await.unwrap_or_default().replace("__BASE__", &base); - ([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response() - } - }) - }; - let inner: Router = Router::new() + let page = |dir: &std::path::Path, name: &str| ServeFile::new(dir.join(name)); + Router::new() .route("/login", get(login)) .route("/callback", get(callback)) .route("/logout", post(logout)) .merge(api::routes()) .merge(activity::routes()) - .route("/dashboard", page(&app, "index.html")) - .route("/dashboard/", page(&app, "index.html")) - .route("/", page(&site, "index.html")) - .route("/index.html", page(&site, "index.html")) - .route("/terms", page(&site, "terms.html")) - .route("/terms.html", page(&site, "terms.html")) - .route("/privacy", page(&site, "privacy.html")) - .route("/privacy.html", page(&site, "privacy.html")) - .nest_service("/dashboard/static", ServeDir::new(app.join("static")).append_index_html_on_directories(false)) - .nest_service("/assets", ServeDir::new(site.join("assets")).append_index_html_on_directories(false)) - .nest_service("/images", ServeDir::new(site.join("images")).append_index_html_on_directories(false)) + .route_service("/dashboard", page(&app, "index.html")) + .route_service("/dashboard/", page(&app, "index.html")) + .route_service("/", page(&site, "index.html")) + .route_service("/index.html", page(&site, "index.html")) + .route_service("/terms", page(&site, "terms.html")) + .route_service("/terms.html", page(&site, "terms.html")) + .route_service("/privacy", page(&site, "privacy.html")) + .route_service("/privacy.html", page(&site, "privacy.html")) + .nest_service("/dashboard/static", ServeDir::new(app.join("static"))) + .nest_service("/assets", ServeDir::new(site.join("assets"))) + .nest_service("/images", ServeDir::new(site.join("images"))) // files too big for Discord, kept for a few hours (see hosted.rs) - .nest_service("/f", ServeDir::new(crate::hosted::dir()).append_index_html_on_directories(false)); - // Under a base path (/dezio) the routes live there. The un-prefixed paths stay too, so it works whether the - // reverse proxy (tailscale serve --set-path) strips the prefix or not. - let routes = if base.is_empty() { inner } else { Router::new().route(&format!("{base}/"), page(&site, "index.html")).nest(&base, inner.clone()).merge(inner) }; - routes - .layer(middleware::from_fn_with_state(base, headers_mw)) + .nest_service("/f", ServeDir::new(crate::hosted::dir())) + .layer(middleware::from_fn(headers_mw)) .layer(axum::extract::DefaultBodyLimit::max(64 * 1024)) .with_state(w) } /// For `--web-dev`: serve on 127.0.0.1:8099 with a signed-in test session (cookie `dezio_session=devtoken`). pub fn start_dev(state: Arc) { - // DASHBOARD_URL's path is kept (…/dezio) so the base-path routing can be tried locally. - let url = format!("http://127.0.0.1:8099{}", base_path(&std::env::var("DASHBOARD_URL").unwrap_or_default())); - let base = base_path(&url); - let cfg = Cfg { origin: url.clone(), base, url, secure: false, host: "127.0.0.1".into(), port: 8099, client_secret: "dev".into() }; + let url = "http://127.0.0.1:8099".to_string(); + let cfg = Cfg { origin: url.clone(), url, secure: false, host: "127.0.0.1".into(), port: 8099, client_secret: "dev".into() }; let sessions = JsonStore::open(std::env::temp_dir().join("dezio-dev-sessions.json")); sessions.set(sha("devtoken"), json!({"user_id": 4242u64, "name": "Dev Tester", "username": "devtester", "avatar": null, "csrf": "devcsrf", "created": now(), "expires": now() + 86400})); - let web = Arc::new(Web { state, cfg, sessions, activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2), sign_ins: RateLimit::new(SIGN_INS_PER_MINUTE) }); + let web = Arc::new(Web { state, cfg, sessions, activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2) }); let app = router(web); tokio::spawn(async move { let listener = tokio::net::TcpListener::bind("127.0.0.1:8099").await.expect("port 8099"); @@ -403,7 +331,7 @@ pub fn start(state: Arc) { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { let cfg = Cfg::from_env(); - let web = Arc::new(Web { sessions: JsonStore::open(paths::data(&["dashboard_sessions.json"])), activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2), sign_ins: RateLimit::new(SIGN_INS_PER_MINUTE), state, cfg }); + let web = Arc::new(Web { sessions: JsonStore::open(paths::data(&["dashboard_sessions.json"])), activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2), state, cfg }); let addr = format!("{}:{}", web.cfg.host, web.cfg.port); let ready = web.sign_in_ready(); let url = web.cfg.url.clone(); @@ -429,51 +357,14 @@ mod tests { use axum::http::{Method, Request as HttpRequest}; use tower::ServiceExt; - #[test] - fn base_path_from_dashboard_url() { - assert_eq!(base_path("https://astar76.com/dezio"), "/dezio"); - assert_eq!(base_path("https://astar76.com/dezio/"), "/dezio"); - assert_eq!(base_path("http://127.0.0.1:8099/a/b"), "/a/b"); - assert_eq!(base_path("http://192.168.1.71:8080"), ""); - assert_eq!(base_path("http://192.168.1.71:8080/"), ""); - assert_eq!(base_path("not a url"), ""); - } - - #[test] - fn sign_ins_are_limited_per_minute() { - let r = RateLimit::new(2); - assert!(r.allow(600) && r.allow(610)); - assert!(!r.allow(619), "third in the same minute"); - assert!(r.allow(660), "a new minute starts over"); - } - - #[tokio::test] - async fn base_path_routes_and_redirects() { - let w = web(); - let cfg = Cfg { url: "http://dashboard.test/dezio".into(), base: "/dezio".into(), origin: "http://dashboard.test".into(), secure: false, host: "127.0.0.1".into(), port: 0, client_secret: "secret".into() }; - let app = router(Arc::new(Web { state: w.state.clone(), cfg, sessions: w.sessions.clone(), activity: w.activity.clone(), preview: tokio::sync::Semaphore::new(2), sign_ins: RateLimit::new(SIGN_INS_PER_MINUTE) })); - let get = |p: &str| HttpRequest::get(p).body(Body::empty()).unwrap(); - for p in ["/dezio/", "/", "/dezio/dashboard", "/dashboard", "/dezio/assets/site.css", "/assets/site.css"] { - assert_eq!(call(&app, get(p)).await.0, StatusCode::OK, "{p}"); - } - let (s, h, _) = call(&app, get("/dezio?x=1")).await; - assert!(s.is_redirection() && h[header::LOCATION] == "/dezio/?x=1", "the bare base gets its slash"); - let (s, _, _) = call(&app, get("/dezio/assets/fonts")).await; - assert_eq!(s, StatusCode::NOT_FOUND, "folders don't redirect (the redirect lost the base path)"); - let (_, h, _) = call(&app, get("/dezio/login")).await; - assert!(h.get_all(header::SET_COOKIE).iter().any(|c| c.to_str().unwrap().contains("; Path=/dezio;"))); - let (s, h, _) = call(&app, get("/dezio/callback?state=a&code=b")).await; - assert!(s.is_redirection() && h[header::LOCATION] == "/dezio/dashboard?error=state"); - } - fn web() -> Shared { let _ = rustls::crypto::ring::default_provider().install_default(); let http = Arc::new(twilight_http::Client::new("x".into())); let state = Arc::new(State::new(http, crate::cmd::Registry::new(vec![]), "x".into())); state.set_app_id(twilight_model::id::Id::new(1)); state.set_bot_id(twilight_model::id::Id::new(2)); - let cfg = Cfg { url: "http://dashboard.test".into(), base: String::new(), origin: "http://dashboard.test".into(), secure: false, host: "127.0.0.1".into(), port: 0, client_secret: "secret".into() }; - Arc::new(Web { state, cfg, sessions: JsonStore::open(std::env::temp_dir().join(format!("dezio-ws-{}.json", rand::random::()))), activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2), sign_ins: RateLimit::new(SIGN_INS_PER_MINUTE) }) + let cfg = Cfg { url: "http://dashboard.test".into(), origin: "http://dashboard.test".into(), secure: false, host: "127.0.0.1".into(), port: 0, client_secret: "secret".into() }; + Arc::new(Web { state, cfg, sessions: JsonStore::open(std::env::temp_dir().join(format!("dezio-ws-{}.json", rand::random::()))), activity: Arc::new(activity::Activity::new()), preview: tokio::sync::Semaphore::new(2) }) } fn signed_in(w: &Shared) -> (String, String) { @@ -559,7 +450,6 @@ mod tests { let (status, headers, body) = call(&app, HttpRequest::get(&path).body(Body::empty()).unwrap()).await; assert_eq!((status, body.as_slice()), (StatusCode::OK, &b"0123456789"[..]), "{path}"); assert_eq!(headers.get("content-type").and_then(|v| v.to_str().ok()), Some("video/mp4")); - assert!(headers["content-security-policy"].to_str().unwrap().starts_with("sandbox;"), "hosted files can't run script"); let (status, _, body) = call(&app, HttpRequest::get(&path).header("range", "bytes=2-4").body(Body::empty()).unwrap()).await; assert_eq!((status, body.as_slice()), (StatusCode::PARTIAL_CONTENT, &b"234"[..])); let (status, _, _) = call(&app, HttpRequest::get("/f/0000000000000000/nothing.mp4").body(Body::empty()).unwrap()).await; diff --git a/web/activity/static/app.js b/web/activity/static/app.js index 7637868..f176c76 100644 --- a/web/activity/static/app.js +++ b/web/activity/static/app.js @@ -7,8 +7,7 @@ */ 'use strict'; -// Where this page is served from: /dezio/activity in a browser, / inside Discord (its URL mapping hides the prefix). -const BASE = location.pathname.replace(/\/(index\.html)?$/, ''); +const BASE = location.pathname.startsWith('/activity') ? '/activity' : ''; const $ = (s) => document.querySelector(s); const CPU_HZ = 4194304; const AUDIO_FRAMES = 4096; diff --git a/web/dashboard/index.html b/web/dashboard/index.html index 6a0a9db..fd08dfe 100644 --- a/web/dashboard/index.html +++ b/web/dashboard/index.html @@ -1,14 +1,14 @@ - + Dezio dashboard - - - - + + + + diff --git a/web/site/privacy.html b/web/site/privacy.html index c1acebb..85bd250 100644 --- a/web/site/privacy.html +++ b/web/site/privacy.html @@ -11,7 +11,7 @@
@@ -42,7 +42,7 @@ diff --git a/web/site/terms.html b/web/site/terms.html index edd060e..e1b0720 100644 --- a/web/site/terms.html +++ b/web/site/terms.html @@ -11,7 +11,7 @@
@@ -48,7 +48,7 @@