From bf12d98c88c4e1c5ac293571b0ad019d90622771 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Mon, 16 Nov 2026 01:14:26 +0100 Subject: [PATCH 1/9] feat(public-pages): the server's own accent colour and background on its public member pages A server can give the pages its members open without the dashboard an accent colour and a background (none, an uploaded picture, or a copy of the server's invite splash that Sylo downloads itself, checks daily and serves itself). Only those two things change: the layout, type, components, themes and the always-on "Powered by Sylo" link stay Sylo's. - migration 81: guild_public_look and public_look_images (purged with the server) - /look/..css and .webp: guild-scoped, hash-named, immutable, no cookie; the style sheet carries custom properties only, the CSP is unchanged - the upload goes through the collectible picture pipeline (2 MB, magic bytes, header size check, decode queue, re-encoded WebP, metadata gone) - an accent below 3:1 against the card falls back to Sylo's colour in that theme - GET/POST /api/v2/guilds/:id/public-page-look (Edit only) and the public-page-look feature string for the app - Server settings -> Public pages with a live preview of the application form - applied to the application form, web shop, ban appeal, quote page and both leaderboards --- docs/dashboard-v2.md | 18 + docs/mobile-app.md | 30 +- docs/privacy-policy.md | 1 + src/db/index.js | 26 ++ src/db/publicLook.js | 133 ++++++ src/db/purge.js | 3 + src/lib/collectibleImage.js | 11 +- src/lib/publicLook.js | 150 +++++++ src/web/lib/publicLook.js | 235 ++++++++++ src/web/lib/routeAccess.js | 6 + src/web/public/public.css | 44 ++ src/web/routes/appeal.js | 9 + src/web/routes/economyBoard.js | 2 + src/web/routes/leaderboard.js | 2 + src/web/routes/mobile.js | 3 + src/web/routes/publicLook.js | 66 +++ src/web/routes/quotes.js | 2 + src/web/routes/v2Api.js | 3 + src/web/routes/v2Apply.js | 5 + src/web/routes/v2PublicLook.js | 168 +++++++ src/web/routes/v2ShopMember.js | 3 + src/web/server.js | 3 + src/web/views/appeal.ejs | 5 +- src/web/views/economy-leaderboard.ejs | 5 +- src/web/views/event-missing.ejs | 2 +- src/web/views/event-signin.ejs | 2 +- src/web/views/event.ejs | 2 +- src/web/views/leaderboard.ejs | 5 +- src/web/views/partials/auth-foot.ejs | 2 +- src/web/views/partials/look.ejs | 3 + src/web/views/partials/powered.ejs | 3 + src/web/views/quotes.ejs | 5 +- src/web/views/verify.ejs | 2 +- test/eventPages.public.test.js | 10 +- test/mobileInfo.test.js | 1 + test/publicLook.lib.test.js | 136 ++++++ test/publicLook.web.test.js | 420 ++++++++++++++++++ test/quotesPublic.test.js | 6 +- test/v2.accessLevels.test.js | 42 ++ .../__tests__/PublicPagesSettings.test.jsx | 178 ++++++++ web-v2/src/__tests__/publicLook.test.jsx | 105 +++++ web-v2/src/api.js | 12 + web-v2/src/components/MemberShell.jsx | 2 + web-v2/src/components/PoweredBy.jsx | 11 + web-v2/src/components/PublicPagesSettings.jsx | 268 +++++++++++ web-v2/src/components/PublicShell.jsx | 2 + web-v2/src/main.jsx | 1 + web-v2/src/pages/Apply.jsx | 3 + web-v2/src/pages/Settings.jsx | 4 + web-v2/src/pages/Shop.jsx | 3 + web-v2/src/publicLook.js | 93 ++++ web-v2/src/styles/p3-look.css | 162 +++++++ 52 files changed, 2398 insertions(+), 20 deletions(-) create mode 100644 src/db/publicLook.js create mode 100644 src/lib/publicLook.js create mode 100644 src/web/lib/publicLook.js create mode 100644 src/web/routes/publicLook.js create mode 100644 src/web/routes/v2PublicLook.js create mode 100644 src/web/views/partials/look.ejs create mode 100644 src/web/views/partials/powered.ejs create mode 100644 test/publicLook.lib.test.js create mode 100644 test/publicLook.web.test.js create mode 100644 web-v2/src/__tests__/PublicPagesSettings.test.jsx create mode 100644 web-v2/src/__tests__/publicLook.test.jsx create mode 100644 web-v2/src/components/PoweredBy.jsx create mode 100644 web-v2/src/components/PublicPagesSettings.jsx create mode 100644 web-v2/src/publicLook.js create mode 100644 web-v2/src/styles/p3-look.css diff --git a/docs/dashboard-v2.md b/docs/dashboard-v2.md index 3c55bf9f..7e9d9848 100644 --- a/docs/dashboard-v2.md +++ b/docs/dashboard-v2.md @@ -79,6 +79,24 @@ all. A step that posts a message (verification, honeypot) or updates AutoMod is named in the preview before you confirm. Each import is written to the audit log. +## Public pages + +Server settings → **Public pages** (Edit access only) gives the pages your members open without the dashboard their +own look: the application form (and the web shop), the ban appeal, the quote page and the two leaderboards. Two +things change and nothing else: the **accent colour** (buttons, links and highlights) and a **background**. The +background is none, a picture you upload (PNG, JPEG or WebP, at most 2 MB; Sylo stores a re-encoded copy without +metadata, at most 1920 pixels wide, and serves it itself), or the server's **invite background** on Discord or +Fluxer: Sylo downloads it once, keeps its own copy, checks it once a day and serves it itself, so a visitor's +browser never talks to Discord or Fluxer. The settings show a live preview of the application form page. + +What stays Sylo's: the layout, the type, the components, the light and dark themes, the readability and the small +"Powered by Sylo" link at the bottom of every public page, which cannot be turned off. The page always sits on a +semi-opaque card over a dim overlay (opaque for visitors who ask for reduced transparency). An accent that is too hard +to read on the card (less than 3:1 against it) is not used in that theme (the light or the dark one): Sylo's own +colour stays there, and the settings say so. The dashboard and the Sylo app are never restyled. The event pages take +no server look, because they carry no server address on purpose. The file addresses are `/look/..css` +and `.webp`; the content security policy is unchanged (styles and images from Sylo only). + ## Duplicate and templates The "⋯" menu of a reminder, an embed message, a reaction-role set, a custom diff --git a/docs/mobile-app.md b/docs/mobile-app.md index d03cd0c3..c154ff14 100644 --- a/docs/mobile-app.md +++ b/docs/mobile-app.md @@ -317,7 +317,7 @@ in there: | `login` | Whether sign-in is available (false in open mode) | | `loginProviders` | The configured logins, for example `["discord", "fluxer"]`; empty when `login` is false | | `platforms` | The platforms the bot runs on, for example `["discord"]` | -| `features` | What this version's app API supports, so the app can hide what an older Sylo lacks. Today: `app-login`, `live-access`, `changelog`, `collectibles`, `welcome-trigger`, `member-search`, `access-levels`, `health`, `app-connect`, `setup-wizard`, `config-history`, `inbox-search`, `config-import`, `duplicate`, `message-templates` and `message-move`, plus `push` and `push-pigeon` when this instance can send notifications. See the list below | +| `features` | What this version's app API supports, so the app can hide what an older Sylo lacks. Today: `app-login`, `live-access`, `changelog`, `collectibles`, `welcome-trigger`, `member-search`, `access-levels`, `health`, `app-connect`, `setup-wizard`, `config-history`, `inbox-search`, `config-import`, `duplicate`, `message-templates`, `message-move` and `public-page-look`, plus `push` and `push-pigeon` when this instance can send notifications. See the list below | The feature strings: @@ -338,6 +338,7 @@ The feature strings: - `duplicate`: the `duplicate` routes for reminders, embed messages, reaction-role sets, custom commands and shop items. - `message-templates`: the built-in message templates and the raw message JSON import and export. - `message-move`: when the channel of a posted **embed message**, the **Welcome channel** message or a **role panel** changes and is published, the server posts a fresh message in the new channel, stores it and then deletes the old one, so the app must not unpublish first. Other bot posts (verification, honeypot traps, applications and so on) are not covered. A publish that loses a race with another publish of the same embed message answers `409` with the current record. +- `public-page-look`: the server's [look on its public pages](#public-page-look): `GET` and `POST /api/v2/guilds/:id/public-page-look`, the background upload and the invite-background check. - `app-connect`: [adding the other login](#adding-the-other-login). Only where sign-in is on and both Discord and Fluxer logins are set up. - `push`, `push-pigeon`: this instance can send notifications to signed-in apps. @@ -393,6 +394,33 @@ Actions that post to the platform (test messages, publishing a message or role menu, locking or unlocking every channel) share a limit of 10 per minute per server and account, answered with `429` and an `{ "error" }`. +### Public page look + +`public-page-look` in `features`. A server may give the pages its members open without the dashboard (the +application form, the ban appeal, the quote and leaderboard pages and the web shop) its own accent colour and a +background. That is all it can change: the layout, the type, the components, the light and dark themes and the +"Powered by Sylo" link at the bottom of every public page stay Sylo's, and the dashboard and the app are never +restyled. The form always sits on a semi-opaque card over a dim overlay (opaque when the visitor asks for reduced +transparency). Every route here needs the **edit** level, the read too (a lower level gets the usual `403`). + +| Call | What it does | +| --- | --- | +| `GET /api/v2/guilds/:id/public-page-look` | The choice and what it comes to (below) | +| `POST /api/v2/guilds/:id/public-page-look` | Saves `{ "accent": "#5865f2" or "", "background": "none", "upload" or "discord-splash" }` and answers like the `GET` | +| `POST /api/v2/guilds/:id/public-page-look/image` | Uploads the background: a multipart body with the field `file` (PNG, JPEG or WebP, at most 2 MB, at most 16 megapixels). Sylo stores a new WebP of at most 1920 pixels, so metadata is gone. Answers like the `GET`. It does not change the choice: save `"background": "upload"` after it | +| `POST /api/v2/guilds/:id/public-page-look/image/delete` | Deletes the uploaded picture (a choice of `upload` falls back to `none`) and answers like the `GET` | +| `POST /api/v2/guilds/:id/public-page-look/splash/refresh` | Checks the invite background against the platform now and answers like the `GET`. Without it Sylo checks once a day, when a page that uses it is opened | + +The answer has `accent` and `background` (what was saved), `platform`, `upload` (`null` or `{ bytes, url, updatedAt }`), +`splash` (`available`: the server has an invite background on the platform, Discord and Fluxer both have one; +`copied`: `null` or `{ url, checkedAt, updatedAt }`, Sylo's own copy), `limits` and `sylo` (Sylo's accent per theme) +and `effective`: `accent` (the colour really used, per theme: `dark` and `light`), `contrast` (the ratio of the +accent to the card per theme and whether it reaches the 3:1 Sylo asks for), `fallback` (the themes where it does not and Sylo's own +colour is used instead), `note` (the sentence to show when `fallback` is not empty, else `null`) and `backgroundUrl`. +A `400` for a colour that is not `#rgb` or `#rrggbb`, for `upload` with no picture or for `discord-splash` +when the server has none; `502` when the invite background could not be downloaded. The urls are paths on the +Sylo server itself (the app prefixes the server address); the pictures are never loaded from the platform's CDN. + --- ## Tokens and signed-in devices diff --git a/docs/privacy-policy.md b/docs/privacy-policy.md index 3b287119..66db2135 100644 --- a/docs/privacy-policy.md +++ b/docs/privacy-policy.md @@ -83,6 +83,7 @@ the public-leaderboard vanity slug. - **Birthdays** — the day and month (and optionally year) a member registers. - **Giveaways** — the host, the entrants (with whether an entry fee was refunded), the drawn winners, and the currency prizes paid to members. - **Events** — the host and, for each event, who pressed Join or Maybe. A server can switch on a page for each event that shows its title, time, place, description, image, capacity and how many pressed Join or Maybe, but no names, no host and no ids. For an event in a channel everyone can read, anyone with the link can open the page. For an event in a private channel, only a person who signs in with the Dashboard login (Discord or Fluxer, the platform the event was posted on), is a member of that server and can see that channel can open it: Sylo checks this against the platform's data on every request and keeps only a plain yes or no, in memory, for a few seconds, and shows a signed-in person who may not open the page the same "not found" page as for a wrong address. A visitor who is not signed in sees a plain sign-in page that shows nothing about the event. An event in an age-restricted channel has no page for anyone. These pages are not cached by browsers or search engines, and nothing about the check is stored beyond the ordinary Dashboard login described in section 3 (a first sign-in creates a dashboard account and a session, which you can delete as described in section 7). The address of each event's page is a random code stored with the event. A visitor's browser contacts only Sylo: Sylo fetches the server icon and the event image from Discord's image servers itself and keeps a copy in memory only, for about ten minutes (a sweep removes expired copies every minute) and hands it out only to a visitor who passes the checks, and the pages carry no visit-count script when they are not found or ask for a sign-in. +- **Public page look** — a server's accent colour and background choice for its public member pages, and the background picture: one the server's staff upload (Sylo keeps a re-encoded copy without metadata) and/or a copy of the server's invite background from Discord or Fluxer, which Sylo downloads itself and refreshes daily. A visitor's browser loads these from Sylo only. Both go when the server's data is deleted. - **Suggestions** — the text of each suggestion, who wrote it (unless they erase it), the staff member who decided it, and each member's 👍 / 👎 vote. - **Temporary roles** — which member holds which temporary role, when it ends, the reason, and the staff member who set it. - **Introductions** — the answers a member gave in the DM questionnaire (up to eight short texts, with @everyone, @here and role mentions removed), the channel and message ids of their card, and when it was made and last changed. The card itself is a public message in the server's introductions channel: it shows the member's avatar, name, answers, the roles they have from the server's role groups, and when they joined. diff --git a/src/db/index.js b/src/db/index.js index 5991616a..8b4662bc 100644 --- a/src/db/index.js +++ b/src/db/index.js @@ -1594,6 +1594,32 @@ export const MIGRATIONS = [ if (!has.has('decided_by_user_id')) database.exec('ALTER TABLE appeals ADD COLUMN decided_by_user_id TEXT;'); }, + + // The server's own look on the public member pages (src/db/publicLook.js, which bootstraps the same tables + // on Postgres): an accent colour and a background choice per server, and the picture of the background + // (an upload, or a copy of the server's invite splash that Sylo keeps itself). One picture per source. + (database) => { + database.exec(` + CREATE TABLE guild_public_look ( + guild_id TEXT PRIMARY KEY, + accent TEXT NOT NULL DEFAULT '', + background TEXT NOT NULL DEFAULT 'none', + updated_at INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE public_look_images ( + guild_id TEXT NOT NULL, + source TEXT NOT NULL, + hash TEXT NOT NULL, + mime TEXT NOT NULL, + bytes INTEGER NOT NULL, + data BLOB NOT NULL, + origin TEXT NOT NULL DEFAULT '', + checked_at INTEGER NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (guild_id, source) + ); + `); + }, ]; /** Highest schema version this build knows how to run. */ diff --git a/src/db/publicLook.js b/src/db/publicLook.js new file mode 100644 index 00000000..451ac5ac --- /dev/null +++ b/src/db/publicLook.js @@ -0,0 +1,133 @@ +// The server's own look on its public member pages, stored in the database. +// +// guild_public_look guild_id, accent ('#rrggbb' or ''), background ('none', 'upload' or 'discord-splash'), +// updated_at +// public_look_images guild_id, source ('upload' or 'splash'), hash (the first 16 hex characters of the SHA-256 +// of the stored bytes: it is in the picture's address), mime, bytes, data (BLOB on SQLite, +// BYTEA on Postgres), origin (for a splash: the hash Discord or Fluxer gave it, so a +// daily check can tell whether it changed without downloading it again), checked_at +// (when the splash was last checked), created_at +// +// Like a collectible's picture, what is stored is never what came in: lib/collectibleImage.js decodes it and +// encodes a new WebP of at most BACKGROUND_MAX_SIDE pixels, so metadata and anything that was not a picture are +// gone. There is one picture per source and server, so replacing one deletes the old one in the same statement, +// and the pictures are part of every backup. Both tables hold rows per server and go with the server's data +// (purge.js). +import { prepare, registerPostgresBootstrap } from './driver.js'; + +/** The background is scaled to fit in a box of this many pixels, at this WebP quality. */ +export const BACKGROUND_MAX_SIDE = 1920; +export const BACKGROUND_QUALITY = 78; +/** The two places a background picture comes from. */ +export const SOURCES = Object.freeze(['upload', 'splash']); + +registerPostgresBootstrap(` + CREATE TABLE IF NOT EXISTS guild_public_look ( + guild_id TEXT PRIMARY KEY, + accent TEXT NOT NULL DEFAULT '', + background TEXT NOT NULL DEFAULT 'none', + updated_at BIGINT NOT NULL DEFAULT 0 + ); + CREATE TABLE IF NOT EXISTS public_look_images ( + guild_id TEXT NOT NULL, + source TEXT NOT NULL, + hash TEXT NOT NULL, + mime TEXT NOT NULL, + bytes INTEGER NOT NULL, + data BYTEA NOT NULL, + origin TEXT NOT NULL DEFAULT '', + checked_at BIGINT NOT NULL, + created_at BIGINT NOT NULL, + PRIMARY KEY (guild_id, source) + ); + -- A WebP does not compress any further: do not let Postgres try. + ALTER TABLE public_look_images ALTER COLUMN data SET STORAGE EXTERNAL; +`); + +const s = { + getLook: prepare('SELECT accent, background, updated_at FROM guild_public_look WHERE guild_id = ?'), + setLook: prepare(` + INSERT INTO guild_public_look (guild_id, accent, background, updated_at) VALUES (?, ?, ?, ?) + ON CONFLICT (guild_id) DO UPDATE SET + accent = excluded.accent, background = excluded.background, updated_at = excluded.updated_at + `), + meta: prepare( + 'SELECT hash, mime, bytes, origin, checked_at, created_at FROM public_look_images WHERE guild_id = ? AND source = ?' + ), + put: prepare(` + INSERT INTO public_look_images (guild_id, source, hash, mime, bytes, data, origin, checked_at, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT (guild_id, source) DO UPDATE SET + hash = excluded.hash, mime = excluded.mime, bytes = excluded.bytes, data = excluded.data, + origin = excluded.origin, checked_at = excluded.checked_at, created_at = excluded.created_at + `), + touch: prepare('UPDATE public_look_images SET checked_at = ? WHERE guild_id = ? AND source = ?'), + drop: prepare('DELETE FROM public_look_images WHERE guild_id = ? AND source = ?'), + byHash: prepare('SELECT mime, bytes, data FROM public_look_images WHERE guild_id = ? AND hash = ?'), +}; + +/** + * What a server chose. Never null: a server that chose nothing has no accent and no background. + * @returns {Promise<{ accent: string, background: string, updatedAt: number }>} + */ +export async function getPublicLook(guildId) { + const row = await s.getLook.get(guildId); + return row + ? { accent: row.accent, background: row.background, updatedAt: Number(row.updated_at) } + : { accent: '', background: 'none', updatedAt: 0 }; +} + +/** Save the choice (already checked by the caller). */ +export async function setPublicLook(guildId, { accent, background }, now = Date.now()) { + await s.setLook.run(guildId, accent, background, now); +} + +/** + * The facts about a stored picture, without its bytes, or null. + * @param {string} guildId + * @param {'upload' | 'splash'} source + * @returns {Promise<{ hash: string, mime: string, bytes: number, origin: string, checkedAt: number, createdAt: number } | null>} + */ +export async function getLookImageMeta(guildId, source) { + const row = await s.meta.get(guildId, source); + return row + ? { + hash: row.hash, + mime: row.mime, + bytes: Number(row.bytes), + origin: row.origin, + checkedAt: Number(row.checked_at), + createdAt: Number(row.created_at), + } + : null; +} + +/** + * Store a picture for a source, replacing (and so deleting) the one it had. + * @param {string} guildId + * @param {'upload' | 'splash'} source + * @param {{ hash: string, mime: string, data: Buffer, origin?: string, now?: number }} image + */ +export async function putLookImage(guildId, source, { hash, mime, data, origin = '', now = Date.now() }) { + await s.put.run(guildId, source, hash, mime, data.length, data, origin, now, now); +} + +/** Note that a splash was checked and is still the same picture. */ +export async function touchLookImage(guildId, source, now = Date.now()) { + await s.touch.run(now, guildId, source); +} + +/** Delete the picture of a source. @returns {Promise} whether there was one */ +export async function deleteLookImage(guildId, source) { + return (await s.drop.run(guildId, source)).changes > 0; +} + +/** + * A stored picture by the hash in its address, for this server only, or null. + * @returns {Promise<{ mime: string, bytes: number, data: Buffer } | null>} + */ +export async function readLookImage(guildId, hash) { + if (typeof hash !== 'string' || !/^[0-9a-f]{16}$/.test(hash)) return null; + const row = await s.byHash.get(guildId, hash); + return row ? { mime: row.mime, bytes: Number(row.bytes), data: Buffer.from(row.data) } : null; +} diff --git a/src/db/purge.js b/src/db/purge.js index fcc06f41..60c89b13 100644 --- a/src/db/purge.js +++ b/src/db/purge.js @@ -65,6 +65,7 @@ import './welcomeSent.js'; import './applications.js'; import './economy.js'; import './economyShop.js'; +import './publicLook.js'; // Tables keyed directly by guild_id. A test in test/guildTables.test.js checks // this stays in sync with the schema so new guild data can't escape /forget or @@ -121,6 +122,8 @@ export const GUILD_TABLES = [ 'economy_items', 'economy_inventory', 'collectible_images', + 'guild_public_look', + 'public_look_images', ]; const simpleStmts = GUILD_TABLES.map((t) => prepare(`DELETE FROM ${t} WHERE guild_id = ?`)); diff --git a/src/lib/collectibleImage.js b/src/lib/collectibleImage.js index 74388d05..49165b11 100644 --- a/src/lib/collectibleImage.js +++ b/src/lib/collectibleImage.js @@ -123,8 +123,11 @@ export const _decodeQueue = () => ({ running, waiting: waiting.length }); /** * Check and re-encode an uploaded file. * @param {Buffer} buf the bytes of the file - * @param {{ queueTimeoutMs?: number, owner?: string, decodeTimeoutMs?: number, loadImage?: Function }} [opts] + * @param {{ queueTimeoutMs?: number, owner?: string, decodeTimeoutMs?: number, loadImage?: Function, + * maxSide?: number, quality?: number }} [opts] * `owner`: who asks (the server id), for the share of the queue. `loadImage` replaces the decoder (tests only). + * `maxSide` and `quality`: the size and the WebP quality of what is stored (a collectible: 512 and 85; the + * background of a public page asks for more, see db/publicLook.js). Every other check is the same. * @returns {Promise<{ data: Buffer, mime: string, width: number, height: number, kind: string }>} * @throws {ImageError} */ @@ -135,6 +138,8 @@ export async function processImage( owner = null, decodeTimeoutMs = DECODE_TIMEOUT_MS, loadImage = null, + maxSide = MAX_SIDE, + quality = WEBP_QUALITY, } = {} ) { if (!Buffer.isBuffer(buf) || buf.length === 0) throw new ImageError('Choose an image to upload.'); @@ -173,7 +178,7 @@ export async function processImage( if (!(w >= 1 && h >= 1) || w * h > MAX_SOURCE_PIXELS) throw new ImageError('That file is not a valid image.'); - const scale = Math.min(1, MAX_SIDE / Math.max(w, h)); + const scale = Math.min(1, maxSide / Math.max(w, h)); const width = Math.max(1, Math.round(w * scale)); const height = Math.max(1, Math.round(h * scale)); const surface = mod.createCanvas(width, height); @@ -181,7 +186,7 @@ export async function processImage( ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = 'high'; ctx.drawImage(img, 0, 0, width, height); - const data = await surface.encode('webp', WEBP_QUALITY); + const data = await surface.encode('webp', quality); if (sniffImage(data) !== 'webp') throw new ImageError('This server cannot process images right now.', 503); return { data, mime: STORED_MIME, width, height, kind }; diff --git a/src/lib/publicLook.js b/src/lib/publicLook.js new file mode 100644 index 00000000..14b2448e --- /dev/null +++ b/src/lib/publicLook.js @@ -0,0 +1,150 @@ +// The server's own look on the public member pages (the application form, the ban appeal, the event and quote +// pages, the web shop): an accent colour and a background, and nothing else. The community owns the content, +// Sylo owns the frame: the layout, the typography, the components, the light and dark themes and the +// readability stay Sylo's, and every page ends with a "Powered by Sylo" link that cannot be turned off. +// +// This file is the pure part: checking an accent colour, the contrast rule, and the style sheet a page loads. +// The style sheet carries custom properties only (--accent, --on-accent, --look-image). Everything that uses +// them (the card, the dim overlay, the buttons) is written once in Sylo's own style sheets, so a server cannot +// change a rule, only the two values the rules read. +import { createHash } from 'node:crypto'; + +/** What a server may choose for its background. */ +export const BACKGROUNDS = Object.freeze(['none', 'upload', 'discord-splash']); + +/** Sylo's own accent per theme (public.css and the dashboard's styles.css), the fallback. */ +export const SYLO_ACCENT = Object.freeze({ dark: '#38c8f0', light: '#076787' }); +/** The colour of the card the form sits on, per theme (--bg-surface). */ +export const CARD = Object.freeze({ dark: '#161618', light: '#ffffff' }); +/** + * The least contrast an accent needs against the card: 3:1, the WCAG minimum for interface elements and large text + * (links on these pages are underlined). No colour reaches 4.5:1 on both the dark and the light card, so a higher bar + * would send every server back to Sylo's colour in one theme; at 3:1 mid-tones such as #5865f2 read in both. + * The text on a button fill is chosen separately and always reaches 4.5:1 (onAccent). + */ +export const MIN_CONTRAST = 3; + +const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i; + +/** + * An accent as '#rrggbb' in lower case, '' for none, or null when it is not a colour. + * @param {unknown} value + * @returns {string | null} + */ +export function normaliseAccent(value) { + if (value == null) return ''; + if (typeof value !== 'string') return null; + const text = value.trim(); + if (text === '') return ''; + const m = HEX.exec(text); + if (!m) return null; + let hex = m[1].toLowerCase(); + if (hex.length === 3) hex = [...hex].map((c) => c + c).join(''); + return `#${hex}`; +} + +function channels(hex) { + const n = parseInt(hex.slice(1), 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; +} + +/** The relative luminance of a '#rrggbb' colour (WCAG 2). */ +export function luminance(hex) { + const [r, g, b] = channels(hex).map((c) => { + const v = c / 255; + return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +/** The contrast ratio of two '#rrggbb' colours, 1 to 21. */ +export function contrast(a, b) { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (hi + 0.05) / (lo + 0.05); +} + +/** The text colour on a fill of this accent (a button): black or white, whichever reads better (4.58:1 at worst). */ +export function onAccent(accent) { + return contrast(accent, '#ffffff') >= contrast(accent, '#000000') ? '#ffffff' : '#000000'; +} + +/** + * Is the accent readable on the card, in each theme? `fallback` lists the themes where Sylo's own accent is + * used instead, because this one would be too faint or too dark to read there. + * @param {string} accent '#rrggbb', or '' for none + * @returns {{ dark: { ratio: number, ok: boolean }, light: { ratio: number, ok: boolean }, fallback: Array<'dark'|'light'> }} + */ +export function accentCheck(accent) { + const out = { fallback: [] }; + for (const theme of ['dark', 'light']) { + if (!accent) { + out[theme] = { ratio: contrast(SYLO_ACCENT[theme], CARD[theme]), ok: true }; + continue; + } + const ratio = contrast(accent, CARD[theme]); + const ok = ratio >= MIN_CONTRAST; + out[theme] = { ratio: Math.round(ratio * 100) / 100, ok }; + if (!ok) out.fallback.push(theme); + } + return out; +} + +/** The accent that is really used per theme (the chosen one where it is readable, else Sylo's). */ +export function effectiveAccent(accent) { + const check = accentCheck(accent); + return { + dark: accent && check.dark.ok ? accent : SYLO_ACCENT.dark, + light: accent && check.light.ok ? accent : SYLO_ACCENT.light, + }; +} + +/** The sentence that says Sylo's accent was used, or null when the chosen one is fine everywhere. */ +export function fallbackNote(accent) { + const { fallback } = accentCheck(accent); + if (!accent || fallback.length === 0) return null; + const where = fallback.length === 2 ? 'both the light and the dark theme' : `the ${fallback[0]} theme`; + return `This colour is too hard to read on the card in ${where}, so public pages use Sylo's own colour there. Pick a darker or lighter shade.`; +} + +/** A short hash of what makes a look: it is in the address of the style sheet, so a change is a new address. */ +export function lookHash({ accent, imageHash }) { + return createHash('sha256') + .update(JSON.stringify([accent || '', imageHash || ''])) + .digest('hex') + .slice(0, 16); +} + +/** The short hash of a picture's bytes. */ +export const imageHashOf = (data) => createHash('sha256').update(data).digest('hex').slice(0, 16); + +/** + * The style sheet of a look. Custom properties only: the accent in each theme where it is readable (Sylo's + * own stays where it is not) and the background picture as a same-origin address. + * @param {{ accent: string, imageUrl: string | null }} look + */ +export function lookCss({ accent, imageUrl }) { + const lines = [ + "/* The look of one server's public pages: an accent colour and a background, nothing else. */", + ]; + const check = accentCheck(accent); + if (accent && check.dark.ok) { + lines.push(`:root { --accent: ${accent}; --on-accent: ${onAccent(accent)}; }`); + } + if (accent && check.light.ok) { + lines.push(`:root[data-theme='light'] { --accent: ${accent}; --on-accent: ${onAccent(accent)}; }`); + } + if (imageUrl) { + // Only an address this site made (see src/web/routes/publicLook.js): never user text. + if (!/^\/look\/[a-z0-9-]+\.[0-9a-f]{16}\.webp$/.test(imageUrl)) throw new Error('bad look image address'); + lines.push(`:root { --look-image: url('${imageUrl}'); }`); + } + return `${lines.join('\n')}\n`; +} + +/** The slug of a server key in an address: "fluxer:123" is "fluxer-123". */ +export const slugOf = (key) => String(key).replace(':', '-'); +/** The server key a slug stands for, or null for a slug of the wrong shape. */ +export function keyOfSlug(slug) { + const m = /^(?:(fluxer)-)?(\d{1,25})$/.exec(String(slug)); + return m ? (m[1] ? `fluxer:${m[2]}` : m[2]) : null; +} diff --git a/src/web/lib/publicLook.js b/src/web/lib/publicLook.js new file mode 100644 index 00000000..461459f4 --- /dev/null +++ b/src/web/lib/publicLook.js @@ -0,0 +1,235 @@ +// A server's look on its public member pages, put together for the pages and for the dashboard: what the chosen +// accent and background come to (the accent where it is readable, the picture that is really there), the +// address of the style sheet a page loads, and the one place the invite splash is fetched. +// +// Nothing is hotlinked: a background is a picture Sylo stores (an upload, or a copy of the server's invite splash +// that Sylo downloaded itself) and serves from its own address (routes/publicLook.js), so a visitor's browser +// never talks to the platform's CDN and the CSP can keep images to this site. +import { log } from '../../lib/log.js'; +import { safeFetch } from '../../lib/safeFetch.js'; +import { MAX_UPLOAD_BYTES, ImageError, processImage } from '../../lib/collectibleImage.js'; +import { + BACKGROUND_MAX_SIDE, + BACKGROUND_QUALITY, + deleteLookImage, + getLookImageMeta, + getPublicLook, + putLookImage, + touchLookImage, +} from '../../db/publicLook.js'; +import { + BACKGROUNDS, + SYLO_ACCENT, + accentCheck, + effectiveAccent, + fallbackNote, + imageHashOf, + lookCss, + lookHash, + slugOf, +} from '../../lib/publicLook.js'; +import { guildByKey, platformOfGuild } from '../../platform/platformOf.js'; + +/** A copied splash is checked against the platform once a day. */ +export const SPLASH_REFRESH_MS = 24 * 60 * 60 * 1000; +/** After a failed download, wait this long before trying again (a page view starts a try). */ +const SPLASH_RETRY_MS = 15 * 60 * 1000; +/** The size asked for at the platform's CDN: a power of two, enough for a full-page background. */ +const SPLASH_SIZE = 2048; + +/** The address of a stored picture: guild-scoped and named by its content hash. */ +export const imagePath = (key, hash) => `/look/${slugOf(key)}.${hash}.webp`; +/** The address of a server's look style sheet. */ +export const cssPath = (key, hash) => `/look/${slugOf(key)}.${hash}.css`; + +/** + * The picture a server's background really is: the one it chose, if that source has a picture. + * @returns {Promise<{ source: 'upload' | 'splash', hash: string } | null>} + */ +async function activeImage(key, background) { + const source = background === 'upload' ? 'upload' : background === 'discord-splash' ? 'splash' : null; + if (!source) return null; + const meta = await getLookImageMeta(key, source); + return meta ? { source, hash: meta.hash } : null; +} + +/** + * The look a page of this server takes: the style sheet to load, or null when the server chose nothing (the + * page stays plain Sylo). With a splash background it also starts the daily check, without waiting for it. + * @param {string} key the server key + * @returns {Promise<{ css: string, accent: string, imageUrl: string | null } | null>} + */ +export async function lookFor(key) { + if (!key) return null; + let row; + try { + row = await getPublicLook(key); + } catch (err) { + // A look is decoration: a page never fails because of it. + log.warn('public-look', 'could not read the look of a server:', err.message); + return null; + } + if (row.background === 'discord-splash') maybeRefreshSplash(key); + const image = await activeImage(key, row.background).catch(() => null); + if (!row.accent && !image) return null; + const hash = lookHash({ accent: row.accent, imageHash: image?.hash }); + return { + css: cssPath(key, hash), + accent: row.accent, + imageUrl: image ? imagePath(key, image.hash) : null, + }; +} + +/** + * The look for the dashboard's member pages (the shop, the application form), which are React pages that load the + * style sheet themselves: its address and whether there is a background picture, or null for plain Sylo. + * @returns {Promise<{ css: string, image: boolean } | null>} + */ +export async function lookRef(key) { + const look = await lookFor(key); + return look ? { css: look.css, image: look.imageUrl != null } : null; +} + +/** The stored look as the style sheet of a request says it: for the route, by the hash in the address. */ +export async function cssFor(key, hash) { + const row = await getPublicLook(key); + const image = await activeImage(key, row.background); + if (!row.accent && !image) return null; + if (lookHash({ accent: row.accent, imageHash: image?.hash }) !== hash) return null; + return lookCss({ accent: row.accent, imageUrl: image ? imagePath(key, image.hash) : null }); +} + +// --- the invite splash ------------------------------------------------------------------------------------- + +/** What the platform says about the server's invite splash: its hash and where to fetch it. */ +function splashOf(guild) { + const hash = guild?.splash; + if (!hash || typeof hash !== 'string') return null; + // Discord takes an extension; Fluxer's helper ignores it. Both give a bounded size. + const url = guild.splashURL?.({ size: SPLASH_SIZE, extension: 'webp' }) ?? null; + return url ? { hash, url } : null; +} + +/** Does the server have an invite splash right now? */ +export const hasSplash = (guild) => splashOf(guild) != null; + +const inFlight = new Map(); +const lastFailure = new Map(); + +/** For tests: forget which servers failed a download lately. */ +export const _resetSplashRetry = () => lastFailure.clear(); + +/** + * Make sure the stored copy of the server's invite splash is the platform's current one. Downloads only when the + * splash changed (or was never copied); a splash that is still the same is just marked as checked. A server + * that no longer has one loses its copy. Never throws: the caller gets what happened. + * @param {object} guild the platform's guild object + * @param {{ force?: boolean, now?: number, fetch?: typeof safeFetch }} [opts] + * `force` skips the once-a-day rule (a save or the "check now" button). + * @returns {Promise<{ status: 'none' | 'unchanged' | 'updated' | 'failed', message?: string }>} + */ +export async function refreshSplash(guild, { force = false, now = Date.now(), fetch = safeFetch } = {}) { + const key = guildKeyOfGuild(guild); + const running = inFlight.get(key); + if (running) return running; + const job = doRefresh(guild, key, { force, now, fetch }).finally(() => inFlight.delete(key)); + inFlight.set(key, job); + return job; +} + +const guildKeyOfGuild = (guild) => { + // The keyed id when the caller holds the dashboard's guild, else the platform's own id. + const id = String(guild.id); + return platformOfGuild(guild) === 'fluxer' && !id.startsWith('fluxer:') ? `fluxer:${id}` : id; +}; + +async function doRefresh(guild, key, { force, now, fetch }) { + try { + const known = await getLookImageMeta(key, 'splash'); + const splash = splashOf(guild); + if (!splash) { + if (known) await deleteLookImage(key, 'splash'); + return { status: 'none' }; + } + if (known && known.origin === splash.hash) { + if (force || now - known.checkedAt >= SPLASH_REFRESH_MS) await touchLookImage(key, 'splash', now); + return { status: 'unchanged' }; + } + if (!force && now - (lastFailure.get(key) ?? 0) < SPLASH_RETRY_MS) return { status: 'failed' }; + const res = await fetch(splash.url, { maxBytes: MAX_UPLOAD_BYTES, timeoutMs: 15_000 }); + if (!res.ok) throw new Error(`the platform answered ${res.status}`); + const picture = await processImage(res.body, { + owner: key, + maxSide: BACKGROUND_MAX_SIDE, + quality: BACKGROUND_QUALITY, + }); + await putLookImage(key, 'splash', { + hash: imageHashOf(picture.data), + mime: picture.mime, + data: picture.data, + origin: splash.hash, + now, + }); + lastFailure.delete(key); + return { status: 'updated' }; + } catch (err) { + const message = + err instanceof ImageError ? err.message : 'The invite background could not be downloaded.'; + lastFailure.set(key, now); + log.warn('public-look', `invite splash of ${key} not refreshed: ${err.message}`); + return { status: 'failed', message }; + } +} + +/** A page view asks for a look of a splash server: refresh in the background when the copy is a day old. */ +function maybeRefreshSplash(key) { + const guild = guildByKey(key); + if (!guild || inFlight.has(key)) return; + getLookImageMeta(key, 'splash') + .then((known) => { + if (known && Date.now() - known.checkedAt < SPLASH_REFRESH_MS) return; + return refreshSplash(guild); + }) + .catch(() => {}); +} + +// --- the dashboard's view --------------------------------------------------------------------------------- + +/** The settings page's data for a server: the choice, the pictures there are, and what it all comes to. */ +export async function lookView(guild, key) { + const [row, upload, splash] = await Promise.all([ + getPublicLook(key), + getLookImageMeta(key, 'upload'), + getLookImageMeta(key, 'splash'), + ]); + const platform = platformOfGuild(guild); + const image = row.background === 'upload' ? upload : row.background === 'discord-splash' ? splash : null; + const check = accentCheck(row.accent); + const look = row.accent || image ? await lookFor(key) : null; + return { + platform, + accent: row.accent, + background: row.background, + backgrounds: [...BACKGROUNDS], + upload: upload + ? { bytes: upload.bytes, url: imagePath(key, upload.hash), updatedAt: upload.createdAt } + : null, + splash: { + // Both platforms have an invite splash; a server may simply not have set one. + available: hasSplash(guild), + copied: splash + ? { url: imagePath(key, splash.hash), checkedAt: splash.checkedAt, updatedAt: splash.createdAt } + : null, + }, + effective: { + accent: effectiveAccent(row.accent), + contrast: { dark: check.dark, light: check.light }, + fallback: check.fallback, + note: fallbackNote(row.accent), + backgroundUrl: image ? imagePath(key, image.hash) : null, + css: look?.css ?? null, + }, + sylo: { accent: SYLO_ACCENT }, + limits: { maxBytes: MAX_UPLOAD_BYTES, types: ['PNG', 'JPEG', 'WebP'], maxSide: BACKGROUND_MAX_SIDE }, + }; +} diff --git a/src/web/lib/routeAccess.js b/src/web/lib/routeAccess.js index fb09e393..aeb4c661 100644 --- a/src/web/lib/routeAccess.js +++ b/src/web/lib/routeAccess.js @@ -258,6 +258,12 @@ export const ROUTE_ACCESS = Object.freeze({ 'POST /guilds/:guildId/modules/economy/shop/items/:id/delete': 'edit', 'POST /guilds/:guildId/modules/economy/shop/items/:id/image': 'edit', 'POST /guilds/:guildId/modules/economy/shop/items/:id/image/delete': 'edit', + // v2PublicLook.js: the server's look on its public pages. Edit only, the read too. + 'GET /guilds/:guildId/public-page-look': 'edit', + 'POST /guilds/:guildId/public-page-look': 'edit', + 'POST /guilds/:guildId/public-page-look/image': 'edit', + 'POST /guilds/:guildId/public-page-look/image/delete': 'edit', + 'POST /guilds/:guildId/public-page-look/splash/refresh': 'edit', 'GET /guilds/:guildId/modules/economy/members/:userId/inventory': 'view', 'POST /guilds/:guildId/modules/economy/members/:userId/inventory/grant': 'edit', 'POST /guilds/:guildId/modules/economy/members/:userId/inventory/:rowId/revoke': 'edit', diff --git a/src/web/public/public.css b/src/web/public/public.css index 6b172c3f..d5290c89 100644 --- a/src/web/public/public.css +++ b/src/web/public/public.css @@ -590,3 +590,47 @@ textarea:focus { transform: none; } } + +/* The look of a server's own public pages (src/lib/publicLook.js). The server's style sheet sets only custom + properties: --accent and --on-accent (already read by the rules above) and --look-image. Everything below is + Sylo's: the dim overlay, the semi-opaque panel the page sits on, the readability of the footer. The classes are + on : has-look (the server chose something) and has-look-image (it chose a background picture). */ +:root { + --look-dim: rgba(0, 0, 0, 0.58); + --look-panel: 90%; +} +:root[data-theme='light'] { + --look-dim: rgba(0, 0, 0, 0.42); +} +body.has-look-image { + background-color: var(--bg-main); + background-image: linear-gradient(var(--look-dim), var(--look-dim)), var(--look-image); + background-size: cover; + background-position: center; + background-repeat: no-repeat; + background-attachment: fixed; +} +body.has-look-image main { + position: relative; + margin-top: 24px; + margin-bottom: 24px; + border-radius: var(--radius); + background: color-mix(in srgb, var(--bg-main) var(--look-panel), transparent); + -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); +} +body.has-look-image .auth-wrap { + min-height: 0; +} +@media (prefers-reduced-transparency: reduce) { + body.has-look-image main { + background: var(--bg-main); + -webkit-backdrop-filter: none; + backdrop-filter: none; + } +} +/* An accent is only held to 3:1 against the card, so links are underlined whenever a server chose a look. */ +body.has-look main a:not(.btn) { + text-decoration: underline; + text-underline-offset: 3px; +} diff --git a/src/web/routes/appeal.js b/src/web/routes/appeal.js index ac2308ab..7edb0875 100644 --- a/src/web/routes/appeal.js +++ b/src/web/routes/appeal.js @@ -4,6 +4,7 @@ // later shows the decision — notification never depends on a DM getting through. import { guildByKey } from '../../platform/platformOf.js'; import { Router } from 'express'; +import { lookFor } from '../lib/publicLook.js'; import { isModuleEnabled, getGuildModule } from '../../db/modules.js'; import { log } from '../../lib/log.js'; import { @@ -126,9 +127,16 @@ async function resolve(req) { const inviteOf = (r) => r.cfg?.appealServerInvite || null; +// The server's own look (accent colour, background) once the link and the server are known to be real: an +// invalid link gets the plain Sylo page, so nothing about a server is shown to someone who only guessed an id. +async function applyLook(req, res, r) { + res.locals.look = r.guild ? await lookFor(req.params.guildId) : null; +} + router.get('/:guildId', async (req, res, next) => { try { const r = await resolve(req); + await applyLook(req, res, r); if (r.error) return render(res, 'error', { heading: r.heading, message: r.error }); if (r.state !== 'form') { return render(res, r.state, { @@ -156,6 +164,7 @@ router.get('/:guildId', async (req, res, next) => { router.post('/:guildId', async (req, res, next) => { try { const r = await resolve(req); + await applyLook(req, res, r); if (r.error) return render(res, 'error', { heading: r.heading, message: r.error }); if (r.state !== 'form') { return render(res, r.state, { diff --git a/src/web/routes/economyBoard.js b/src/web/routes/economyBoard.js index c8d2fcb3..ceffa0cd 100644 --- a/src/web/routes/economyBoard.js +++ b/src/web/routes/economyBoard.js @@ -8,6 +8,7 @@ import { guildByKey } from '../../platform/platformOf.js'; import { isPlatformGuildId } from '../../lib/platformId.js'; import { economySettings, formatNumber, leaderboardPage } from '../../modules/economy.js'; import { notFound, pageProfiles } from './leaderboard.js'; +import { lookFor } from '../lib/publicLook.js'; const PAGE_SIZE = 25; @@ -37,6 +38,7 @@ router.get('/:guildId', async (req, res, next) => { total: formatNumber(r.total), }; }); + res.locals.look = await lookFor(guildId); res.render('economy-leaderboard', { guild: { id: guild.id, name: guild.name, icon: guild.iconURL({ size: 64 }) }, members, diff --git a/src/web/routes/leaderboard.js b/src/web/routes/leaderboard.js index ec8c6dc7..7e36c1eb 100644 --- a/src/web/routes/leaderboard.js +++ b/src/web/routes/leaderboard.js @@ -15,6 +15,7 @@ import { periodKeys, } from '../../db/leveling.js'; import { levelProgress } from '../../modules/lib/levels.js'; +import { lookFor } from '../lib/publicLook.js'; import { guildForVanity } from '../../db/leaderboardVanity.js'; const PAGE_SIZE = 25; @@ -139,6 +140,7 @@ async function renderLeaderboard(req, res, next, guildId, canonical) { }) ); + res.locals.look = await lookFor(guildId); res.render('leaderboard', { guild: { id: guild.id, name: guild.name, icon: guild.iconURL({ size: 64 }) }, members, diff --git a/src/web/routes/mobile.js b/src/web/routes/mobile.js index 1d5575c4..e0f0a209 100644 --- a/src/web/routes/mobile.js +++ b/src/web/routes/mobile.js @@ -312,6 +312,8 @@ export const mobileApiRouter = Router(); // sign-in is on and both Discord and Fluxer logins are set up. `access-levels`: View / Inbox / Edit // dashboard access, with `access` on each GET /api/v2/guilds entry and GET/POST // /api/v2/guilds/:id/access. `message-move`: a posted message moves to its new channel on publish. +// `public-page-look`: GET/POST /api/v2/guilds/:id/public-page-look (the server's accent colour and background +// on its public member pages), its picture upload and the invite-background check. const FEATURES = Object.freeze([ 'app-login', 'live-access', @@ -328,6 +330,7 @@ const FEATURES = Object.freeze([ 'duplicate', 'message-templates', 'message-move', + 'public-page-look', ]); // Public and ahead of the open-mode guard: the app calls it before anyone signs in, and an open-mode diff --git a/src/web/routes/publicLook.js b/src/web/routes/publicLook.js new file mode 100644 index 00000000..4e8e9415 --- /dev/null +++ b/src/web/routes/publicLook.js @@ -0,0 +1,66 @@ +// The look of a server's public pages as files: its style sheet (/look/..css) and the picture of +// its background (/look/..webp). Mounted in server.js BEFORE the session and CSRF middleware, with +// its own rate limit, like the collectible pictures: a request here never starts a session and the answer +// carries no cookie, so any cache may keep it. +// +// Both addresses are guild-scoped and named by a content hash. The style sheet is only served while the hash is +// the one of the server's current look (so an old address is a plain 404, never a stale look), and the picture +// is looked up in THIS server's own pictures by its hash, never by a path. Anything else gets the same plain 404 +// with no detail. The files are immutable: a change is a new address. +// +// The style sheet holds custom properties only (lib/publicLook.js) and the picture is a WebP Sylo made, so the +// page's strict CSP stays as it is: styles and images from this site only. +import { Router } from 'express'; +import { keyOfSlug } from '../../lib/publicLook.js'; +import { readLookImage } from '../../db/publicLook.js'; +import { cssFor } from '../lib/publicLook.js'; + +const URL_RE = /^\/look\/([a-z0-9-]{1,32})\.([0-9a-f]{16})\.(css|webp)$/; + +const notFound = (res) => + res + .status(404) + .set({ 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' }) + .type('text/plain') + .send('Not found'); + +const FILE_HEADERS = { + 'Cache-Control': 'public, max-age=31536000, immutable', + 'X-Content-Type-Options': 'nosniff', + 'Content-Security-Policy': "default-src 'none'; sandbox", + 'Cross-Origin-Resource-Policy': 'same-origin', + 'Referrer-Policy': 'no-referrer', + 'X-Robots-Tag': 'noindex, nofollow', +}; + +const router = Router(); + +router.get('/:file', async (req, res, next) => { + try { + const match = URL_RE.exec(String(req.originalUrl).split('?')[0]); + const key = match && keyOfSlug(match[1]); + if (!key) return notFound(res); + const [hash, kind] = [match[2], match[3]]; + if (kind === 'css') { + const css = await cssFor(key, hash); + if (css == null) return notFound(res); + res.set({ ...FILE_HEADERS, 'Content-Type': 'text/css; charset=utf-8' }); + return res.send(css); + } + const image = await readLookImage(key, hash); + if (!image) return notFound(res); + res.set({ + ...FILE_HEADERS, + 'Content-Type': image.mime, + 'Content-Length': String(image.data.length), + }); + return res.end(image.data); + } catch (err) { + return next(err); + } +}); + +// Everything else under /look answers the same plain 404, not the dashboard's login redirect. +router.use((_req, res) => notFound(res)); + +export default router; diff --git a/src/web/routes/quotes.js b/src/web/routes/quotes.js index 170087d8..fd679820 100644 --- a/src/web/routes/quotes.js +++ b/src/web/routes/quotes.js @@ -9,6 +9,7 @@ // from a channel that has become private since (re-checked when the page is drawn, see // nowPrivateChannels). import { Router } from 'express'; +import { lookFor } from '../lib/publicLook.js'; import { guildByKey } from '../../platform/platformOf.js'; import { isPlatformGuildId } from '../../lib/platformId.js'; import { getGuildModule } from '../../db/modules.js'; @@ -86,6 +87,7 @@ router.get('/:guildId', async (req, res, next) => { limit: PAGE_SIZE, }); + res.locals.look = await lookFor(guildId); res.render('quotes', { guild: { name: guild.name, icon: guild.iconURL?.({ size: 64 }) ?? null }, quotes: rows.map((r) => ({ diff --git a/src/web/routes/v2Api.js b/src/web/routes/v2Api.js index 1db30f44..2f739ed7 100644 --- a/src/web/routes/v2Api.js +++ b/src/web/routes/v2Api.js @@ -69,6 +69,7 @@ import setupRouter from './v2Setup.js'; import applyMemberRouter from './v2Apply.js'; import economyRouter from './v2Economy.js'; import shopRouter from './v2Shop.js'; +import publicLookRouter from './v2PublicLook.js'; import shopMemberRouter from './v2ShopMember.js'; import { cancelIntroductionSessions } from '../../modules/introductions.js'; import { cancelApplicationSessions } from '../../modules/applications.js'; @@ -549,6 +550,8 @@ router.use('/guilds/:guildId', introRouter); router.use('/guilds/:guildId', economyRouter); // Economy shop: items, a member's inventory, the activity log (v2Shop.js). router.use('/guilds/:guildId', shopRouter); +// The server's own look on the public member pages: accent colour and background (v2PublicLook.js). +router.use('/guilds/:guildId', publicLookRouter); // Applications: settings, forms, the panel, submissions, export (v2Applications.js). router.use('/guilds/:guildId', applicationsRouter); // Setup wizard: the proposal for the server and applying it (v2Setup.js). diff --git a/src/web/routes/v2Apply.js b/src/web/routes/v2Apply.js index a1b50865..f7392094 100644 --- a/src/web/routes/v2Apply.js +++ b/src/web/routes/v2Apply.js @@ -20,6 +20,7 @@ import { asyncHandler } from '../lib/asyncHandler.js'; import { guildByKey, guildKey } from '../../platform/platformOf.js'; import { isPlatformGuildId, splitPlatformGuildId } from '../../lib/platformId.js'; import { identityFor } from '../lib/accountAuth.js'; +import { lookRef } from '../lib/publicLook.js'; import { isModuleEnabled } from '../../db/modules.js'; import { pendingSubmission } from '../../db/applications.js'; import { @@ -108,9 +109,12 @@ const publicQuestion = (q) => ({ /** The page's data: the form and its questions, or why this member cannot fill it in now. */ async function formView({ guild, key, member, form, own, limited }) { + // the server's own look (accent colour, background), see lib/publicLook.js + const look = await lookRef(key); if (limited) { return { guild: { name: guild.name, id: key }, + look, viewer: member.id, form: { id: own.formId, name: own.formName, description: '', version: 0, intro: '' }, pending: { id: own.id, createdAt: own.createdAt }, @@ -125,6 +129,7 @@ async function formView({ guild, key, member, form, own, limited }) { const pending = await pendingSubmission(key, form.id, member.id); const base = { guild: { name: guild.name, id: key }, + look, // whose draft the page may restore (drafts are kept in the browser, per person) viewer: member.id, form: { diff --git a/src/web/routes/v2PublicLook.js b/src/web/routes/v2PublicLook.js new file mode 100644 index 00000000..495874a8 --- /dev/null +++ b/src/web/routes/v2PublicLook.js @@ -0,0 +1,168 @@ +// JSON API for Server settings → Public pages: the server's own look on the pages its members open without the +// dashboard (the application form, the ban appeal, the event and quote pages, the web shop). An accent colour and +// a background, nothing else: the layout, the type, the components and the "Powered by Sylo" link stay Sylo's. +// +// Mounted at /guilds/:guildId AFTER the admin guard in v2Api.js, so req.guild is set. Every route here needs the +// Edit level (src/web/lib/routeAccess.js), the reads too; writes have passed the CSRF check. +// +// The background picture goes through the collectible pictures' pipeline (lib/collectibleImage.js): at most 2 MB, +// the kind decided by the first bytes, the size read from the header before anything is decoded, at most two +// decodes at a time, and a new WebP is stored, so what was uploaded (and its metadata) is never kept. The +// choice 'discord-splash' uses a copy of the server's invite splash that Sylo downloads itself. +import { accessRouter } from '../middleware/access.js'; +import { currentUser } from '../middleware/auth.js'; +import { clientKey, rateLimit } from '../middleware/rateLimit.js'; +import { asyncHandler } from '../lib/asyncHandler.js'; +import { recordAudit } from '../../db/audit.js'; +import { + BACKGROUND_MAX_SIDE, + BACKGROUND_QUALITY, + deleteLookImage, + getLookImageMeta, + getPublicLook, + putLookImage, + setPublicLook, +} from '../../db/publicLook.js'; +import { ImageError, processImage, readUpload } from '../../lib/collectibleImage.js'; +import { BACKGROUNDS, imageHashOf, normaliseAccent } from '../../lib/publicLook.js'; +import { hasSplash, lookView, refreshSplash } from '../lib/publicLook.js'; + +const router = accessRouter('/guilds/:guildId', { mergeParams: true }); + +const actor = (req) => (currentUser(req)?.open ? 'Dashboard' : `${currentUser(req).name} (dashboard)`); +const fail = (res, message, status = 400) => res.status(status).json({ error: message }); + +const uploadLimit = rateLimit({ + windowMs: 60_000, + max: 20, + message: 'Too many uploads: wait a minute and try again.', + keyFn: (req) => `look-image|${req.params?.guildId ?? ''}|${clientKey(req)}`, +}); +const splashLimit = rateLimit({ + windowMs: 60_000, + max: 6, + message: 'Too many checks: wait a minute and try again.', + keyFn: (req) => `look-splash|${req.params?.guildId ?? ''}|${clientKey(req)}`, +}); + +const send = async (res, req) => res.json(await lookView(req.guild, req.guild.id)); + +router.get( + '/public-page-look', + asyncHandler(async (req, res) => send(res, req)) +); + +router.post( + '/public-page-look', + asyncHandler(async (req, res) => { + const guildId = req.guild.id; + const accent = normaliseAccent(req.body?.accent); + if (accent === null) return fail(res, 'The accent colour must look like #5865f2.'); + const background = String(req.body?.background ?? 'none'); + if (!BACKGROUNDS.includes(background)) + return fail(res, 'Choose no background, an upload or the invite background.'); + + if (background === 'upload' && !(await getLookImageMeta(guildId, 'upload'))) { + return fail(res, 'Upload a picture first, or choose another background.'); + } + if (background === 'discord-splash') { + if (!hasSplash(req.guild)) { + return fail( + res, + 'This server has no invite background. Set one in the server settings, or choose another.' + ); + } + const out = await refreshSplash(req.guild, { force: true }); + if (out.status === 'failed' || out.status === 'none') { + return fail( + res, + out.message ?? 'The invite background could not be downloaded. Try again in a moment.', + 502 + ); + } + } + + const before = await getPublicLook(guildId); + await setPublicLook(guildId, { accent, background }); + await recordAudit(guildId, { + actor: actor(req), + action: 'settings:public-look', + detail: + before.accent === accent && before.background === background + ? 'public page look saved' + : `public page look: accent ${accent || 'Sylo default'}, background ${background}`, + }); + return send(res, req); + }) +); + +router.post( + '/public-page-look/image', + uploadLimit, + asyncHandler(async (req, res) => { + const guildId = req.guild.id; + let picture; + try { + picture = await processImage(await readUpload(req), { + owner: guildId, + maxSide: BACKGROUND_MAX_SIDE, + quality: BACKGROUND_QUALITY, + }); + } catch (err) { + if (err instanceof ImageError) return fail(res, err.message, err.status); + throw err; + } + await putLookImage(guildId, 'upload', { + hash: imageHashOf(picture.data), + mime: picture.mime, + data: picture.data, + }); + await recordAudit(guildId, { + actor: actor(req), + action: 'settings:public-look', + detail: 'uploaded a background picture for the public pages', + }); + return send(res, req); + }) +); + +router.post( + '/public-page-look/image/delete', + asyncHandler(async (req, res) => { + const guildId = req.guild.id; + const had = await deleteLookImage(guildId, 'upload'); + if (had) { + const look = await getPublicLook(guildId); + // A background that points at a picture that is gone is none. + if (look.background === 'upload') + await setPublicLook(guildId, { accent: look.accent, background: 'none' }); + await recordAudit(guildId, { + actor: actor(req), + action: 'settings:public-look', + detail: 'removed the uploaded background picture', + }); + } + return send(res, req); + }) +); + +// Check the invite background against the platform now (otherwise it is checked once a day, when a page that +// uses it is opened). A changed splash is downloaded again; one the server no longer has is dropped. +router.post( + '/public-page-look/splash/refresh', + splashLimit, + asyncHandler(async (req, res) => { + const out = await refreshSplash(req.guild, { force: true }); + if (out.status === 'none') { + const look = await getPublicLook(req.guild.id); + if (look.background === 'discord-splash') { + await setPublicLook(req.guild.id, { accent: look.accent, background: 'none' }); + } + } + if (out.status === 'failed') + return fail(res, out.message ?? 'The invite background could not be downloaded.', 502); + return send(res, req); + }) +); + +export default router; diff --git a/src/web/routes/v2ShopMember.js b/src/web/routes/v2ShopMember.js index 69ea549a..e78fc580 100644 --- a/src/web/routes/v2ShopMember.js +++ b/src/web/routes/v2ShopMember.js @@ -17,6 +17,7 @@ import { asyncHandler } from '../lib/asyncHandler.js'; import { guildByKey, guildKey } from '../../platform/platformOf.js'; import { isPlatformGuildId, splitPlatformGuildId } from '../../lib/platformId.js'; import { identityFor } from '../lib/accountAuth.js'; +import { lookRef } from '../lib/publicLook.js'; import { getGuildModule } from '../../db/modules.js'; import { collectionPage, listInventory, listItems } from '../../db/economyShop.js'; import { rarityLabel } from '../../modules/lib/collectibles.js'; @@ -120,6 +121,8 @@ async function shopView({ guild, key, member, config }) { } return { guild: { name: guild.name, id: key }, + // the server's own look (accent colour, background), see lib/publicLook.js + look: await lookRef(key), currency: { name: config.currencyName, emoji: config.currencyEmoji }, balance: { cash: bal.cash, bank: bal.bank, total: bal.total }, items: items.map((i) => { diff --git a/src/web/server.js b/src/web/server.js index ed602ba0..d6f7e5fa 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -25,6 +25,7 @@ import quotesRouter from './routes/quotes.js'; import economyBoardRouter from './routes/economyBoard.js'; import eventPageRouter from './routes/events.js'; import collectibleImageRouter from './routes/collectibleImage.js'; +import publicLookRouter from './routes/publicLook.js'; import verifyRouter from './routes/verify.js'; import appealRouter from './routes/appeal.js'; import githubWebhookRouter from './routes/githubWebhook.js'; @@ -195,6 +196,8 @@ export function createApp() { // ahead of the session and the CSRF check, so an answer never carries a cookie (it is cacheable by anyone). // Its own limit, higher than the pages below: one collection page shows up to ten pictures, fetched in a burst. app.use('/c', rateLimit({ windowMs: 60_000, max: 240 }), collectibleImageRouter); + // The look of a server's public pages (style sheet and background picture): no login, named by content hash. + app.use('/look', rateLimit({ windowMs: 60_000, max: 240 }), publicLookRouter); // Per-client ceiling on everything below. It runs ahead of the body parsers: a request whose // body fails to parse (too large, broken JSON) is answered by the parser's own error, so a // limiter behind them would never count it. Generous for normal clicking, but stops a stuck diff --git a/src/web/views/appeal.ejs b/src/web/views/appeal.ejs index 9323aaf1..7849699e 100644 --- a/src/web/views/appeal.ejs +++ b/src/web/views/appeal.ejs @@ -6,8 +6,9 @@ Ban appeal — Sylo +<%- include('partials/look') %> - +>
Sylo
@@ -73,7 +74,7 @@

<%= message %>

<% } %>
-

Powered by Sylo

+<%- include('partials/powered', { cls: 'lb-foot' }) %>
diff --git a/src/web/views/economy-leaderboard.ejs b/src/web/views/economy-leaderboard.ejs index 5466c725..fea0ef7f 100644 --- a/src/web/views/economy-leaderboard.ejs +++ b/src/web/views/economy-leaderboard.ejs @@ -6,8 +6,9 @@ <%= guild.name %> — Economy leaderboard +<%- include('partials/look') %> - +>
Sylo
@@ -45,7 +46,7 @@ <% } %> <% } %> -

Powered by Sylo

+<%- include('partials/powered', { cls: 'lb-foot' }) %>
diff --git a/src/web/views/event-missing.ejs b/src/web/views/event-missing.ejs index 176765e0..09288586 100644 --- a/src/web/views/event-missing.ejs +++ b/src/web/views/event-missing.ejs @@ -21,7 +21,7 @@

No event here

<%= message %>

-

Powered by Sylo

+<%- include('partials/powered', { cls: 'auth-foot' }) %> diff --git a/src/web/views/event-signin.ejs b/src/web/views/event-signin.ejs index 63e3c0b9..484a384c 100644 --- a/src/web/views/event-signin.ejs +++ b/src/web/views/event-signin.ejs @@ -26,7 +26,7 @@ Sign in with <%= label %> -

Powered by Sylo

+<%- include('partials/powered', { cls: 'auth-foot' }) %> diff --git a/src/web/views/event.ejs b/src/web/views/event.ejs index e058e4a2..e8fc6c73 100644 --- a/src/web/views/event.ejs +++ b/src/web/views/event.ejs @@ -59,7 +59,7 @@ <% } %> -

Powered by Sylo

+<%- include('partials/powered', { cls: 'lb-foot' }) %> diff --git a/src/web/views/leaderboard.ejs b/src/web/views/leaderboard.ejs index 1b667b0b..75848b5c 100644 --- a/src/web/views/leaderboard.ejs +++ b/src/web/views/leaderboard.ejs @@ -7,8 +7,9 @@ <% if (typeof canonical !== 'undefined' && canonical) { %><% } %> +<%- include('partials/look') %> - +>
Sylo
@@ -64,7 +65,7 @@ <% } %> <% } %> -

Powered by Sylo

+<%- include('partials/powered', { cls: 'lb-foot' }) %>
diff --git a/src/web/views/partials/auth-foot.ejs b/src/web/views/partials/auth-foot.ejs index 4bdd5b39..b42ac962 100644 --- a/src/web/views/partials/auth-foot.ejs +++ b/src/web/views/partials/auth-foot.ejs @@ -1,7 +1,7 @@ <%# `publicPage: true` is the footer of the pages a member sees (the same line as the leaderboard, quotes, event, verify and appeal pages); otherwise the dashboard-side footer with the version. %> <% if (typeof publicPage !== 'undefined' && publicPage) { %> -

Powered by Sylo

+ <%- include('powered', { cls: 'auth-foot' }) %> <% } else { %>

Sylo<% if (typeof syloVersion !== 'undefined' && syloVersion) { %> v<%= syloVersion %><% } %> diff --git a/src/web/views/partials/look.ejs b/src/web/views/partials/look.ejs new file mode 100644 index 00000000..3376284f --- /dev/null +++ b/src/web/views/partials/look.ejs @@ -0,0 +1,3 @@ +<%# The look of one server's public pages: its style sheet (custom properties only: the accent colour and the + background picture, see src/lib/publicLook.js). Loaded after public.css. Nothing when the server chose no look. %> + <% if (typeof look !== 'undefined' && look) { %><% } %> diff --git a/src/web/views/partials/powered.ejs b/src/web/views/partials/powered.ejs new file mode 100644 index 00000000..2c085d98 --- /dev/null +++ b/src/web/views/partials/powered.ejs @@ -0,0 +1,3 @@ +<%# The "Powered by Sylo" line at the bottom of every public page. Always shown and not configurable: a + server's look (accent colour, background) never touches it. Local: `cls`, the footer's class. %> +

Powered by Sylo

diff --git a/src/web/views/quotes.ejs b/src/web/views/quotes.ejs index 4535d937..423f56b0 100644 --- a/src/web/views/quotes.ejs +++ b/src/web/views/quotes.ejs @@ -7,8 +7,9 @@ <%= guild.name %> — Quotes +<%- include('partials/look') %> - +>
Sylo
@@ -43,7 +44,7 @@ <% } %> <% } %> -

Powered by Sylo

+<%- include('partials/powered', { cls: 'lb-foot' }) %>
diff --git a/src/web/views/verify.ejs b/src/web/views/verify.ejs index 7ec7bfdf..feef32ed 100644 --- a/src/web/views/verify.ejs +++ b/src/web/views/verify.ejs @@ -35,7 +35,7 @@

<%= message %>

<% } %> -

Powered by Sylo

+<%- include('partials/powered', { cls: 'lb-foot' }) %> diff --git a/test/eventPages.public.test.js b/test/eventPages.public.test.js index 77be2aab..711a8a57 100644 --- a/test/eventPages.public.test.js +++ b/test/eventPages.public.test.js @@ -264,6 +264,11 @@ test('an event past its end is ended even before the clock tick has closed it', assert.match(await page(running), /ev-badge ev-upcoming">UpcomingPowered by Sylo<\/a>/; + test('no host, no member, no role, no channel and no id of any kind', async () => { const html = await page(ev); for (const secret of [HOST, ...MEMBERS, '100000000000000700', CH.general, GID]) { @@ -272,7 +277,8 @@ test('no host, no member, no role, no channel and no id of any kind', async () = assert.doesNotMatch(html, /\b\d{17,20}\b/, 'nothing that looks like a snowflake'); assert.doesNotMatch(html, /user-\d{4}/, 'no display names or tags'); assert.doesNotMatch(html, /<@|<#|host|Host|participant|Participant/i); - assert.doesNotMatch(html, /]*href="https?:/i, 'no outward links'); + assert.match(html, POWERED_BY); + assert.doesNotMatch(html.replace(POWERED_BY, ''), /]*href="https?:/i, 'no outward links but one'); assert.doesNotMatch(html, new RegExp(`#${ev.id}\\b`), 'not even the event number'); }); @@ -313,7 +319,7 @@ test('the page holds no third-party address and no id: the icon and the image ar const html = await page(withImage); assert.ok(html.includes(`src="/events/${withImage.public_token}/icon"`), 'the icon through Sylo'); assert.ok(html.includes(`src="/events/${withImage.public_token}/image"`), 'the image through Sylo'); - assert.doesNotMatch(html, /https?:\/\//, 'no address of anyone else'); + assert.doesNotMatch(html.replace(POWERED_BY, ''), /https?:\/\//, 'no address of anyone else'); assert.doesNotMatch(html, /discordapp/); assert.doesNotMatch(html, /\b\d{17,20}\b/, 'none of the ids in the image links'); assert.ok(!html.includes(GID) && !html.includes(CH.general) && !html.includes('100000000000000042')); diff --git a/test/mobileInfo.test.js b/test/mobileInfo.test.js index efba5685..3e2167cd 100644 --- a/test/mobileInfo.test.js +++ b/test/mobileInfo.test.js @@ -51,6 +51,7 @@ test('GET /api/mobile/info describes a server with login on, without a cookie or assert.ok(info.features.includes(f), f); } assert.ok(info.features.includes('message-move'), 'a posted message moves when its channel changes'); + assert.ok(info.features.includes('public-page-look'), 'the server look on public pages'); assert.ok(info.features.every((f) => typeof f === 'string')); }); diff --git a/test/publicLook.lib.test.js b/test/publicLook.lib.test.js new file mode 100644 index 00000000..5c4db933 --- /dev/null +++ b/test/publicLook.lib.test.js @@ -0,0 +1,136 @@ +// The pure rules of a server's look on its public pages (src/lib/publicLook.js): what counts as an accent colour, +// the contrast check against the card in both themes with the fallback to Sylo's own colour, and the style sheet, +// which may carry custom properties only. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + CARD, + MIN_CONTRAST, + SYLO_ACCENT, + accentCheck, + contrast, + effectiveAccent, + fallbackNote, + keyOfSlug, + lookCss, + lookHash, + normaliseAccent, + onAccent, + slugOf, +} from '../src/lib/publicLook.js'; + +test('an accent is #rgb or #rrggbb, with or without the hash, in any case; empty is none; the rest is refused', () => { + assert.equal(normaliseAccent('#5865F2'), '#5865f2'); + assert.equal(normaliseAccent('5865f2'), '#5865f2'); + assert.equal(normaliseAccent(' #abc '), '#aabbcc'); + assert.equal(normaliseAccent(''), ''); + assert.equal(normaliseAccent(null), ''); + assert.equal(normaliseAccent(undefined), ''); + for (const bad of [ + 'red', + '#12', + '#12345', + '#1234567', + '#gggggg', + 'rgb(1,2,3)', + 'url(x)', + '#fff;}body{display:none', + "#fff' onload='x", + {}, + ['#fff'], + ]) { + assert.equal(normaliseAccent(bad), null, JSON.stringify(bad)); + } +}); + +test('contrast is the WCAG ratio', () => { + assert.equal(Math.round(contrast('#000000', '#ffffff')), 21); + assert.equal(contrast('#777777', '#777777'), 1); + assert.ok(contrast('#ffffff', '#767676') > 4.5 && contrast('#ffffff', '#767676') < 4.6); +}); + +test("an accent is checked against the card of each theme; where it is too faint Sylo's own colour is used", () => { + // Sylo's own colours pass on their card. + assert.deepEqual(accentCheck('').fallback, []); + assert.ok(contrast(SYLO_ACCENT.dark, CARD.dark) >= MIN_CONTRAST); + assert.ok(contrast(SYLO_ACCENT.light, CARD.light) >= MIN_CONTRAST); + // A deep blue reads on the white card but not on the dark one; a pale yellow the other way round. + const blue = accentCheck('#1a2a6c'); + assert.deepEqual(blue.fallback, ['dark']); + assert.equal(blue.light.ok, true); + const yellow = accentCheck('#ffe14d'); + assert.deepEqual(yellow.fallback, ['light']); + assert.equal(yellow.dark.ok, true); + // A mid-tone such as Discord's blurple reads on both cards. No colour reaches 4.5:1 on both, so 3:1 is the bar. + assert.deepEqual(accentCheck('#5865f2').fallback, []); + assert.ok(!(contrast('#5865f2', CARD.dark) >= 4.5 && contrast('#5865f2', CARD.light) >= 4.5)); + + assert.deepEqual(effectiveAccent('#1a2a6c'), { dark: SYLO_ACCENT.dark, light: '#1a2a6c' }); + assert.deepEqual(effectiveAccent('#ffe14d'), { dark: '#ffe14d', light: SYLO_ACCENT.light }); + assert.deepEqual(effectiveAccent(''), SYLO_ACCENT); + + assert.match(fallbackNote('#1a2a6c'), /too hard to read on the card/); + assert.match(fallbackNote('#1a2a6c'), /the dark theme/); + assert.match(fallbackNote('#1a2a6c'), /Sylo's own colour/); + assert.equal(fallbackNote('#5865f2'), null, 'a readable accent needs no note'); + assert.equal(fallbackNote(''), null); +}); + +test('the text on an accent fill is white or near-black, whichever reads better', () => { + assert.equal(onAccent('#ffe14d'), '#000000'); + assert.equal(onAccent('#1a2a6c'), '#ffffff'); + for (const c of ['#5865f2', '#ff0000', '#00ff00', '#808080', '#787878', '#123456', '#fedcba']) { + assert.ok(contrast(c, onAccent(c)) >= 4.5, c); + } +}); + +test('the style sheet holds custom properties only, and the accent only in the themes where it is readable', () => { + const both = lookCss({ accent: '#5865f2', imageUrl: null }); + assert.match(both, /:root \{ --accent: #5865f2; --on-accent: #ffffff; \}/); + assert.match(both, /:root\[data-theme='light'\] \{ --accent: #5865f2;/); + assert.doesNotMatch(both, /--look-image/); + + const darkOnly = lookCss({ accent: '#ffe14d', imageUrl: null }); + assert.match(darkOnly, /:root \{ --accent: #ffe14d;/); + assert.doesNotMatch(darkOnly, /data-theme/); + + const lightOnly = lookCss({ accent: '#1a2a6c', imageUrl: null }); + assert.doesNotMatch(lightOnly, /^:root \{/m, "too dark for the dark card: Sylo's own colour stays there"); + assert.match(lightOnly, /data-theme='light'\] \{ --accent: #1a2a6c/); + + const image = lookCss({ accent: '', imageUrl: '/look/123456789012345678.0123456789abcdef.webp' }); + assert.doesNotMatch(image, /--accent/); + assert.match(image, /--look-image: url\('\/look\/123456789012345678\.0123456789abcdef\.webp'\)/); + // Only custom properties: no selector other than :root, nothing but "--name: value" inside. + for (const css of [both, darkOnly, lightOnly, image]) { + for (const line of css.split('\n').filter((l) => l && !l.startsWith('/*'))) { + assert.match(line, /^:root(\[data-theme='light'\])? \{( --[a-z-]+: [^;{}]+;)+ \}$/, line); + } + } + for (const url of [ + 'https://evil.example/x.webp', + "/look/x');}body{x:y", + '/look/../../etc.webp', + '//evil/x.webp', + ]) { + assert.throws(() => lookCss({ accent: '', imageUrl: url }), /bad look image address/, url); + } +}); + +test('the hash of a look changes with the accent and the picture, and not otherwise', () => { + const a = lookHash({ accent: '#0a5c36', imageHash: '' }); + assert.match(a, /^[0-9a-f]{16}$/); + assert.equal(lookHash({ accent: '#0a5c36', imageHash: '' }), a); + assert.notEqual(lookHash({ accent: '#0a5c37', imageHash: '' }), a); + assert.notEqual(lookHash({ accent: '#0a5c36', imageHash: 'abc' }), a); +}); + +test('a server key is a slug in an address and back; anything else is not a key', () => { + assert.equal(slugOf('900000000000000123'), '900000000000000123'); + assert.equal(slugOf('fluxer:123'), 'fluxer-123'); + assert.equal(keyOfSlug('900000000000000123'), '900000000000000123'); + assert.equal(keyOfSlug('fluxer-123'), 'fluxer:123'); + for (const bad of ['', 'x', 'fluxer-', 'discord-1', '../1', '1/2', 'FLUXER-1', '1'.repeat(26)]) { + assert.equal(keyOfSlug(bad), null, bad); + } +}); diff --git a/test/publicLook.web.test.js b/test/publicLook.web.test.js new file mode 100644 index 00000000..9db4b5ef --- /dev/null +++ b/test/publicLook.web.test.js @@ -0,0 +1,420 @@ +// A server's own look on its public member pages through the dashboard API and the public files: the upload +// (limits, kind by magic bytes, metadata gone, a re-encoded WebP), the invite splash (a copy Sylo downloads from a +// fake CDN and serves itself), the style sheet and picture addresses (guild-scoped, named by hash, immutable, no +// cookie, a plain 404 for everything else), the contrast fallback, what the public pages render (the accent, the +// background, always the "Powered by Sylo" link) and what the purge removes. Who may change it (Edit only, on the +// web and in the app, across servers) is in v2.accessLevels.test.js. +process.env.ALLOW_PRIVATE_URLS = 'true'; // the fake CDN below listens on 127.0.0.1 +import test, { beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; + +const { startWebApp } = await import('./helpers/webApp.js'); +const { v2Open, auditRows } = await import('./helpers/v2Open.js'); +const { GID } = await import('./helpers/fakeGuild.js'); +const { makePicture, pngClaiming, upload, HTML, SVG } = await import('./helpers/collectibleFixtures.js'); +const { db } = await import('../src/db/index.js'); +const { purgeGuild } = await import('../src/db/purge.js'); +const { setGuildModule } = await import('../src/db/modules.js'); +const { signAppealToken } = await import('../src/modules/appeals.js'); +const { imageDimensions } = await import('../src/lib/imageSize.js'); +const { refreshSplash, SPLASH_REFRESH_MS, lookRef, _resetSplashRetry } = + await import('../src/web/lib/publicLook.js'); +const { getLookImageMeta, getPublicLook, putLookImage, setPublicLook } = + await import('../src/db/publicLook.js'); +const { imageHashOf } = await import('../src/lib/publicLook.js'); + +let app; +let api; +let cdn; +let cdnHits = 0; +let cdnBody; +let cdnStatus = 200; +const USER = '444444444444444444'; +const OTHER = '900000000000000777'; + +test.before(async () => { + app = await startWebApp(); + api = v2Open(app, GID); + cdn = await new Promise((resolve) => { + const s = http.createServer((req, res) => { + cdnHits += 1; + res.writeHead(cdnStatus, { 'content-type': 'image/webp' }); + res.end(cdnBody); + }); + s.listen(0, '127.0.0.1', () => resolve(s)); + }); + app.guild.splashURL = () => `http://127.0.0.1:${cdn.address().port}/splash.webp`; +}); +test.after(() => { + cdn.closeAllConnections?.(); + cdn.close(); + app.close(); +}); +beforeEach(async () => { + await purgeGuild(GID); + await purgeGuild(OTHER); + app.guild.splash = null; + cdnHits = 0; + cdnStatus = 200; + _resetSplashRetry(); +}); + +const json = (res) => res.json(); +const get = (path) => fetch(`${app.base}${path}`); +const putFile = (form) => + fetch(`${app.base}/api/v2/guilds/${GID}/public-page-look/image`, { method: 'POST', body: form }); +const save = (body) => api.post('/public-page-look', body); +const rows = () => + db + .prepare('SELECT source, hash, mime, bytes, origin FROM public_look_images WHERE guild_id = ?') + .all(GID) + .map((r) => ({ ...r })); +const view = async () => json(await api.get('/public-page-look')); +const pic = (w, h, format = 'png') => makePicture(w, h, format); +const hashOf = (path) => /\.([0-9a-f]{16})\.(css|webp)$/.exec(path)[1]; + +/** A JPEG with an EXIF segment (a made-up GPS note) and bytes appended after the picture, like a phone photo. */ +async function jpegWithMetadata() { + const jpeg = await pic(300, 200, 'jpeg'); + const body = Buffer.from('Exif\0\0SECRET-GPS-NOTE-48.8584N-2.2945E'); + const segment = Buffer.concat([Buffer.from([0xff, 0xe1, 0, body.length + 2]), body]); + return Buffer.concat([jpeg.subarray(0, 2), segment, jpeg.subarray(2), Buffer.from('TRAILING-SECRET')]); +} + +test('a server that chose nothing has the plain Sylo look, and the view says what is on offer', async () => { + const v = await view(); + assert.equal(v.accent, ''); + assert.equal(v.background, 'none'); + assert.equal(v.upload, null); + assert.deepEqual(v.splash, { available: false, copied: null }); + assert.equal(v.effective.css, null); + assert.equal(v.effective.backgroundUrl, null); + assert.deepEqual(v.effective.fallback, []); + assert.equal(v.effective.note, null); + assert.equal(v.platform, 'discord'); + assert.equal(v.limits.maxBytes, 2 * 1024 * 1024); +}); + +test('saving an accent and a background: checked, stored, audited, and the style sheet follows', async () => { + const bad = await save({ accent: 'red', background: 'none' }); + assert.equal(bad.status, 400); + assert.match((await json(bad)).error, /#5865f2/); + assert.equal((await save({ accent: '#5865f2', background: 'sparkles' })).status, 400); + assert.equal((await save({ accent: '#5865f2', background: 'upload' })).status, 400, 'no picture yet'); + assert.equal((await save({ accent: '#5865f2', background: 'discord-splash' })).status, 400, 'no splash'); + assert.deepEqual(await getPublicLook(GID), { accent: '', background: 'none', updatedAt: 0 }); + + const ok = await save({ accent: '#5865F2', background: 'none' }); + assert.equal(ok.status, 200); + const v = await json(ok); + assert.equal(v.accent, '#5865f2'); + assert.match(v.effective.css, new RegExp(`^/look/${GID}\\.[0-9a-f]{16}\\.css$`)); + const css = await get(v.effective.css); + assert.equal(css.status, 200); + assert.match(css.headers.get('content-type'), /^text\/css/); + assert.equal(css.headers.get('cache-control'), 'public, max-age=31536000, immutable'); + assert.equal(css.headers.get('x-content-type-options'), 'nosniff'); + assert.equal(css.headers.get('set-cookie'), null, 'no session, no cookie'); + const text = await css.text(); + assert.match(text, /--accent: #5865f2/); + assert.doesNotMatch(text, /--look-image/); + assert.equal((await auditRows(GID, 'settings:public-look')).length, 1); + + // Clearing both gives the plain look back, and the old style sheet address is gone. + const old = v.effective.css; + const cleared = await json(await save({ accent: '', background: 'none' })); + assert.equal(cleared.effective.css, null); + assert.equal((await get(old)).status, 404, 'a stale address is a 404, never a stale look'); +}); + +test("an accent that is too hard to read on the card falls back to Sylo's colour, and the answer says so", async () => { + const v = await json(await save({ accent: '#ffe14d', background: 'none' })); + assert.deepEqual(v.effective.fallback, ['light']); + assert.match(v.effective.note, /too hard to read on the card in the light theme/); + assert.equal(v.effective.accent.dark, '#ffe14d'); + assert.equal(v.effective.accent.light, v.sylo.accent.light); + const css = await (await get(v.effective.css)).text(); + assert.match(css, /^:root \{ --accent: #ffe14d;/m); + assert.doesNotMatch(css, /data-theme/, "the light theme keeps Sylo's own colour"); + + const dark = await json(await save({ accent: '#1a2a6c', background: 'none' })); + assert.deepEqual(dark.effective.fallback, ['dark']); + assert.match(dark.effective.note, /in the dark theme/); + const blurple = await json(await save({ accent: '#5865f2', background: 'none' })); + assert.deepEqual(blurple.effective.fallback, [], 'a mid-tone reads on both cards'); + assert.equal(blurple.effective.note, null); +}); + +test('an upload becomes a WebP of at most 1920 px with the metadata gone, served from Sylo by its hash', async () => { + const original = await jpegWithMetadata(); + assert.ok(original.includes('SECRET-GPS-NOTE')); + const res = await putFile(upload(original, { name: 'phone.jpg', type: 'image/jpeg' })); + assert.equal(res.status, 200); + const v = await json(res); + assert.match(v.upload.url, new RegExp(`^/look/${GID}\\.[0-9a-f]{16}\\.webp$`)); + + const [stored] = rows(); + assert.equal(stored.source, 'upload'); + assert.equal(stored.mime, 'image/webp'); + const served = await get(v.upload.url); + assert.equal(served.status, 200); + assert.equal(served.headers.get('content-type'), 'image/webp'); + assert.equal(served.headers.get('cache-control'), 'public, max-age=31536000, immutable'); + assert.equal(served.headers.get('cross-origin-resource-policy'), 'same-origin'); + assert.equal(served.headers.get('set-cookie'), null); + const body = Buffer.from(await served.arrayBuffer()); + assert.equal(imageHashOf(body), stored.hash); + assert.equal(body.toString('latin1', 0, 4), 'RIFF'); + assert.ok(!body.includes('SECRET'), 'no EXIF note and no appended bytes'); + assert.deepEqual(imageDimensions(body), { width: 300, height: 200 }); + + // A big picture is scaled down to fit in 1920 px. + const big = await json(await putFile(upload(await pic(4000, 1000)))); + const bigBody = Buffer.from(await (await get(big.upload.url)).arrayBuffer()); + assert.deepEqual(imageDimensions(bigBody), { width: 1920, height: 480 }); + // The upload does not change the choice by itself. + assert.equal(big.background, 'none'); +}); + +test('the upload refuses what is not a picture, what is too large and what claims too many pixels', async () => { + const refuse = async (form, status, text) => { + const res = await putFile(form); + assert.equal(res.status, status, String(text)); + assert.match((await json(res)).error, text); + assert.equal(rows().length, 0, 'nothing stored'); + }; + await refuse(upload(SVG, { name: 'x.svg', type: 'image/svg+xml' }), 400, /PNG, JPEG or WebP/); + await refuse(upload(HTML, { name: 'x.png', type: 'image/png' }), 400, /PNG, JPEG or WebP/); + await refuse(upload(pngClaiming(30000, 30000)), 400, /too large in pixels/); + const huge = Buffer.concat([pngClaiming(10, 10), Buffer.alloc(2 * 1024 * 1024)]); + await refuse(upload(huge), 413, /larger than 2 MB/); + const noField = new FormData(); + noField.append('other', new Blob(['x']), 'x.png'); + await refuse(noField, 400, /Choose an image/); + const plain = await fetch(`${app.base}/api/v2/guilds/${GID}/public-page-look/image`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: '{}', + }); + assert.equal(plain.status, 415); +}); + +test('replacing the picture deletes the old one, and removing it sets a picture background back to none', async () => { + const first = await json(await putFile(upload(await pic(64, 64, 'png')))); + const firstUrl = first.upload.url; + const second = await json(await putFile(upload(await pic(96, 48, 'png')))); + assert.notEqual(second.upload.url, firstUrl); + assert.equal(rows().length, 1, 'one picture per source: the old file is gone'); + assert.equal((await get(firstUrl)).status, 404); + assert.equal((await get(second.upload.url)).status, 200); + + const chosen = await json(await save({ accent: '#5865f2', background: 'upload' })); + const css = chosen.effective.css; + assert.equal((await get(css)).status, 200); + const v = await json(await api.post('/public-page-look/image/delete')); + assert.equal(v.upload, null); + assert.equal(v.background, 'none'); + assert.equal(rows().length, 0); + assert.equal((await get(second.upload.url)).status, 404); + assert.equal((await get(css)).status, 404, 'the old style sheet named the deleted picture'); +}); + +test('a picture background is in the style sheet with a same-origin address, and the CSP is untouched', async () => { + const up = await json(await putFile(upload(await pic(200, 100)))); + const v = await json(await save({ accent: '#5865f2', background: 'upload' })); + assert.equal(v.effective.backgroundUrl, up.upload.url); + const css = await (await get(v.effective.css)).text(); + assert.ok(css.includes(`--look-image: url('${up.upload.url}')`)); + assert.doesNotMatch(css, /https?:|\/\//, 'no other origin'); + const page = await get(`/quotes/${GID}`); + const csp = page.headers.get('content-security-policy'); + assert.match(csp, /img-src 'self' data: https:/, 'unchanged by the look'); + assert.match(csp, /style-src 'self'(;|$)/); +}); + +test('the files answer only for this server and the exact hash; everything else is the same plain 404', async () => { + const up = await json(await putFile(upload(await pic(40, 40)))); + const v = await json(await save({ accent: '#5865f2', background: 'upload' })); + const hash = hashOf(up.upload.url); + const cssHash = hashOf(v.effective.css); + // another server's address with this server's hashes + assert.equal((await get(`/look/${OTHER}.${hash}.webp`)).status, 404); + assert.equal((await get(`/look/${OTHER}.${cssHash}.css`)).status, 404); + // a server with a look of its own has its own hashes only + await setPublicLook(OTHER, { accent: '#5865f2', background: 'none' }); + assert.equal( + (await get(`/look/${OTHER}.${cssHash}.css`)).status, + 404, + 'this look names a picture it lacks' + ); + assert.equal((await get(`/look/${GID}.${cssHash}.css`)).status, 200); + for (const bad of [ + `/look/${GID}.0000000000000000.webp`, + `/look/${GID}.${hash}.png`, + `/look/${GID}.${hash}.WEBP`, + `/look/${GID}.${hash}.webp/`, + `/look/${GID}.${hash.slice(1)}.webp`, + `/look/fluxer-${GID}.${hash}.webp`, + `/look/${GID}`, + `/look/`, + `/look/..%2fx.${hash}.webp`, + ]) { + const res = await get(bad); + assert.equal(res.status, 404, bad); + assert.equal(res.headers.get('cache-control'), 'no-store', bad); + assert.equal(await res.text(), 'Not found', bad); + } +}); + +test('the invite background: a copy downloaded once from the CDN, served by Sylo, checked daily, dropped when gone', async () => { + cdnBody = await pic(800, 450, 'webp'); + app.guild.splash = 'splash-hash-1'; + const first = await view(); + assert.equal(first.splash.available, true); + assert.equal(first.splash.copied, null, 'nothing is downloaded until the server chooses it'); + assert.equal(cdnHits, 0); + + const saved = await json(await save({ accent: '', background: 'discord-splash' })); + assert.equal(cdnHits, 1); + assert.match(saved.splash.copied.url, new RegExp(`^/look/${GID}\\.[0-9a-f]{16}\\.webp$`)); + assert.equal(saved.effective.backgroundUrl, saved.splash.copied.url); + const served = await get(saved.splash.copied.url); + assert.equal(served.status, 200); + assert.deepEqual(imageDimensions(Buffer.from(await served.arrayBuffer())), { width: 800, height: 450 }); + assert.equal((await getLookImageMeta(GID, 'splash')).origin, 'splash-hash-1'); + + // The same splash on the platform: no second download, only marked as checked. + const later = Date.now() + SPLASH_REFRESH_MS + 1000; + assert.equal((await refreshSplash(app.guild, { now: later })).status, 'unchanged'); + assert.equal(cdnHits, 1); + assert.equal((await getLookImageMeta(GID, 'splash')).checkedAt, later); + + // A new splash on the platform is downloaded again and replaces the copy. + cdnBody = await pic(640, 360, 'webp'); + app.guild.splash = 'splash-hash-2'; + assert.equal((await refreshSplash(app.guild, { force: true })).status, 'updated'); + assert.equal(cdnHits, 2); + assert.equal(rows().filter((r) => r.source === 'splash').length, 1); + assert.equal((await get(saved.splash.copied.url)).status, 404, 'the old copy is gone'); + + // The explicit check route does the same job. + assert.equal((await api.post('/public-page-look/splash/refresh')).status, 200); + + // The server removes its splash: the copy goes and a splash background shows nothing. + app.guild.splash = null; + assert.equal((await refreshSplash(app.guild, { force: true })).status, 'none'); + assert.equal(rows().length, 0); + const after = await view(); + assert.equal(after.effective.backgroundUrl, null); + assert.equal(after.splash.available, false); +}); + +test('a splash that cannot be downloaded or is not a picture keeps the old copy; choosing it then is refused', async () => { + cdnBody = await pic(100, 100, 'webp'); + app.guild.splash = 'a'; + await save({ accent: '', background: 'discord-splash' }); + const before = (await getLookImageMeta(GID, 'splash')).hash; + + app.guild.splash = 'b'; + cdnStatus = 500; + assert.equal((await refreshSplash(app.guild, { force: true })).status, 'failed'); + assert.equal((await getLookImageMeta(GID, 'splash')).hash, before); + + cdnStatus = 200; + cdnBody = SVG; + const refused = await refreshSplash(app.guild, { force: true }); + assert.equal(refused.status, 'failed'); + assert.match(refused.message, /PNG, JPEG or WebP/); + assert.equal((await getLookImageMeta(GID, 'splash')).hash, before); + + // A server with no copy yet, whose splash cannot be fetched: the choice is refused and nothing is saved. + await purgeGuild(GID); + const res = await save({ accent: '#5865f2', background: 'discord-splash' }); + assert.equal(res.status, 502); + assert.equal((await getPublicLook(GID)).background, 'none'); +}); + +test('a page view of a splash server copies the splash in the background, once, and not again while it is fresh', async () => { + cdnBody = await pic(100, 100, 'webp'); + app.guild.splash = 'x'; + await setPublicLook(GID, { accent: '', background: 'discord-splash' }); + await setGuildModule(GID, 'quote-board', { enabled: true, config: { publicPage: true } }); + assert.equal((await get(`/quotes/${GID}`)).status, 200); + for (let i = 0; i < 50 && cdnHits === 0; i += 1) await new Promise((r) => setTimeout(r, 20)); + assert.equal(cdnHits, 1, 'the first view copies it'); + await new Promise((r) => setTimeout(r, 100)); + assert.equal((await get(`/quotes/${GID}`)).status, 200); + await new Promise((r) => setTimeout(r, 150)); + assert.equal(cdnHits, 1, 'a fresh copy is not downloaded again'); + const page = await (await get(`/quotes/${GID}`)).text(); + assert.match(page, /has-look has-look-image/, 'the page shows it once the copy is there'); +}); + +test('the public pages take the accent and the background, and always end with the Powered by Sylo link', async () => { + await setGuildModule(GID, 'quote-board', { enabled: true, config: { publicPage: true } }); + await setGuildModule(GID, 'appeals', { enabled: true }); + const link = /]*>Powered by Sylo<\/a>/; + + const plain = await (await get(`/quotes/${GID}`)).text(); + assert.doesNotMatch(plain, /\/look\//, 'a server with no look gets plain Sylo'); + assert.doesNotMatch(plain, /has-look/); + assert.match(plain, link); + + await json(await putFile(upload(await pic(200, 100)))); + const v = await json(await save({ accent: '#5865f2', background: 'upload' })); + + const quotes = await (await get(`/quotes/${GID}`)).text(); + assert.ok(quotes.includes(``), 'the style sheet'); + assert.match(quotes, //); + assert.ok(quotes.indexOf('/public.css') < quotes.indexOf(v.effective.css), "after Sylo's own styles"); + assert.match(quotes, link); + assert.doesNotMatch(quotes, //); + assert.match(appeal, /Appeal your ban/); + assert.match(appeal, link); + + // An invalid link does not show whose page it was: plain Sylo, but the link is still there. + const invalid = await (await get(`/appeal/${GID}?t=nonsense`)).text(); + assert.doesNotMatch(invalid, /\/look\//); + assert.match(invalid, link); + + // An accent without a picture: the class without the image. + await save({ accent: '#5865f2', background: 'none' }); + const accentOnly = await (await get(`/quotes/${GID}`)).text(); + assert.match(accentOnly, //); + assert.match(accentOnly, link); +}); + +test('the dashboard member pages (application form, web shop) get the look in their data', async () => { + assert.equal(await lookRef(GID), null); + await save({ accent: '#5865f2', background: 'none' }); + const ref = await lookRef(GID); + assert.match(ref.css, new RegExp(`^/look/${GID}\\.[0-9a-f]{16}\\.css$`)); + assert.equal(ref.image, false); + await putFile(upload(await pic(50, 50))); + await save({ accent: '#5865f2', background: 'upload' }); + assert.equal((await lookRef(GID)).image, true); +}); + +test('purging a server removes its look and both pictures', async () => { + await putFile(upload(await pic(50, 50))); + await putLookImage(GID, 'splash', { + hash: '0123456789abcdef', + mime: 'image/webp', + data: await pic(10, 10, 'webp'), + origin: 'o', + }); + await setPublicLook(GID, { accent: '#5865f2', background: 'upload' }); + assert.equal(rows().length, 2); + await purgeGuild(GID); + assert.equal(rows().length, 0); + assert.deepEqual(await getPublicLook(GID), { accent: '', background: 'none', updatedAt: 0 }); + assert.equal(db.prepare('SELECT COUNT(*) AS n FROM guild_public_look WHERE guild_id = ?').get(GID).n, 0); +}); diff --git a/test/quotesPublic.test.js b/test/quotesPublic.test.js index 97916d4b..70c67426 100644 --- a/test/quotesPublic.test.js +++ b/test/quotesPublic.test.js @@ -114,7 +114,11 @@ test('no ids leak: not the author, the saver, the channel or the message, and no assert.ok(!html.includes(secret), `the page must not contain ${secret}`); } assert.doesNotMatch(html, /\/channels\//); - assert.doesNotMatch(html, /]*href="https?:/i, 'no outward links at all'); + // The one outward link every public page has: "Powered by Sylo", with rel="noreferrer". + const poweredBy = + /Powered by Sylo<\/a>/; + assert.match(html, poweredBy); + assert.doesNotMatch(html.replace(poweredBy, ''), /]*href="https?:/i, 'no outward links but that one'); // nothing that looks like a snowflake besides the server's own id assert.doesNotMatch(html.replaceAll(GID, ''), /\b\d{17,20}\b/); }); diff --git a/test/v2.accessLevels.test.js b/test/v2.accessLevels.test.js index 8bfd002a..10936c04 100644 --- a/test/v2.accessLevels.test.js +++ b/test/v2.accessLevels.test.js @@ -147,6 +147,9 @@ const WRITES = [ ['/moderation/warnings/clear', { userId: '810000000000000001' }, 404], ['/access', { viewRoleIds: [VIEW, OTHER_ROLE] }, 200], ['/setup/apply', { items: [] }, 400], + ['/public-page-look', { accent: '', background: 'none' }, 200], + ['/public-page-look/image/delete', {}, 200], + ['/public-page-look/splash/refresh', {}, 200], ]; async function expectLevel(client, level) { @@ -186,6 +189,7 @@ const GETS_ABOVE_VIEW = { 'GET /guilds/:guildId/applications/submissions/:id': 'inbox', 'GET /guilds/:guildId/applications/export': 'inbox', 'GET /guilds/:guildId/export': 'edit', + 'GET /guilds/:guildId/public-page-look': 'edit', }; test('every /api/v2 route declares its access level, and every declaration has a route', () => { @@ -666,3 +670,41 @@ test('below Edit: RSS feed URLs show only their origin; no config download, no i assert.equal((await master.web.get(g('/export'))).status, 200); assert.equal((await view.web.post(g('/insights/refresh'))).status, 403); }); + +test("the server's look on its public pages is Edit only, the read too, on the web and in the app", async () => { + for (const roles of [[VIEW], [INBOX]]) { + const { web, app } = await person({ roles }); + for (const client of [web, app]) { + const read = await client.get(g('/public-page-look')); + assert.equal(read.status, 403, `${roles} may not read it`); + assert.equal((await read.json()).required, 'edit'); + const write = await client.post(g('/public-page-look'), { accent: '#0a5c36', background: 'none' }); + assert.equal(write.status, 403); + assert.equal((await write.json()).required, 'edit'); + } + } + const master = await person({ roles: [MASTER] }); + for (const client of [master.web, master.app]) { + assert.equal((await client.get(g('/public-page-look'))).status, 200); + const saved = await client.post(g('/public-page-look'), { accent: '#0a5c36', background: 'none' }); + assert.equal(saved.status, 200); + assert.equal((await saved.json()).accent, '#0a5c36'); + } + // Another server is another server: the same person gets nothing there. + const other = runtime.clients.discord.guilds.cache.get(OTHER_D_GUILD); + other.members.cache.set(master.id, fakeMember(master.id, { roles: [MASTER] })); + try { + for (const client of [master.web, master.app]) { + assert.equal((await client.get(`/guilds/${OTHER_D_GUILD}/public-page-look`)).status, 403); + assert.equal( + (await client.post(`/guilds/${OTHER_D_GUILD}/public-page-look`, { accent: '#0a5c36' })).status, + 403 + ); + } + } finally { + other.members.cache.clear(); + } + // Fluxer servers have the same routes behind the same guard. + const fluxer = await person({ platform: 'fluxer', roles: [VIEW] }); + assert.equal((await fluxer.app.get(`/guilds/${F_KEY}/public-page-look`)).status, 403); +}); diff --git a/web-v2/src/__tests__/PublicPagesSettings.test.jsx b/web-v2/src/__tests__/PublicPagesSettings.test.jsx new file mode 100644 index 00000000..7a19c822 --- /dev/null +++ b/web-v2/src/__tests__/PublicPagesSettings.test.jsx @@ -0,0 +1,178 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import PublicPagesSettings from '../components/PublicPagesSettings.jsx'; +import { AccessProvider } from '../access.jsx'; + +vi.mock('../api.js', () => ({ + ApiError: class ApiError extends Error {}, + getPublicLook: vi.fn(), + savePublicLook: vi.fn(), + uploadPublicLookImage: vi.fn(), + deletePublicLookImage: vi.fn(), + refreshPublicLookSplash: vi.fn(), + getGuildAccess: vi.fn(), +})); +vi.mock('../notify.js', () => ({ notify: vi.fn() })); +const api = await import('../api.js'); +const { notify } = await import('../notify.js'); + +const GUILD = '123456789012345678'; +const SYLO = { dark: '#38c8f0', light: '#076787' }; + +const look = (over = {}) => ({ + platform: 'discord', + accent: '', + background: 'none', + backgrounds: ['none', 'upload', 'discord-splash'], + upload: null, + splash: { available: false, copied: null }, + effective: { accent: SYLO, fallback: [], note: null, backgroundUrl: null, css: null }, + sylo: { accent: SYLO }, + limits: { maxBytes: 2 * 1024 * 1024, types: ['PNG', 'JPEG', 'WebP'], maxSide: 1920 }, + ...over, +}); + +function renderSection(level = 'edit') { + api.getGuildAccess.mockResolvedValue({ level }); + return render( + + + + ); +} + +beforeEach(() => { + vi.resetAllMocks(); + document.documentElement.removeAttribute('data-theme'); +}); + +describe('Server settings: Public pages', () => { + it('shows nothing below Edit access, whatever the server answers', async () => { + // The level is not known for a moment, so the first request may go out; the server refuses it (403). + api.getPublicLook.mockResolvedValue(look({ accent: '#5865f2' })); + renderSection('view'); + await waitFor(() => expect(api.getGuildAccess).toHaveBeenCalled()); + await new Promise((r) => setTimeout(r, 30)); + expect(screen.queryByText('Public pages')).toBeNull(); + expect(screen.queryByLabelText('Accent colour')).toBeNull(); + }); + + it('shows nothing when the server refuses the read', async () => { + api.getPublicLook.mockRejectedValue(new Error('forbidden')); + renderSection('edit'); + await waitFor(() => expect(api.getPublicLook).toHaveBeenCalled()); + await new Promise((r) => setTimeout(r, 30)); + expect(screen.queryByText('Public pages')).toBeNull(); + }); + + it('starts from what is saved and says what stays Sylo’s', async () => { + api.getPublicLook.mockResolvedValue(look({ accent: '#5865f2' })); + renderSection(); + expect(await screen.findByText('Public pages')).toBeTruthy(); + expect(screen.getByLabelText('Accent colour').value).toBe('#5865f2'); + expect( + screen.getByText( + /the layout,\s+the type, the light and dark themes and the "Powered by Sylo" link stay/ + ) + ).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Save public pages' }).disabled).toBe(true); + }); + + it('previews the application form with the accent, and Sylo’s colour where the accent is hard to read', async () => { + api.getPublicLook.mockResolvedValue(look()); + renderSection(); + const input = await screen.findByLabelText('Accent colour'); + const preview = screen.getByTestId('look-preview'); + expect(preview.style.getPropertyValue('--accent')).toBe(SYLO.dark); + + fireEvent.change(input, { target: { value: '#5865F2' } }); + expect(preview.style.getPropertyValue('--accent')).toBe('#5865f2'); + expect(screen.queryByText(/too hard to read/)).toBeNull(); + expect(screen.getByText('Submit application')).toBeTruthy(); + expect(screen.getByText('Powered by Sylo', { selector: 'p' })).toBeTruthy(); + + // a deep blue is hard to read on the dark card (the theme now shown): Sylo's colour, and the note says so + fireEvent.change(input, { target: { value: '#1a2a6c' } }); + expect(preview.style.getPropertyValue('--accent')).toBe(SYLO.dark); + expect( + screen.getByText(/too hard to read on the card in the dark theme, so public pages use Sylo/) + ).toBeTruthy(); + + // the light theme reads it, and the preview follows the theme of the dashboard + document.documentElement.setAttribute('data-theme', 'light'); + fireEvent.change(input, { target: { value: '#1a2a6d' } }); + expect(preview.style.getPropertyValue('--accent')).toBe('#1a2a6d'); + }); + + it('refuses a colour that is not one and keeps the save button off', async () => { + api.getPublicLook.mockResolvedValue(look()); + renderSection(); + const input = await screen.findByLabelText('Accent colour'); + fireEvent.change(input, { target: { value: 'red' } }); + expect(screen.getByText('Use a colour like #5865f2.')).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Save public pages' }).disabled).toBe(true); + }); + + it('saves the accent and the background', async () => { + api.getPublicLook.mockResolvedValue(look()); + api.savePublicLook.mockResolvedValue(look({ accent: '#5865f2' })); + renderSection(); + const input = await screen.findByLabelText('Accent colour'); + fireEvent.change(input, { target: { value: '5865F2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save public pages' })); + await waitFor(() => + expect(api.savePublicLook).toHaveBeenCalledWith(GUILD, { accent: '#5865f2', background: 'none' }) + ); + await waitFor(() => expect(notify).toHaveBeenCalledWith('Public pages saved.', 'info')); + }); + + it('offers the invite background only when the server has one, named for its platform', async () => { + api.getPublicLook.mockResolvedValue(look({ platform: 'fluxer' })); + const { unmount } = renderSection(); + const none = await screen.findByRole('option', { name: /Invite background from Fluxer \(not set\)/ }); + expect(none.disabled).toBe(true); + unmount(); + + api.getPublicLook.mockResolvedValue(look({ splash: { available: true, copied: null } })); + renderSection(); + const option = await screen.findByRole('option', { name: 'Invite background from Discord' }); + expect(option.disabled).toBe(false); + const select = screen.getByLabelText('Background'); + fireEvent.change(select, { target: { value: 'discord-splash' } }); + expect(screen.getByText(/downloaded when you save/)).toBeTruthy(); + expect(screen.getByText(/visitors never load it from Discord/)).toBeTruthy(); + expect(screen.getByRole('button', { name: 'Check the invite background now' })).toBeTruthy(); + }); + + it('uploads a picture, chooses it, and removes it again', async () => { + api.getPublicLook.mockResolvedValue(look()); + api.uploadPublicLookImage.mockResolvedValue( + look({ upload: { bytes: 900, url: '/look/123456789012345678.0123456789abcdef.webp', updatedAt: 1 } }) + ); + api.deletePublicLookImage.mockResolvedValue(look()); + const { container } = renderSection(); + await screen.findByText('Public pages'); + const file = new File([new Uint8Array(10)], 'bg.png', { type: 'image/png' }); + fireEvent.change(container.querySelector('input[type=file]'), { target: { files: [file] } }); + await waitFor(() => expect(api.uploadPublicLookImage).toHaveBeenCalledWith(GUILD, file)); + await waitFor(() => expect(screen.getByLabelText('Background').value).toBe('upload')); + const preview = screen.getByTestId('look-preview'); + expect(preview.style.backgroundImage).toContain('/look/123456789012345678.0123456789abcdef.webp'); + // choosing it is still a save + expect(screen.getByRole('button', { name: 'Save public pages' }).disabled).toBe(false); + + fireEvent.click(screen.getByRole('button', { name: 'Remove picture' })); + await waitFor(() => expect(api.deletePublicLookImage).toHaveBeenCalledWith(GUILD)); + await waitFor(() => expect(screen.getByLabelText('Background').value).toBe('none')); + }); + + it('does not send a picture larger than 2 MB', async () => { + api.getPublicLook.mockResolvedValue(look()); + const { container } = renderSection(); + await screen.findByText('Public pages'); + const big = new File([new Uint8Array(2 * 1024 * 1024 + 1)], 'big.png', { type: 'image/png' }); + fireEvent.change(container.querySelector('input[type=file]'), { target: { files: [big] } }); + await waitFor(() => expect(notify).toHaveBeenCalledWith('The picture is larger than 2 MB.')); + expect(api.uploadPublicLookImage).not.toHaveBeenCalled(); + }); +}); diff --git a/web-v2/src/__tests__/publicLook.test.jsx b/web-v2/src/__tests__/publicLook.test.jsx new file mode 100644 index 00000000..1d7df038 --- /dev/null +++ b/web-v2/src/__tests__/publicLook.test.jsx @@ -0,0 +1,105 @@ +import { render, cleanup } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { MemoryRouter } from 'react-router-dom'; +import MemberShell from '../components/MemberShell.jsx'; +import PublicShell from '../components/PublicShell.jsx'; +import { + SYLO_ACCENT, + accentNote, + accentOutcome, + contrast, + normaliseAccent, + onAccent, + useServerLook, +} from '../publicLook.js'; +// The server's own half of the same rules: the page must agree with it. +import * as server from '../../../src/lib/publicLook.js'; + +afterEach(() => { + cleanup(); + document.head.querySelectorAll('link[rel=stylesheet]').forEach((l) => l.remove()); + document.body.className = ''; +}); + +describe('the accent rules agree with the server', () => { + const colours = ['#5865f2', '#ffe14d', '#1a2a6c', '#ff0000', '#787878', '#000000', '#ffffff', '#07a', '']; + + it('normalises the same way', () => { + for (const c of [...colours, 'red', '#12', 'ABCDEF', ' #abc ', null, undefined, 5, ['#fff']]) { + expect(normaliseAccent(c), String(c)).toBe(server.normaliseAccent(c)); + } + }); + + it('gives the same outcome per theme and the same sentence', () => { + for (const raw of colours) { + const c = normaliseAccent(raw); + const mine = accentOutcome(c); + const theirs = server.effectiveAccent(c); + const check = server.accentCheck(c); + expect(mine.dark.color, c).toBe(theirs.dark); + expect(mine.light.color, c).toBe(theirs.light); + expect(mine.dark.ok, c).toBe(check.dark.ok); + expect(mine.light.ok, c).toBe(check.light.ok); + expect(accentNote(c), c).toBe(server.fallbackNote(c)); + if (c) expect(onAccent(c), c).toBe(server.onAccent(c)); + } + }); + + it('falls back to Sylo’s colour where the accent is hard to read on the card', () => { + expect(accentOutcome('#1a2a6c').dark.color).toBe(SYLO_ACCENT.dark); + expect(accentOutcome('#1a2a6c').light.color).toBe('#1a2a6c'); + expect(accentOutcome('#ffe14d').light.color).toBe(SYLO_ACCENT.light); + expect(accentOutcome('#5865f2').dark.ok && accentOutcome('#5865f2').light.ok).toBe(true); + expect(contrast('#000000', '#ffffff')).toBeCloseTo(21, 0); + }); +}); + +function Probe({ look }) { + useServerLook(look); + return null; +} + +describe('useServerLook', () => { + it('loads the server’s style sheet and marks the page, and undoes both when the page closes', () => { + const css = '/look/123456789012345678.0123456789abcdef.css'; + const { unmount } = render(); + expect(document.head.querySelector(`link[rel=stylesheet][href="${css}"]`)).not.toBeNull(); + expect(document.body.classList.contains('has-look')).toBe(true); + expect(document.body.classList.contains('has-look-image')).toBe(true); + unmount(); + expect(document.head.querySelector(`link[href="${css}"]`)).toBeNull(); + expect(document.body.classList.contains('has-look')).toBe(false); + expect(document.body.classList.contains('has-look-image')).toBe(false); + }); + + it('marks an accent-only look without the image class', () => { + render(); + expect(document.body.classList.contains('has-look')).toBe(true); + expect(document.body.classList.contains('has-look-image')).toBe(false); + }); + + it('does nothing without a look, and never loads an address that is not one of Sylo’s look files', () => { + render(); + render(); + render(); + expect(document.head.querySelectorAll('link[rel=stylesheet]').length).toBe(0); + expect(document.body.classList.contains('has-look')).toBe(false); + }); +}); + +describe('the Powered by Sylo link', () => { + it('ends the member pages and the signed-out public pages', () => { + for (const Shell of [MemberShell, PublicShell]) { + const { container, unmount } = render( + + + + ); + const link = container.querySelector('footer a'); + expect(link.textContent).toBe('Powered by Sylo'); + expect(link.getAttribute('href')).toBe('https://github.com/Ferdinand99/Sylo'); + expect(link.getAttribute('rel')).toBe('noopener noreferrer'); + unmount(); + } + }); +}); diff --git a/web-v2/src/api.js b/web-v2/src/api.js index e93b45e1..45caa3e3 100644 --- a/web-v2/src/api.js +++ b/web-v2/src/api.js @@ -213,6 +213,18 @@ export const getShopActivity = (guildId, { userId = '', itemId = '', page = 1 } apiFetch( `${shopBase(guildId)}/shop/activity?userId=${encodeURIComponent(userId)}&itemId=${encodeURIComponent(itemId)}&page=${Number(page) || 1}` ); +// The server's own look on its public pages (Server settings → Public pages): the accent colour, the +// background, the uploaded picture (a multipart upload, the field "file") and the invite-background check. +const lookBase = (guildId) => `/api/v2/guilds/${gid(guildId)}/public-page-look`; +export const getPublicLook = (guildId) => apiFetch(lookBase(guildId)); +export const savePublicLook = (guildId, body) => postJson(lookBase(guildId), body); +export const uploadPublicLookImage = (guildId, file) => { + const body = new FormData(); + body.append('file', file); + return apiFetch(`${lookBase(guildId)}/image`, { method: 'POST', body }); +}; +export const deletePublicLookImage = (guildId) => postJson(`${lookBase(guildId)}/image/delete`, {}); +export const refreshPublicLookSplash = (guildId) => postJson(`${lookBase(guildId)}/splash/refresh`, {}); // The member-facing web shop (/v2/shop/). export const getWebShop = (guildId) => apiFetch(`/api/v2/shop/${gid(guildId)}`); export const buyWebShopItem = (guildId, itemId, price, version) => diff --git a/web-v2/src/components/MemberShell.jsx b/web-v2/src/components/MemberShell.jsx index 8da41a14..01b1639a 100644 --- a/web-v2/src/components/MemberShell.jsx +++ b/web-v2/src/components/MemberShell.jsx @@ -1,5 +1,6 @@ import { Suspense, useRef } from 'react'; import { Outlet } from 'react-router-dom'; +import PoweredBy from './PoweredBy.jsx'; import ThemeToggle from './ThemeToggle.jsx'; import Toasts from './Toasts.jsx'; import useLabelLinks from './useLabelLinks.js'; @@ -30,6 +31,7 @@ export default function MemberShell() { + ); diff --git a/web-v2/src/components/PoweredBy.jsx b/web-v2/src/components/PoweredBy.jsx new file mode 100644 index 00000000..e2216967 --- /dev/null +++ b/web-v2/src/components/PoweredBy.jsx @@ -0,0 +1,11 @@ +// The small "Powered by Sylo" link at the bottom of every public page. Always shown and not configurable: a +// server's look (accent colour, background; see publicLook.js) never reaches it. +export default function PoweredBy() { + return ( + + ); +} diff --git a/web-v2/src/components/PublicPagesSettings.jsx b/web-v2/src/components/PublicPagesSettings.jsx new file mode 100644 index 00000000..4cf44349 --- /dev/null +++ b/web-v2/src/components/PublicPagesSettings.jsx @@ -0,0 +1,268 @@ +import { useEffect, useRef, useState } from 'react'; +import { + deletePublicLookImage, + getPublicLook, + refreshPublicLookSplash, + savePublicLook, + uploadPublicLookImage, +} from '../api.js'; +import { useApiData } from '../useApiData.js'; +import { notify } from '../notify.js'; +import { useAccess } from '../access.jsx'; +import Field from './Field.jsx'; +import { SYLO_ACCENT, accentNote, accentOutcome, normaliseAccent, onAccent } from '../publicLook.js'; + +const MAX_BYTES = 2 * 1024 * 1024; + +/** The theme the dashboard shows now, so the preview matches what the person sees. */ +const currentTheme = () => + typeof document !== 'undefined' && document.documentElement.getAttribute('data-theme') === 'light' + ? 'light' + : 'dark'; + +/** + * Server settings → Public pages: the server's own accent colour and background on the pages its members open + * without the dashboard (the application form, the ban appeal, the event and quote pages, the web shop). Only + * these two things change; the layout, the type, the light and dark themes and the "Powered by Sylo" link stay + * Sylo's. The preview is the application form page. Edit level only (the section is not shown below it). + */ +export default function PublicPagesSettings({ guildId }) { + const { can } = useAccess(); + const allowed = can('edit'); + const { data, error, setData } = useApiData( + () => (allowed ? Promise.resolve().then(() => getPublicLook(guildId)) : Promise.resolve(null)), + [guildId, allowed] + ); + const [accent, setAccent] = useState(''); + const [background, setBackground] = useState('none'); + const [busy, setBusy] = useState(false); + const fileInput = useRef(null); + + // Start from what is saved, and again when another server's answer arrives. + const savedFor = data ? `${guildId}|${data.accent}|${data.background}` : null; + useEffect(() => { + if (!data) return; + setAccent(data.accent); + setBackground(data.background); + // only a new saved state resets the form, not every answer (an upload changes the picture, not the choice) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [savedFor]); + + if (!allowed || error || !data) return null; + + const normalised = normaliseAccent(accent); + const invalid = normalised === null; + const dirty = !invalid && (normalised !== data.accent || background !== data.background); + const note = invalid ? null : accentNote(normalised); + const theme = currentTheme(); + const outcome = accentOutcome(invalid ? '' : normalised); + const shown = outcome[theme].color; + + const splash = data.splash; + const image = + background === 'upload' ? data.upload?.url : background === 'discord-splash' ? splash.copied?.url : null; + const waitingSplash = background === 'discord-splash' && !splash.copied; + + async function run(fn, done) { + setBusy(true); + try { + const out = await fn(); + if (out) setData(out); + if (done) notify(done, 'info'); + return out; + } catch (err) { + notify(err.message); + return null; + } finally { + setBusy(false); + } + } + + const onSave = (e) => { + e.preventDefault(); + if (!dirty) return; + run(() => savePublicLook(guildId, { accent: normalised, background }), 'Public pages saved.'); + }; + + async function onFile(e) { + const file = e.target.files?.[0]; + e.target.value = ''; + if (!file) return; + if (file.size > MAX_BYTES) { + notify('The picture is larger than 2 MB.'); + return; + } + const out = await run(() => uploadPublicLookImage(guildId, file)); + if (out) { + setBackground('upload'); + notify('Picture uploaded. Save to use it.', 'info'); + } + } + + async function onRemove() { + const out = await run(() => deletePublicLookImage(guildId), 'Picture removed.'); + if (out && background === 'upload') setBackground('none'); + } + + const platformName = data.platform === 'fluxer' ? 'Fluxer' : 'Discord'; + const splashHint = !splash.available + ? `This server has no invite background on ${platformName}. Set one there to use it here.` + : `Sylo keeps its own copy of the server's ${platformName} invite background and checks it once a day, so visitors never load it from ${platformName}.`; + + return ( +
+

Public pages

+

+ Give the pages your members open without the dashboard (application forms, ban appeals, events, quotes + and the web shop) your server's accent colour and a background. Only these two things change: the + layout, the type, the light and dark themes and the "Powered by Sylo" link stay as they are. +

+
+
+ +
+ setAccent(e.target.value)} + /> + setAccent(e.target.value)} + /> + +
+

+ {invalid + ? 'Use a colour like #5865f2.' + : 'Used for buttons, links and highlights. Leave it empty for Sylo’s own colour.'} +

+ {note ? ( +

+ {note} +

+ ) : null} +
+ + + + + +
+ Your own picture +
+ + + {data.upload ? ( + + ) : null} + {background === 'discord-splash' && splash.available ? ( + + ) : null} +
+

+ PNG, JPEG or WebP, at most 2 MB. Sylo stores a re-encoded copy (metadata removed) and serves it + itself. + {!splash.available ? ` ${splashHint}` : ''} +

+
+ +

Preview: the application form

+
+
+
+

Your server

+

Staff application

+

+ Tell us a little about you. Read the rules first + . +

+
Why do you want to join?
+ Submit application +
+

Powered by Sylo

+
+
+ {waitingSplash ? ( +

The invite background is downloaded when you save.

+ ) : null} +

+ Shown in the {theme} theme.{' '} + {['dark', 'light'].map((t) => ( + + {t}:{' '} + {outcome[t].ratio == null + ? 'Sylo’s colour' + : `${outcome[t].ratio}:1${outcome[t].ok ? '' : ' (too low)'}`}{' '} + + ))} +

+ +
+ +
+
+
+ ); +} diff --git a/web-v2/src/components/PublicShell.jsx b/web-v2/src/components/PublicShell.jsx index b85be394..734bc3fa 100644 --- a/web-v2/src/components/PublicShell.jsx +++ b/web-v2/src/components/PublicShell.jsx @@ -1,5 +1,6 @@ import { Suspense, useRef } from 'react'; import { NavLink, Outlet, useLocation } from 'react-router-dom'; +import PoweredBy from './PoweredBy.jsx'; import ThemeToggle from './ThemeToggle.jsx'; import Toasts from './Toasts.jsx'; import useLabelLinks from './useLabelLinks.js'; @@ -40,6 +41,7 @@ export default function PublicShell() { + ); diff --git a/web-v2/src/main.jsx b/web-v2/src/main.jsx index e97b7ce7..a4e15d27 100644 --- a/web-v2/src/main.jsx +++ b/web-v2/src/main.jsx @@ -22,6 +22,7 @@ import './styles/setup-wizard.css'; import './styles/access.css'; import './styles/history.css'; import './styles/health.css'; +import './styles/p3-look.css'; createRoot(document.getElementById('root')).render( diff --git a/web-v2/src/pages/Apply.jsx b/web-v2/src/pages/Apply.jsx index c6e34b21..d7bf254e 100644 --- a/web-v2/src/pages/Apply.jsx +++ b/web-v2/src/pages/Apply.jsx @@ -3,6 +3,7 @@ import { useParams } from 'react-router-dom'; import { ApiError, getWebApply, submitWebApply, withdrawWebApply } from '../api.js'; import { useApiData } from '../useApiData.js'; import { notify } from '../notify.js'; +import { useServerLook } from '../publicLook.js'; import { confirmDialog } from '../components/ConfirmDialog.jsx'; import ApplicationQuestion from '../components/ApplicationQuestion.jsx'; import Time from '../components/Time.jsx'; @@ -33,6 +34,8 @@ function Nothing() { export default function Apply() { const { guildId, formId } = useParams(); const { data, error, setData } = useApiData(() => getWebApply(guildId, formId), [guildId, formId]); + // The server's own accent colour and background, when it chose any (see publicLook.js). + useServerLook(data?.look); const [answers, setAnswers] = useState(null); const [errors, setErrors] = useState({}); const [busy, setBusy] = useState(false); diff --git a/web-v2/src/pages/Settings.jsx b/web-v2/src/pages/Settings.jsx index b177dbed..b37e98b6 100644 --- a/web-v2/src/pages/Settings.jsx +++ b/web-v2/src/pages/Settings.jsx @@ -16,6 +16,7 @@ import ChipPicker from '../components/ChipPicker.jsx'; import { notify } from '../notify.js'; import Reveal from '../components/Reveal.jsx'; import ConfigImport from '../components/ConfigImport.jsx'; +import PublicPagesSettings from '../components/PublicPagesSettings.jsx'; import { useCanSetUp } from '../setupAccess.js'; import { AccessLock, useAccess } from '../access.jsx'; @@ -284,6 +285,9 @@ export default function Settings() { + {/* The server's own accent colour and background on its public member pages (Edit access only). */} + +

Server data

diff --git a/web-v2/src/pages/Shop.jsx b/web-v2/src/pages/Shop.jsx index 90c5cf2c..ea2f6d23 100644 --- a/web-v2/src/pages/Shop.jsx +++ b/web-v2/src/pages/Shop.jsx @@ -3,6 +3,7 @@ import { useParams } from 'react-router-dom'; import { ApiError, buyWebShopItem, getWebShop } from '../api.js'; import { useApiData } from '../useApiData.js'; import { notify } from '../notify.js'; +import { useServerLook } from '../publicLook.js'; import { confirmDialog } from '../components/ConfirmDialog.jsx'; import Meta from '../components/Meta.jsx'; import Time from '../components/Time.jsx'; @@ -36,6 +37,8 @@ function kindText(item) { export default function Shop() { const { guildId } = useParams(); const { data, error, setData } = useApiData(() => getWebShop(guildId), [guildId]); + // The server's own accent colour and background, when it chose any (see publicLook.js). + useServerLook(data?.look); const [busy, setBusy] = useState(null); if (error) { diff --git a/web-v2/src/publicLook.js b/web-v2/src/publicLook.js new file mode 100644 index 00000000..72e14880 --- /dev/null +++ b/web-v2/src/publicLook.js @@ -0,0 +1,93 @@ +// The server's own look on the public member pages, on the page side (the server's half is +// src/lib/publicLook.js, which has the last word; the contrast rule below is the same, so the settings preview can +// say at once what a colour will do). Two things: +// - useServerLook(look): the pages a member opens inside the dashboard (the application form, the web shop) +// load the server's style sheet (custom properties only) and mark , the same way the server renders the +// appeal, event and quote pages. +// - the accent rules the "Public pages" settings preview uses. +import { useEffect } from 'react'; + +export const SYLO_ACCENT = { dark: '#38c8f0', light: '#076787' }; +/** The card behind the form, per theme (--bg-surface). */ +export const CARD = { dark: '#161618', light: '#ffffff' }; +/** The least contrast of an accent against the card (3:1, see src/lib/publicLook.js). */ +export const MIN_CONTRAST = 3; + +/** '#rrggbb' in lower case, '' for none, null when it is not a colour. */ +export function normaliseAccent(value) { + if (value == null) return ''; + if (typeof value !== 'string') return null; + const text = value.trim(); + if (text === '') return ''; + const m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(text); + if (!m) return null; + let hex = m[1].toLowerCase(); + if (hex.length === 3) hex = [...hex].map((c) => c + c).join(''); + return `#${hex}`; +} + +function luminance(hex) { + const n = parseInt(hex.slice(1), 16); + const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((c) => { + const v = c / 255; + return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +} + +export function contrast(a, b) { + const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x); + return (hi + 0.05) / (lo + 0.05); +} + +/** The text colour on a fill of this accent. */ +export const onAccent = (accent) => + contrast(accent, '#ffffff') >= contrast(accent, '#000000') ? '#ffffff' : '#000000'; + +/** What a colour comes to per theme: the colour really used and whether Sylo's own replaced it. */ +export function accentOutcome(accent) { + const out = {}; + for (const theme of ['dark', 'light']) { + const ratio = accent ? contrast(accent, CARD[theme]) : null; + const ok = !accent || ratio >= MIN_CONTRAST; + out[theme] = { + ratio: ratio == null ? null : Math.round(ratio * 100) / 100, + ok, + color: accent && ok ? accent : SYLO_ACCENT[theme], + }; + } + return out; +} + +/** The sentence for a colour that is replaced in a theme, or null. */ +export function accentNote(accent) { + if (!accent) return null; + const out = accentOutcome(accent); + const bad = ['dark', 'light'].filter((t) => !out[t].ok); + if (bad.length === 0) return null; + const where = bad.length === 2 ? 'both the light and the dark theme' : `the ${bad[0]} theme`; + return `This colour is too hard to read on the card in ${where}, so public pages use Sylo's own colour there. Pick a darker or lighter shade.`; +} + +/** + * Load the server's look for the page that is open: its style sheet and the marks on that the dim + * overlay and the panel hang on (styles/p3-look.css). `look` is `{ css, image }` from the page's data, or + * null for plain Sylo. Undone when the page closes. + */ +export function useServerLook(look) { + const css = look?.css ?? null; + const image = Boolean(look?.image); + useEffect(() => { + if (!css || !/^\/look\/[a-z0-9-]+\.[0-9a-f]{16}\.css$/.test(css)) return undefined; + const link = document.createElement('link'); + link.rel = 'stylesheet'; + link.href = css; + document.head.appendChild(link); + const marks = image ? ['has-look', 'has-look-image'] : ['has-look']; + document.body.classList.add(...marks); + return () => { + link.remove(); + document.body.classList.remove(...marks); + }; + }, [css, image]); +} diff --git a/web-v2/src/styles/p3-look.css b/web-v2/src/styles/p3-look.css new file mode 100644 index 00000000..2eaa8329 --- /dev/null +++ b/web-v2/src/styles/p3-look.css @@ -0,0 +1,162 @@ +/* The look of a server's public pages inside the dashboard (the application form, the web shop) and the + "Powered by Sylo" line. The server's style sheet (/look/...) sets only custom properties: --accent and + --on-accent (the dashboard already reads them) and --look-image. Everything here is Sylo's: the dim overlay, the + panel the page sits on, the primary button taking the accent. public.css has the same for the EJS pages. */ +:root { + --look-dim: rgba(0, 0, 0, 0.58); + --look-panel: 90%; +} +:root[data-theme='light'] { + --look-dim: rgba(0, 0, 0, 0.42); +} + +.v2-powered { + padding: 4px 16px 24px; + text-align: center; + font-size: var(--fs-sm); + color: var(--text-muted); +} +.v2-powered a { + color: var(--text-muted); + text-decoration: underline; + text-underline-offset: 2px; +} +.v2-powered a:hover { + color: var(--text); +} + +/* A server that chose an accent: the primary button of its pages takes it. */ +body.has-look .v2-public .v2-btn-primary { + background: var(--accent); + color: var(--on-accent); +} + +/* A server that chose a background picture: the picture under a dim overlay, and the page on a semi-opaque panel. */ +body.has-look-image { + background-color: var(--bg-main); + background-image: linear-gradient(var(--look-dim), var(--look-dim)), var(--look-image); + background-size: cover; + background-position: center; + background-repeat: no-repeat; + background-attachment: fixed; +} +body.has-look-image .v2-public-page { + margin-top: 16px; + margin-bottom: 16px; + border-radius: var(--radius); + background: color-mix(in srgb, var(--bg-main) var(--look-panel), transparent); + -webkit-backdrop-filter: blur(10px); + backdrop-filter: blur(10px); +} +body.has-look-image .v2-powered { + padding-top: 0; +} +body.has-look-image .v2-powered a { + display: inline-block; + padding: 3px 12px; + border-radius: var(--radius-pill); + background: color-mix(in srgb, var(--bg-main) 88%, transparent); +} +@media (prefers-reduced-transparency: reduce) { + body.has-look-image .v2-public-page, + body.has-look-image .v2-powered a { + background: var(--bg-main); + -webkit-backdrop-filter: none; + backdrop-filter: none; + } +} + +/* Server settings → Public pages: the preview of the application form page. */ +.v2-look-preview-title { + margin: 18px 0 8px; + font-size: var(--fs-md); + font-weight: 600; +} +.v2-look-preview { + border-radius: var(--radius); + border: 1px solid var(--border-subtle); + background-color: var(--bg-main); + background-size: cover; + background-position: center; + padding: 14px; +} +.v2-look-preview-panel { + display: flex; + flex-direction: column; + gap: 8px; + max-width: 28rem; + margin: 0 auto; +} +.v2-look-preview.has-image .v2-look-preview-panel { + padding: 10px; + border-radius: var(--radius); + background: color-mix(in srgb, var(--bg-main) var(--look-panel), transparent); +} +.v2-look-preview-card { + display: flex; + flex-direction: column; + gap: 8px; + padding: 14px 16px; + border-radius: var(--radius-sm); + border: 1px solid var(--border-subtle); + background: color-mix(in srgb, var(--bg-surface) 92%, transparent); +} +.v2-look-preview-eyebrow, +.v2-look-preview-text, +.v2-look-preview-heading, +.v2-look-preview-foot { + margin: 0; +} +.v2-look-preview-eyebrow { + font-size: var(--fs-xs); + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + color: var(--text-muted); +} +.v2-look-preview-heading { + font-size: var(--fs-lg); + font-weight: 700; +} +.v2-look-preview-text { + font-size: var(--fs-sm); +} +.v2-look-preview-link { + color: var(--accent); + text-decoration: underline; +} +.v2-look-preview-field { + padding: 8px 10px; + border-radius: var(--radius-sm); + border: 1px solid var(--border-strong); + color: var(--text-muted); + font-size: var(--fs-sm); +} +.v2-look-preview-btn { + align-self: flex-start; + padding: 6px 16px; + border-radius: var(--radius-pill); + background: var(--accent); + color: var(--on-accent); + font-size: 0.875rem; + font-weight: 600; +} +.v2-look-preview-foot { + text-align: center; + font-size: var(--fs-xs); + color: var(--text-muted); +} +.v2-look-ratio { + white-space: nowrap; +} +@media (prefers-reduced-transparency: reduce) { + .v2-look-preview.has-image .v2-look-preview-panel, + .v2-look-preview-card { + background: var(--bg-surface); + } +} + +/* An accent is only held to 3:1 against the card, so links are underlined whenever a server chose a look. */ +body.has-look .v2-public-page a:not(.v2-btn-primary):not(.v2-btn-ghost) { + text-decoration: underline; +} From 8742b3bec737e80babb46ebdfab61c0c886dbb67 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Mon, 16 Nov 2026 01:25:21 +0100 Subject: [PATCH 2/9] test(public-pages): wait for the settings form to take the saved colour --- web-v2/src/__tests__/PublicPagesSettings.test.jsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web-v2/src/__tests__/PublicPagesSettings.test.jsx b/web-v2/src/__tests__/PublicPagesSettings.test.jsx index 7a19c822..e1ced92f 100644 --- a/web-v2/src/__tests__/PublicPagesSettings.test.jsx +++ b/web-v2/src/__tests__/PublicPagesSettings.test.jsx @@ -69,7 +69,8 @@ describe('Server settings: Public pages', () => { api.getPublicLook.mockResolvedValue(look({ accent: '#5865f2' })); renderSection(); expect(await screen.findByText('Public pages')).toBeTruthy(); - expect(screen.getByLabelText('Accent colour').value).toBe('#5865f2'); + // the form takes the saved value in an effect, right after the first render with the data + await waitFor(() => expect(screen.getByLabelText('Accent colour').value).toBe('#5865f2')); expect( screen.getByText( /the layout,\s+the type, the light and dark themes and the "Powered by Sylo" link stay/ From dc8c49d766a3a086afe67d2cd9a106fd90c140cf Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Mon, 16 Nov 2026 01:56:31 +0100 Subject: [PATCH 3/9] fix(public-pages): readable accent text, light-theme picture contrast, product link, test gaps - text uses of the accent read --accent-text (the accent, or the same hue lightened/darkened to 4.5:1 on card, page and tinted card); fills, borders and focus rings keep the 3:1 bar - hovered buttons keep 4.5:1 for their text (--accent-hover moves away from the text colour) - light theme over a picture: a light veil, a 99 % panel, the top bar glass always on - "Powered by Sylo" links to sylobot.com, one muted style on every page - lookCss refuses a stored accent that is not #rrggbb - a forced splash check no longer takes the answer of a running unforced one - pictures are cached for a day; public_look_images copied in small chunks to Postgres - docs, comments and tests: readability, upload route in the access matrix, Fluxer end to end, leaderboard/Apply/Shop with a look, migration 81 upgrade --- docs/dashboard-v2.md | 17 +- docs/mobile-app.md | 9 +- docs/privacy-policy.md | 2 +- scripts/migrate-sqlite-to-postgres.js | 2 +- src/db/publicLook.js | 7 +- src/lib/publicLook.js | 76 ++++++-- src/web/lib/publicLook.js | 16 +- src/web/public/public.css | 33 +++- src/web/routes/publicLook.js | 11 +- src/web/routes/v2PublicLook.js | 3 +- src/web/views/partials/powered.ejs | 2 +- test/eventPages.public.test.js | 3 +- test/publicLook.lib.test.js | 5 +- test/publicLook.readability.test.js | 184 ++++++++++++++++++ test/publicLook.web.test.js | 62 +++++- test/publicPagesPolish.test.js | 11 +- test/quotesPublic.test.js | 3 +- test/upgradeBoot.test.js | 124 ++++++++++++ test/v2.accessLevels.test.js | 26 +++ test/v2Apply.test.js | 63 ++++++ test/v2WebShop.test.js | 7 + .../__tests__/PublicPagesSettings.test.jsx | 3 + web-v2/src/__tests__/publicLook.test.jsx | 5 +- web-v2/src/components/PoweredBy.jsx | 2 +- web-v2/src/components/PublicPagesSettings.jsx | 12 +- web-v2/src/publicLook.js | 37 +++- web-v2/src/styles.css | 2 +- web-v2/src/styles/p3-look.css | 18 +- 28 files changed, 683 insertions(+), 62 deletions(-) create mode 100644 test/publicLook.readability.test.js diff --git a/docs/dashboard-v2.md b/docs/dashboard-v2.md index 7e9d9848..f7200ed8 100644 --- a/docs/dashboard-v2.md +++ b/docs/dashboard-v2.md @@ -90,12 +90,17 @@ Fluxer: Sylo downloads it once, keeps its own copy, checks it once a day and ser browser never talks to Discord or Fluxer. The settings show a live preview of the application form page. What stays Sylo's: the layout, the type, the components, the light and dark themes, the readability and the small -"Powered by Sylo" link at the bottom of every public page, which cannot be turned off. The page always sits on a -semi-opaque card over a dim overlay (opaque for visitors who ask for reduced transparency). An accent that is too hard -to read on the card (less than 3:1 against it) is not used in that theme (the light or the dark one): Sylo's own -colour stays there, and the settings say so. The dashboard and the Sylo app are never restyled. The event pages take -no server look, because they carry no server address on purpose. The file addresses are `/look/..css` -and `.webp`; the content security policy is unchanged (styles and images from Sylo only). +"Powered by Sylo" link (to sylobot.com) at the bottom of every public page, which cannot be turned off. The page always +sits on a semi-opaque card over a dim overlay (a light veil in the light theme, and an all but opaque panel, so Sylo's +own text stays readable on any picture; fully opaque for visitors who ask for reduced transparency). The accent is held +to 3:1 against the card for fills, borders and focus rings: below that it is not used in that theme (the light or the +dark one), Sylo's own colour stays there, and the settings say so. Where the accent is used as text (links, the active +pill, top ranks) the pages use a text colour made from it: the accent itself when it reaches 4.5:1 on the card and the +page, otherwise the same hue lightened (dark theme) or darkened (light theme) until it does. The text on a button +fill is black or white, whichever reads better, also when hovered. The dashboard and the Sylo app are never restyled. +The event pages take no server look, because they carry no server address on purpose. The file addresses are +`/look/..css` and `.webp`; the style sheet is kept by caches for a year (its address is its content), +a picture for a day. The content security policy is unchanged (styles and images from Sylo only). ## Duplicate and templates diff --git a/docs/mobile-app.md b/docs/mobile-app.md index c154ff14..fda9bd3b 100644 --- a/docs/mobile-app.md +++ b/docs/mobile-app.md @@ -414,9 +414,12 @@ transparency). Every route here needs the **edit** level, the read too (a lower The answer has `accent` and `background` (what was saved), `platform`, `upload` (`null` or `{ bytes, url, updatedAt }`), `splash` (`available`: the server has an invite background on the platform, Discord and Fluxer both have one; `copied`: `null` or `{ url, checkedAt, updatedAt }`, Sylo's own copy), `limits` and `sylo` (Sylo's accent per theme) -and `effective`: `accent` (the colour really used, per theme: `dark` and `light`), `contrast` (the ratio of the -accent to the card per theme and whether it reaches the 3:1 Sylo asks for), `fallback` (the themes where it does not and Sylo's own -colour is used instead), `note` (the sentence to show when `fallback` is not empty, else `null`) and `backgroundUrl`. +`backgrounds` (the three values the app may send) and `effective`: `accent` (the colour really used for fills and +borders, per theme: `dark` and `light`), `accentText` (the colour used for text, per theme: the accent, or the same hue +lightened or darkened to reach 4.5:1), `contrast` (the ratio of the accent to the card per theme and whether it reaches +the 3:1 Sylo asks for), `fallback` (the themes where it does not and Sylo's own colour is used instead), `note` (the +sentence to show when `fallback` is not empty, else `null`), `backgroundUrl` (the picture of the chosen background, +or `null`) and `css` (the path of the style sheet public pages load, or `null` when the server chose nothing). A `400` for a colour that is not `#rgb` or `#rrggbb`, for `upload` with no picture or for `discord-splash` when the server has none; `502` when the invite background could not be downloaded. The urls are paths on the Sylo server itself (the app prefixes the server address); the pictures are never loaded from the platform's CDN. diff --git a/docs/privacy-policy.md b/docs/privacy-policy.md index 66db2135..7794f748 100644 --- a/docs/privacy-policy.md +++ b/docs/privacy-policy.md @@ -83,7 +83,7 @@ the public-leaderboard vanity slug. - **Birthdays** — the day and month (and optionally year) a member registers. - **Giveaways** — the host, the entrants (with whether an entry fee was refunded), the drawn winners, and the currency prizes paid to members. - **Events** — the host and, for each event, who pressed Join or Maybe. A server can switch on a page for each event that shows its title, time, place, description, image, capacity and how many pressed Join or Maybe, but no names, no host and no ids. For an event in a channel everyone can read, anyone with the link can open the page. For an event in a private channel, only a person who signs in with the Dashboard login (Discord or Fluxer, the platform the event was posted on), is a member of that server and can see that channel can open it: Sylo checks this against the platform's data on every request and keeps only a plain yes or no, in memory, for a few seconds, and shows a signed-in person who may not open the page the same "not found" page as for a wrong address. A visitor who is not signed in sees a plain sign-in page that shows nothing about the event. An event in an age-restricted channel has no page for anyone. These pages are not cached by browsers or search engines, and nothing about the check is stored beyond the ordinary Dashboard login described in section 3 (a first sign-in creates a dashboard account and a session, which you can delete as described in section 7). The address of each event's page is a random code stored with the event. A visitor's browser contacts only Sylo: Sylo fetches the server icon and the event image from Discord's image servers itself and keeps a copy in memory only, for about ten minutes (a sweep removes expired copies every minute) and hands it out only to a visitor who passes the checks, and the pages carry no visit-count script when they are not found or ask for a sign-in. -- **Public page look** — a server's accent colour and background choice for its public member pages, and the background picture: one the server's staff upload (Sylo keeps a re-encoded copy without metadata) and/or a copy of the server's invite background from Discord or Fluxer, which Sylo downloads itself and refreshes daily. A visitor's browser loads these from Sylo only. Both go when the server's data is deleted. +- **Public page look** — a server's accent colour and background choice for its public member pages, and the background picture: one the server's staff upload (Sylo keeps a re-encoded copy without metadata) and/or a copy of the server's invite background from Discord or Fluxer, which Sylo downloads itself and re-checks against the platform at most once a day (when a page that uses it is opened), downloading it again only when it changed. A visitor's browser loads these from Sylo only. A picture a server removes is deleted at once; copies that browsers or shared caches already hold are kept for up to a day (the style sheet, which holds only a colour and an address, up to a year). Both go when the server's data is deleted. - **Suggestions** — the text of each suggestion, who wrote it (unless they erase it), the staff member who decided it, and each member's 👍 / 👎 vote. - **Temporary roles** — which member holds which temporary role, when it ends, the reason, and the staff member who set it. - **Introductions** — the answers a member gave in the DM questionnaire (up to eight short texts, with @everyone, @here and role mentions removed), the channel and message ids of their card, and when it was made and last changed. The card itself is a public message in the server's introductions channel: it shows the member's avatar, name, answers, the roles they have from the server's role groups, and when they joined. diff --git a/scripts/migrate-sqlite-to-postgres.js b/scripts/migrate-sqlite-to-postgres.js index 6ee82937..bef94263 100644 --- a/scripts/migrate-sqlite-to-postgres.js +++ b/scripts/migrate-sqlite-to-postgres.js @@ -103,7 +103,7 @@ const DRY_RUN = process.argv.includes('--dry-run'); const CHUNK = 1000; // A table with a binary column (the pictures of collectibles, up to about a megabyte each) is copied in small // chunks, so a chunk never holds hundreds of megabytes. The bytes are copied as they are (a Buffer is a BYTEA). -const CHUNK_OF = { collectible_images: 10 }; +const CHUNK_OF = { collectible_images: 10, public_look_images: 10 }; function fail(msg) { console.error(`\n✖ ${msg}`); diff --git a/src/db/publicLook.js b/src/db/publicLook.js index 451ac5ac..636e8a1e 100644 --- a/src/db/publicLook.js +++ b/src/db/publicLook.js @@ -73,7 +73,12 @@ const s = { export async function getPublicLook(guildId) { const row = await s.getLook.get(guildId); return row - ? { accent: row.accent, background: row.background, updatedAt: Number(row.updated_at) } + ? { + // only a colour this code wrote (normaliseAccent): anything else in the row (a restored backup) is none + accent: /^#[0-9a-f]{6}$/.test(row.accent) ? row.accent : '', + background: row.background, + updatedAt: Number(row.updated_at), + } : { accent: '', background: 'none', updatedAt: 0 }; } diff --git a/src/lib/publicLook.js b/src/lib/publicLook.js index 14b2448e..6b26cb83 100644 --- a/src/lib/publicLook.js +++ b/src/lib/publicLook.js @@ -1,10 +1,12 @@ -// The server's own look on the public member pages (the application form, the ban appeal, the event and quote -// pages, the web shop): an accent colour and a background, and nothing else. The community owns the content, +// The server's own look on the public member pages (the application form, the ban appeal, the quote page, the +// leaderboards, the web shop; not the event pages, which carry no server address): an accent colour and a +// background, and nothing else. The community owns the content, // Sylo owns the frame: the layout, the typography, the components, the light and dark themes and the // readability stay Sylo's, and every page ends with a "Powered by Sylo" link that cannot be turned off. // // This file is the pure part: checking an accent colour, the contrast rule, and the style sheet a page loads. -// The style sheet carries custom properties only (--accent, --on-accent, --look-image). Everything that uses +// The style sheet carries custom properties only (--accent, --on-accent, --accent-hover, --accent-text, +// --look-image). Everything that uses // them (the card, the dim overlay, the buttons) is written once in Sylo's own style sheets, so a server cannot // change a rule, only the two values the rules read. import { createHash } from 'node:crypto'; @@ -17,12 +19,18 @@ export const SYLO_ACCENT = Object.freeze({ dark: '#38c8f0', light: '#076787' }); /** The colour of the card the form sits on, per theme (--bg-surface). */ export const CARD = Object.freeze({ dark: '#161618', light: '#ffffff' }); /** - * The least contrast an accent needs against the card: 3:1, the WCAG minimum for interface elements and large text - * (links on these pages are underlined). No colour reaches 4.5:1 on both the dark and the light card, so a higher bar - * would send every server back to Sylo's colour in one theme; at 3:1 mid-tones such as #5865f2 read in both. + * The least contrast an accent needs against the card to be used at all: 3:1, the WCAG minimum for interface + * elements (fills, borders, focus rings, bars). No colour reaches 4.5:1 on both the dark and the light card, so a + * higher bar would send every server back to Sylo's colour in one theme; at 3:1 mid-tones such as #5865f2 read in + * both. Where the accent is used as TEXT (links, the active pill, top ranks) the page uses --accent-text instead: + * the accent, or the same hue lightened (dark theme) or darkened (light theme) until it reaches 4.5:1 (accentText). * The text on a button fill is chosen separately and always reaches 4.5:1 (onAccent). */ export const MIN_CONTRAST = 3; +/** WCAG AA for text. */ +export const MIN_TEXT_CONTRAST = 4.5; +/** The page colour behind the card, per theme (--bg-main). */ +export const PAGE = Object.freeze({ dark: '#0b0b0d', light: '#f5f5f7' }); const HEX = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i; @@ -68,6 +76,41 @@ export function onAccent(accent) { return contrast(accent, '#ffffff') >= contrast(accent, '#000000') ? '#ffffff' : '#000000'; } +const hex2 = (n) => + Math.round(Math.min(255, Math.max(0, n))) + .toString(16) + .padStart(2, '0'); + +/** The colour `t` (0 to 1) of the way from `a` to `b`, both '#rrggbb'. */ +export function mixHex(a, b, t) { + const [x, y] = [channels(a), channels(b)]; + return `#${x.map((c, i) => hex2(c + (y[i] - c) * t)).join('')}`; +} + +/** + * The accent as a text colour in a theme: the accent itself when it reaches 4.5:1 against the card, the page and + * the accent-tinted card (the active pill), else the same hue mixed toward white (dark theme) or black (light + * theme) in small steps until it does. Always reaches 4.5:1 on all three, so the server's colour stays + * recognisable and the text stays readable. + * @param {string} accent '#rrggbb' + * @param {'dark' | 'light'} theme + */ +export function accentText(accent, theme) { + const backs = [CARD[theme], PAGE[theme], mixHex(CARD[theme], accent, 0.14)]; + const ok = (c) => backs.every((b) => contrast(c, b) >= MIN_TEXT_CONTRAST); + if (ok(accent)) return accent; + const target = theme === 'dark' ? '#ffffff' : '#000000'; + for (let t = 0.02; t < 1; t += 0.02) { + const c = mixHex(accent, target, t); + if (ok(c)) return c; + } + return target; +} + +/** The fill of a hovered button: the accent moved 14 % away from the text on it, so the text keeps its contrast. */ +export const accentHover = (accent) => + mixHex(accent, onAccent(accent) === '#ffffff' ? '#000000' : '#ffffff', 0.14); + /** * Is the accent readable on the card, in each theme? `fallback` lists the themes where Sylo's own accent is * used instead, because this one would be too faint or too dark to read there. @@ -98,6 +141,15 @@ export function effectiveAccent(accent) { }; } +/** The colour of accent TEXT that is really used per theme (see accentText; Sylo's own where the accent is not used). */ +export function effectiveAccentText(accent) { + const check = accentCheck(accent); + return { + dark: accent && check.dark.ok ? accentText(accent, 'dark') : SYLO_ACCENT.dark, + light: accent && check.light.ok ? accentText(accent, 'light') : SYLO_ACCENT.light, + }; +} + /** The sentence that says Sylo's accent was used, or null when the chosen one is fine everywhere. */ export function fallbackNote(accent) { const { fallback } = accentCheck(accent); @@ -123,16 +175,16 @@ export const imageHashOf = (data) => createHash('sha256').update(data).digest('h * @param {{ accent: string, imageUrl: string | null }} look */ export function lookCss({ accent, imageUrl }) { + // Only a colour this code wrote: never stored text (a restored backup, a future import) into a style sheet. + if (accent && !/^#[0-9a-f]{6}$/.test(accent)) throw new Error('bad look accent'); const lines = [ "/* The look of one server's public pages: an accent colour and a background, nothing else. */", ]; const check = accentCheck(accent); - if (accent && check.dark.ok) { - lines.push(`:root { --accent: ${accent}; --on-accent: ${onAccent(accent)}; }`); - } - if (accent && check.light.ok) { - lines.push(`:root[data-theme='light'] { --accent: ${accent}; --on-accent: ${onAccent(accent)}; }`); - } + const props = (theme) => + `--accent: ${accent}; --on-accent: ${onAccent(accent)}; --accent-hover: ${accentHover(accent)}; --accent-text: ${accentText(accent, theme)};`; + if (accent && check.dark.ok) lines.push(`:root { ${props('dark')} }`); + if (accent && check.light.ok) lines.push(`:root[data-theme='light'] { ${props('light')} }`); if (imageUrl) { // Only an address this site made (see src/web/routes/publicLook.js): never user text. if (!/^\/look\/[a-z0-9-]+\.[0-9a-f]{16}\.webp$/.test(imageUrl)) throw new Error('bad look image address'); diff --git a/src/web/lib/publicLook.js b/src/web/lib/publicLook.js index 461459f4..19b17869 100644 --- a/src/web/lib/publicLook.js +++ b/src/web/lib/publicLook.js @@ -22,6 +22,7 @@ import { SYLO_ACCENT, accentCheck, effectiveAccent, + effectiveAccentText, fallbackNote, imageHashOf, lookCss, @@ -131,9 +132,17 @@ export const _resetSplashRetry = () => lastFailure.clear(); export async function refreshSplash(guild, { force = false, now = Date.now(), fetch = safeFetch } = {}) { const key = guildKeyOfGuild(guild); const running = inFlight.get(key); - if (running) return running; - const job = doRefresh(guild, key, { force, now, fetch }).finally(() => inFlight.delete(key)); - inFlight.set(key, job); + if (running) { + // A check that is already running answers for everyone who did not ask for more. A forced one (a save, the + // "check now" button) must not take the answer of an unforced one, which may have stopped at the retry gate: + // it runs after it. + if (!force || running.force) return running.job; + return running.job.then(() => refreshSplash(guild, { force, now, fetch })); + } + const job = doRefresh(guild, key, { force, now, fetch }).finally(() => { + if (inFlight.get(key)?.job === job) inFlight.delete(key); + }); + inFlight.set(key, { job, force }); return job; } @@ -223,6 +232,7 @@ export async function lookView(guild, key) { }, effective: { accent: effectiveAccent(row.accent), + accentText: effectiveAccentText(row.accent), contrast: { dark: check.dark, light: check.light }, fallback: check.fallback, note: fallbackNote(row.accent), diff --git a/src/web/public/public.css b/src/web/public/public.css index d5290c89..0f947e9b 100644 --- a/src/web/public/public.css +++ b/src/web/public/public.css @@ -25,6 +25,10 @@ --text: #f5f5f7; --text-muted: #a1a1a6; --accent: #38c8f0; + /* The accent as TEXT (links, the active pill, top ranks): a server's look sets its own, held to 4.5:1. */ + --accent-text: var(--accent); + /* The fill of a hovered button. */ + --accent-hover: color-mix(in srgb, var(--accent) 86%, #fff); /* Text on an accent fill (the primary button): near-black on the bright dark-theme cyan. */ --on-accent: #04141a; --success: #30d158; @@ -55,6 +59,7 @@ --text: #1d1d1f; --text-muted: #6e6e73; --accent: #076787; + --accent-hover: color-mix(in srgb, var(--accent) 88%, #000); --on-accent: #ffffff; --success: #1e7f36; --warn: #b25000; @@ -92,7 +97,7 @@ h2 { text-wrap: balance; } a { - color: var(--accent); + color: var(--accent-text); text-decoration: none; text-underline-offset: 3px; } @@ -209,7 +214,7 @@ a:hover { background-color var(--dur-ui) ease; } .btn:hover { - background: color-mix(in srgb, var(--accent) 86%, var(--text)); + background: var(--accent-hover); color: var(--on-accent); text-decoration: none; } @@ -359,7 +364,7 @@ textarea:focus { .lb-periods a.on { border-color: color-mix(in srgb, var(--accent) 50%, transparent); background: color-mix(in srgb, var(--accent) 14%, transparent); - color: var(--accent); + color: var(--accent-text); } .lb-list { list-style: none; @@ -389,7 +394,7 @@ textarea:focus { font-weight: 700; } .lb-top .lb-rank { - color: var(--accent); + color: var(--accent-text); } .lb-avatar { width: 40px; @@ -592,15 +597,18 @@ textarea:focus { } /* The look of a server's own public pages (src/lib/publicLook.js). The server's style sheet sets only custom - properties: --accent and --on-accent (already read by the rules above) and --look-image. Everything below is - Sylo's: the dim overlay, the semi-opaque panel the page sits on, the readability of the footer. The classes are + properties: --accent, --on-accent, --accent-hover and --accent-text (already read by the rules above) and + --look-image. Everything below is Sylo's: the dim overlay, the semi-opaque panel the page sits on, the readability of the footer. The classes are on : has-look (the server chose something) and has-look-image (it chose a background picture). */ :root { --look-dim: rgba(0, 0, 0, 0.58); --look-panel: 90%; } +/* In the light theme the picture is veiled with light, not black, and the panel is all but opaque, so Sylo's own + text (muted text included) keeps 4.5:1 whatever the picture is (tested in web-v2/src/__tests__/lookPanel.test.js). */ :root[data-theme='light'] { - --look-dim: rgba(0, 0, 0, 0.42); + --look-dim: rgba(245, 245, 247, 0.5); + --look-panel: 99%; } body.has-look-image { background-color: var(--bg-main); @@ -634,3 +642,14 @@ body.has-look main a:not(.btn) { text-decoration: underline; text-underline-offset: 3px; } +/* The "Powered by Sylo" line is the frame's: the same muted, underlined link on every page, whatever the accent. */ +body .lb-foot a, +body .auth-foot a { + color: var(--text-muted); + text-decoration: underline; + text-underline-offset: 3px; +} +body .lb-foot a:hover, +body .auth-foot a:hover { + color: var(--text); +} diff --git a/src/web/routes/publicLook.js b/src/web/routes/publicLook.js index 4e8e9415..c46cfed7 100644 --- a/src/web/routes/publicLook.js +++ b/src/web/routes/publicLook.js @@ -6,7 +6,8 @@ // Both addresses are guild-scoped and named by a content hash. The style sheet is only served while the hash is // the one of the server's current look (so an old address is a plain 404, never a stale look), and the picture // is looked up in THIS server's own pictures by its hash, never by a path. Anything else gets the same plain 404 -// with no detail. The files are immutable: a change is a new address. +// with no detail. The style sheet is immutable (a change is a new address). The picture is named by its hash too, +// but is kept by caches for a day only, so a picture a server removed does not outlive its removal for long. // // The style sheet holds custom properties only (lib/publicLook.js) and the picture is a WebP Sylo made, so the // page's strict CSP stays as it is: styles and images from this site only. @@ -25,7 +26,6 @@ const notFound = (res) => .send('Not found'); const FILE_HEADERS = { - 'Cache-Control': 'public, max-age=31536000, immutable', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; sandbox", 'Cross-Origin-Resource-Policy': 'same-origin', @@ -44,13 +44,18 @@ router.get('/:file', async (req, res, next) => { if (kind === 'css') { const css = await cssFor(key, hash); if (css == null) return notFound(res); - res.set({ ...FILE_HEADERS, 'Content-Type': 'text/css; charset=utf-8' }); + res.set({ + ...FILE_HEADERS, + 'Cache-Control': 'public, max-age=31536000, immutable', + 'Content-Type': 'text/css; charset=utf-8', + }); return res.send(css); } const image = await readLookImage(key, hash); if (!image) return notFound(res); res.set({ ...FILE_HEADERS, + 'Cache-Control': 'public, max-age=86400', 'Content-Type': image.mime, 'Content-Length': String(image.data.length), }); diff --git a/src/web/routes/v2PublicLook.js b/src/web/routes/v2PublicLook.js index 495874a8..375f8b92 100644 --- a/src/web/routes/v2PublicLook.js +++ b/src/web/routes/v2PublicLook.js @@ -1,5 +1,6 @@ // JSON API for Server settings → Public pages: the server's own look on the pages its members open without the -// dashboard (the application form, the ban appeal, the event and quote pages, the web shop). An accent colour and +// dashboard (the application form, the web shop, the ban appeal, the quote page and the leaderboards; the event +// pages carry no server address and take no look). An accent colour and // a background, nothing else: the layout, the type, the components and the "Powered by Sylo" link stay Sylo's. // // Mounted at /guilds/:guildId AFTER the admin guard in v2Api.js, so req.guild is set. Every route here needs the diff --git a/src/web/views/partials/powered.ejs b/src/web/views/partials/powered.ejs index 2c085d98..1f79bede 100644 --- a/src/web/views/partials/powered.ejs +++ b/src/web/views/partials/powered.ejs @@ -1,3 +1,3 @@ <%# The "Powered by Sylo" line at the bottom of every public page. Always shown and not configurable: a server's look (accent colour, background) never touches it. Local: `cls`, the footer's class. %> -

Powered by Sylo

+

Powered by Sylo

diff --git a/test/eventPages.public.test.js b/test/eventPages.public.test.js index 711a8a57..a641219a 100644 --- a/test/eventPages.public.test.js +++ b/test/eventPages.public.test.js @@ -266,8 +266,7 @@ test('an event past its end is ended even before the clock tick has closed it', // The one outward link every public page has: "Powered by Sylo", with rel="noreferrer" so the address of the page // (and the token in it) is never sent on. The event page takes no server look: it has no server id in it. -const POWERED_BY = - /Powered by Sylo<\/a>/; +const POWERED_BY = /Powered by Sylo<\/a>/; test('no host, no member, no role, no channel and no id of any kind', async () => { const html = await page(ev); diff --git a/test/publicLook.lib.test.js b/test/publicLook.lib.test.js index 5c4db933..676813c0 100644 --- a/test/publicLook.lib.test.js +++ b/test/publicLook.lib.test.js @@ -86,7 +86,10 @@ test('the text on an accent fill is white or near-black, whichever reads better' test('the style sheet holds custom properties only, and the accent only in the themes where it is readable', () => { const both = lookCss({ accent: '#5865f2', imageUrl: null }); - assert.match(both, /:root \{ --accent: #5865f2; --on-accent: #ffffff; \}/); + assert.match( + both, + /:root \{ --accent: #5865f2; --on-accent: #ffffff; --accent-hover: #[0-9a-f]{6}; --accent-text: #[0-9a-f]{6}; \}/ + ); assert.match(both, /:root\[data-theme='light'\] \{ --accent: #5865f2;/); assert.doesNotMatch(both, /--look-image/); diff --git a/test/publicLook.readability.test.js b/test/publicLook.readability.test.js new file mode 100644 index 00000000..9be5db97 --- /dev/null +++ b/test/publicLook.readability.test.js @@ -0,0 +1,184 @@ +// What a server's look may NOT do to readability. The accent is held to 3:1 for fills, borders and focus rings; where +// it is used as TEXT the pages use --accent-text, which is the accent or the same hue lightened (dark theme) or +// darkened (light theme) until it reaches 4.5:1 on the card, the page and the accent-tinted card. The text on a +// button fill, also hovered, keeps 4.5:1. Over a background picture Sylo's own text keeps 4.5:1 on the panel and on +// the top bar's glass, whatever the picture is. Values are read from the style sheets themselves. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { + CARD, + PAGE, + accentHover, + accentText, + contrast, + effectiveAccentText, + lookCss, + mixHex, + normaliseAccent, + onAccent, + accentCheck, +} from '../src/lib/publicLook.js'; + +const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n'); + +// A sweep over the colour wheel at several lightnesses, plus the colours that tend to break rules. +const sweep = []; +for (let r = 0; r <= 255; r += 51) + for (let g = 0; g <= 255; g += 51) + for (let b = 0; b <= 255; b += 51) { + sweep.push(`#${[r, g, b].map((c) => c.toString(16).padStart(2, '0')).join('')}`); + } +const edge = ['#5865f2', '#757575', '#787878', '#ffe14d', '#1a2a6c', '#ff0000', '#00ff00', '#0000ff', '#07a']; +const colours = [...new Set([...sweep, ...edge.map(normaliseAccent)])]; + +test('accent text reaches 4.5:1 on the card, the page and the tinted card in both themes, for every colour', () => { + for (const c of colours) { + for (const theme of ['dark', 'light']) { + const text = accentText(c, theme); + const tint = mixHex(CARD[theme], c, 0.14); + for (const [name, back] of [ + ['card', CARD[theme]], + ['page', PAGE[theme]], + ['tint', tint], + ]) { + assert.ok( + contrast(text, back) >= 4.5, + `${c} as ${theme} text on the ${name}: ${text} ${contrast(text, back)}` + ); + } + } + } +}); + +test('blurple stays blurple-ish: the same hue, lightened on the dark theme and darkened on the light one', () => { + const dark = accentText('#5865f2', 'dark'); + const light = accentText('#5865f2', 'light'); + assert.notEqual(dark, '#5865f2', 'it is 3.9:1 on the dark card: not enough for text'); + assert.ok(contrast(dark, '#161618') >= 4.5 && contrast(dark, '#0b0b0d') >= 4.5); + assert.ok(contrast(light, '#ffffff') >= 4.5 && contrast(light, '#f5f5f7') >= 4.5); + // lighter than the accent in dark, darker in light + assert.ok(contrast(dark, '#000000') > contrast('#5865f2', '#000000')); + assert.ok(contrast(light, '#ffffff') > contrast('#5865f2', '#ffffff')); + // a colour that already reads as text is kept as it is + assert.equal(accentText('#ffe14d', 'dark'), '#ffe14d'); + assert.equal(accentText('#1a2a6c', 'light'), '#1a2a6c'); +}); + +test('the text on a button fill reaches 4.5:1, also hovered, for every colour', () => { + for (const c of colours) { + const text = onAccent(c); + assert.ok(contrast(c, text) >= 4.5, `${c} with ${text}`); + assert.ok(contrast(accentHover(c), text) >= 4.5, `${c} hovered with ${text}: ${accentHover(c)}`); + } + // the example from the review: a grey that is 4.61:1 with white must not drop below 4.5 on hover + assert.ok(contrast('#757575', '#ffffff') >= 4.5); + assert.ok(contrast(accentHover('#757575'), onAccent('#757575')) >= 4.5); +}); + +test('the style sheet gives each theme where the accent is used its fill, button text, hover and text colour', () => { + const css = lookCss({ accent: '#5865f2', imageUrl: null }); + const dark = /^:root \{ (.*) \}$/m.exec(css)[1]; + const light = /^:root\[data-theme='light'\] \{ (.*) \}$/m.exec(css)[1]; + for (const [block, theme] of [ + [dark, 'dark'], + [light, 'light'], + ]) { + assert.match(block, /--accent: #5865f2;/); + assert.ok(block.includes(`--on-accent: ${onAccent('#5865f2')};`)); + assert.ok(block.includes(`--accent-hover: ${accentHover('#5865f2')};`)); + assert.ok(block.includes(`--accent-text: ${accentText('#5865f2', theme)};`)); + } + // a theme where the accent is not used keeps Sylo's own text colour too + assert.deepEqual(effectiveAccentText('#1a2a6c').dark, '#38c8f0'); + assert.equal(effectiveAccentText('#1a2a6c').light, accentText('#1a2a6c', 'light')); + assert.deepEqual(accentCheck('#1a2a6c').fallback, ['dark']); +}); + +test('a stored accent that is not a colour this code wrote never reaches a style sheet', () => { + for (const bad of ['red', '#fff', '#FFFFFF', '#12345g', '#fff;} body{display:none', 'url(x)', '#1234567']) { + assert.throws(() => lookCss({ accent: bad, imageUrl: null }), /bad look accent/, bad); + } + assert.doesNotThrow(() => lookCss({ accent: '', imageUrl: null })); +}); + +// --- text on the panel and on the top bar over a picture --------------------------------------------------------- + +function tokens(css, selector) { + const out = {}; + const esc = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + for (const [, body] of css.matchAll(new RegExp(`^${esc} \\{([^}]*)\\}`, 'gm'))) { + for (const m of body.matchAll(/(--[a-z0-9-]+):\s*([^;]+);/g)) out[m[1]] = m[2].trim(); + } + return out; +} +const hex = (c) => `#${c.map((n) => Math.round(n).toString(16).padStart(2, '0')).join('')}`; +const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16)); +const over = (fg, alpha, bg) => fg.map((c, i) => c * alpha + bg[i] * (1 - alpha)); + +const publicCss = read('src/web/public/public.css'); +const lookCssFile = read('web-v2/src/styles/p3-look.css'); +const dashCss = read('web-v2/src/styles.css'); + +for (const [name, css] of [ + ['public.css (server-rendered pages)', publicCss], + ['p3-look.css (dashboard member pages)', lookCssFile], +]) { + const base = { ...tokens(css, ':root') }; + const lightLook = { ...base, ...tokens(css, ":root[data-theme='light']") }; + const darkTokens = tokens(publicCss, ':root'); + const lightTokens = { ...darkTokens, ...tokens(publicCss, ":root[data-theme='light']") }; + + for (const theme of ['dark', 'light']) { + test(`${name}: over the worst picture, ${theme} theme, Sylo's text on the panel keeps 4.5:1`, () => { + const look = theme === 'dark' ? base : lightLook; + const t = theme === 'dark' ? darkTokens : lightTokens; + const dim = /rgba\((\d+), (\d+), (\d+), ([\d.]+)\)/.exec(look['--look-dim']); + const veil = [Number(dim[1]), Number(dim[2]), Number(dim[3])]; + const veilAlpha = Number(dim[4]); + const panel = Number.parseFloat(look['--look-panel']) / 100; + assert.ok(panel > 0 && panel <= 1); + // The picture can be anything from black to white; the veil goes over it, the panel over that. + for (const picture of [rgb('#000000'), rgb('#ffffff'), rgb('#808080')]) { + const backdrop = over(veil, veilAlpha, picture); + const surface = hex(over(rgb(t['--bg-main']), panel, backdrop)); + for (const token of ['--text', '--text-muted']) { + const ratio = contrast(t[token], surface); + assert.ok(ratio >= 4.5, `${token} on the panel over ${hex(picture)}: ${ratio.toFixed(2)}`); + } + } + }); + } +} + +test('over a picture the top bar glass is always on, and its text keeps 4.5:1 on it, whatever the picture', () => { + assert.match(lookCssFile, /body\.has-look-image \.v2-topbar::before \{\s*opacity: 1;/); + const glass = { dark: [11, 11, 13, 0.72], light: [245, 245, 247, 0.72] }; + const dashDark = tokens(dashCss, ':root'); + const dashLight = { ...dashDark, ...tokens(dashCss, ":root[data-theme='light']") }; + const look = { + dark: tokens(lookCssFile, ':root'), + light: tokens(lookCssFile, ":root[data-theme='light']"), + }; + for (const theme of ['dark', 'light']) { + const t = theme === 'dark' ? dashDark : dashLight; + const dim = /rgba\((\d+), (\d+), (\d+), ([\d.]+)\)/.exec( + look[theme]['--look-dim'] ?? look.dark['--look-dim'] + ); + const veil = [Number(dim[1]), Number(dim[2]), Number(dim[3])]; + for (const picture of [rgb('#000000'), rgb('#ffffff'), rgb('#808080')]) { + const backdrop = over(veil, Number(dim[4]), picture); + const [r, g, b, a] = glass[theme]; + const surface = hex(over([r, g, b], a, backdrop)); + assert.ok(contrast(t['--text'], surface) >= 4.5, `${theme} brand text over ${hex(picture)}`); + } + } +}); + +test('the accent is read as text only through --accent-text', () => { + assert.match(publicCss, /^a \{\s*color: var\(--accent-text\);/m); + assert.match(publicCss, /\.lb-periods a\.on \{[^}]*color: var\(--accent-text\);/); + assert.match(publicCss, /\.lb-top \.lb-rank \{\s*color: var\(--accent-text\);/); + assert.match(dashCss, /^a \{\s*color: var\(--accent-text, var\(--accent\)\);/m); + assert.match(publicCss, /\.btn:hover \{\s*background: var\(--accent-hover\);/); +}); diff --git a/test/publicLook.web.test.js b/test/publicLook.web.test.js index 9db4b5ef..953eeb2c 100644 --- a/test/publicLook.web.test.js +++ b/test/publicLook.web.test.js @@ -160,7 +160,7 @@ test('an upload becomes a WebP of at most 1920 px with the metadata gone, served const served = await get(v.upload.url); assert.equal(served.status, 200); assert.equal(served.headers.get('content-type'), 'image/webp'); - assert.equal(served.headers.get('cache-control'), 'public, max-age=31536000, immutable'); + assert.equal(served.headers.get('cache-control'), 'public, max-age=86400'); assert.equal(served.headers.get('cross-origin-resource-policy'), 'same-origin'); assert.equal(served.headers.get('set-cookie'), null); const body = Buffer.from(await served.arrayBuffer()); @@ -354,7 +354,7 @@ test('a page view of a splash server copies the splash in the background, once, test('the public pages take the accent and the background, and always end with the Powered by Sylo link', async () => { await setGuildModule(GID, 'quote-board', { enabled: true, config: { publicPage: true } }); await setGuildModule(GID, 'appeals', { enabled: true }); - const link = /]*>Powered by Sylo<\/a>/; + const link = /]*>Powered by Sylo<\/a>/; const plain = await (await get(`/quotes/${GID}`)).text(); assert.doesNotMatch(plain, /\/look\//, 'a server with no look gets plain Sylo'); @@ -418,3 +418,61 @@ test('purging a server removes its look and both pictures', async () => { assert.deepEqual(await getPublicLook(GID), { accent: '', background: 'none', updatedAt: 0 }); assert.equal(db.prepare('SELECT COUNT(*) AS n FROM guild_public_look WHERE guild_id = ?').get(GID).n, 0); }); + +test('a forced check that lands while an unforced one is running is not answered by it', async () => { + cdnBody = await pic(100, 100, 'webp'); + app.guild.splash = 'f1'; + cdnStatus = 500; + assert.equal((await refreshSplash(app.guild, { force: true })).status, 'failed'); // starts the retry gate + cdnStatus = 200; + // The page view's check stops at the gate; the save's (forced) check, started right behind it, must still run. + const unforced = refreshSplash(app.guild); + const forced = refreshSplash(app.guild, { force: true }); + assert.equal((await unforced).status, 'failed'); + assert.equal((await forced).status, 'updated'); + assert.equal(cdnHits, 2, 'one failed download and one that worked'); + assert.ok(await getLookImageMeta(GID, 'splash')); +}); + +test('the style sheet is kept for a year (its address is its content), the picture for a day', async () => { + const up = await json(await putFile(upload(await pic(40, 40)))); + const v = await json(await save({ accent: '#5865f2', background: 'upload' })); + assert.equal( + (await get(v.effective.css)).headers.get('cache-control'), + 'public, max-age=31536000, immutable' + ); + assert.equal((await get(up.upload.url)).headers.get('cache-control'), 'public, max-age=86400'); +}); + +test('the leaderboards take the look too, and end with the Powered by Sylo link', async () => { + await setGuildModule(GID, 'leveling', { enabled: true, config: { publicLeaderboard: true } }); + await setGuildModule(GID, 'economy', { enabled: true, config: { publicLeaderboard: true } }); + const link = /]*>Powered by Sylo<\/a>/; + for (const path of [`/leaderboard/${GID}`, `/economy/${GID}`]) { + const plain = await get(path); + assert.equal(plain.status, 200, path); + const plainHtml = await plain.text(); + assert.doesNotMatch(plainHtml, /has-look|\/look\//, path); + assert.match(plainHtml, link); + } + await json(await putFile(upload(await pic(200, 100)))); + const v = await json(await save({ accent: '#5865f2', background: 'upload' })); + for (const path of [`/leaderboard/${GID}`, `/economy/${GID}`]) { + const html = await (await get(path)).text(); + assert.ok(html.includes(``), path); + assert.match(html, //, path); + assert.match(html, link, path); + } +}); + +test('the "Powered by Sylo" line is the same muted frame link on every page, whatever the accent', async () => { + await setGuildModule(GID, 'quote-board', { enabled: true, config: { publicPage: true } }); + await save({ accent: '#ff0000', background: 'none' }); + const html = await (await get(`/quotes/${GID}`)).text(); + assert.match( + html, + /

Powered by Sylo<\/a><\/p>/ + ); + const css = await (await get('/public.css')).text(); + assert.match(css, /body \.lb-foot a,\s*body \.auth-foot a \{\s*color: var\(--text-muted\);/); +}); diff --git a/test/publicPagesPolish.test.js b/test/publicPagesPolish.test.js index 4996dcf6..a7fb61b9 100644 --- a/test/publicPagesPolish.test.js +++ b/test/publicPagesPolish.test.js @@ -47,8 +47,15 @@ test('the public 404s have no dashboard button, a generic error still has one', assert.match(lb, /No leaderboard here/); assert.doesNotMatch(lb, /Back to the dashboard/); assert.match(lb, /Go to the dashboard/); - assert.doesNotMatch(lb, /sylobot\.com/, 'never the hosted product, a self-hosted instance has its own'); - assert.match(lb, /Powered by Sylo/); + // The button goes to this instance's own dashboard, never to the hosted one; the one link to the product site is + // the "Powered by Sylo" line. + assert.doesNotMatch( + lb, + /app\.sylobot\.com/, + 'never the hosted dashboard, a self-hosted instance has its own' + ); + assert.match(lb, /Go to the dashboard<\/a>/); + assert.match(lb, /Powered by Sylo<\/a>/); const q = await (await get('/quotes/not-a-server')).text(); assert.doesNotMatch(q, /Back to the dashboard/); diff --git a/test/quotesPublic.test.js b/test/quotesPublic.test.js index 70c67426..3f2fd6c7 100644 --- a/test/quotesPublic.test.js +++ b/test/quotesPublic.test.js @@ -115,8 +115,7 @@ test('no ids leak: not the author, the saver, the channel or the message, and no } assert.doesNotMatch(html, /\/channels\//); // The one outward link every public page has: "Powered by Sylo", with rel="noreferrer". - const poweredBy = - /Powered by Sylo<\/a>/; + const poweredBy = /Powered by Sylo<\/a>/; assert.match(html, poweredBy); assert.doesNotMatch(html.replace(poweredBy, ''), /]*href="https?:/i, 'no outward links but that one'); // nothing that looks like a snowflake besides the server's own id diff --git a/test/upgradeBoot.test.js b/test/upgradeBoot.test.js index f8a9c77d..e012f9b8 100644 --- a/test/upgradeBoot.test.js +++ b/test/upgradeBoot.test.js @@ -645,3 +645,127 @@ test( } } ); + +// --- 5.2 -> this branch: the server look tables (migration 81) ------------------------------------------------ + +const RELEASE_5_2_MIGRATIONS = 80; + +test('SQLite: a database from the 5.2 release boots, gets the public look tables and keeps its rows', () => { + assert.ok( + MIGRATIONS.length > RELEASE_5_2_MIGRATIONS, + 'the server look is migration 81, after the 5.2 release' + ); + const dir = mkdtempSync(join(tmpdir(), 'sylo-upgrade52-')); + try { + const old = join(dir, 'old.db'); + const db = new Database(old); + for (let v = 0; v < RELEASE_5_2_MIGRATIONS; v += 1) { + db.transaction(() => MIGRATIONS[v](db))(); + } + db.pragma(`user_version = ${RELEASE_5_2_MIGRATIONS}`); + for (const table of ['guild_public_look', 'public_look_images']) { + assert.equal( + db.prepare('SELECT name FROM sqlite_master WHERE name = ?').get(table), + undefined, + `5.2 has no ${table}` + ); + } + db.close(); + + boot({ DATABASE_PATH: old }); + const fresh = join(dir, 'fresh.db'); + boot({ DATABASE_PATH: fresh }); + const upgraded = sqliteShape(old); + assert.equal(upgraded.version, MIGRATIONS.length); + assert.deepEqual(upgraded.shape, sqliteShape(fresh).shape); + assert.deepEqual(upgraded.shape['table guild_public_look'], [ + "accent TEXT 1 '' 0", + "background TEXT 1 'none' 0", + 'guild_id TEXT 0 null 1', + 'updated_at INTEGER 1 0 0', + ]); + + // usable: the pictures keep every byte, one per source and server, a replace overwrites + const writable = new Database(old); + const bytes = Buffer.from(Array.from({ length: 256 }, (_, i) => i)); + const put = writable.prepare(`INSERT INTO public_look_images + (guild_id, source, hash, mime, bytes, data, origin, checked_at, created_at) VALUES (?, ?, ?, ?, ?, ?, '', 1, 1) + ON CONFLICT (guild_id, source) DO UPDATE SET hash = excluded.hash, data = excluded.data`); + put.run('g', 'upload', 'a'.repeat(16), 'image/webp', bytes.length, bytes); + put.run('g', 'splash', 'b'.repeat(16), 'image/webp', bytes.length, bytes); + put.run('g', 'upload', 'c'.repeat(16), 'image/webp', bytes.length, Buffer.from('new')); + const rows = writable.prepare('SELECT source, hash, data FROM public_look_images ORDER BY source').all(); + writable.close(); + assert.deepEqual( + rows.map((r) => [r.source, r.hash]), + [ + ['splash', 'b'.repeat(16)], + ['upload', 'c'.repeat(16)], + ] + ); + assert.ok(Buffer.from(rows[0].data).equals(bytes), 'a picture comes back as it went in'); + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test( + 'Postgres: a 5.2 database gets the public look tables from the bootstrap, usable and with the same shape as a fresh one', + { skip: !url && 'DATABASE_URL not set (sqlite-only run)' }, + async (t) => { + const postgres = (await import('postgres')).default; + const admin = postgres(url); + const urlFor = (db) => { + const u = new URL(url); + u.pathname = `/${db}`; + return u.toString(); + }; + const made = []; + const create = async (suffix) => { + const db = `sylo_upgrade52_${suffix}_${process.pid}_${Date.now()}`; + await admin.unsafe(`CREATE DATABASE "${db}"`); + made.push(db); + return db; + }; + t.after(async () => { + for (const db of made) await admin.unsafe(`DROP DATABASE IF EXISTS "${db}" WITH (FORCE)`); + await admin.end({ timeout: 1 }); + }); + const sqliteFile = join(mkdtempSync(join(tmpdir(), 'sylo-upgrade52-pg-')), 'x.db'); + const pgBoot = (db) => boot({ DATABASE_URL: urlFor(db), DATABASE_PATH: sqliteFile }); + + const freshDb = await create('fresh'); + pgBoot(freshDb); + const oldDb = await create('old'); + pgBoot(oldDb); + const old = postgres(urlFor(oldDb)); + await old.unsafe(` + DROP TABLE IF EXISTS guild_public_look; + DROP TABLE IF EXISTS public_look_images; + DELETE FROM schema_migrations; + INSERT INTO schema_migrations (version) VALUES (${RELEASE_5_2_MIGRATIONS}); + `); + const [gone] = await old`SELECT to_regclass('public.public_look_images') AS t`; + assert.equal(gone.t, null, 'the 5.2 shape has no look tables'); + await old.end({ timeout: 1 }); + + pgBoot(oldDb); + + const a = postgres(urlFor(freshDb)); + const b = postgres(urlFor(oldDb)); + try { + assert.deepEqual(await pgShape(b), await pgShape(a)); + const bytes = Buffer.from(Array.from({ length: 256 }, (_, i) => i)); + await b`INSERT INTO public_look_images (guild_id, source, hash, mime, bytes, data, origin, checked_at, created_at) + VALUES ('g', 'upload', ${'a'.repeat(16)}, 'image/webp', ${bytes.length}, ${bytes}, '', 1, 1)`; + const [stored] = await b`SELECT data FROM public_look_images`; + assert.ok(Buffer.from(stored.data).equals(bytes), 'a picture comes back as it went in'); + await b`INSERT INTO guild_public_look (guild_id, accent, background, updated_at) VALUES ('g', '#5865f2', 'upload', 1)`; + const [look] = await b`SELECT accent, background FROM guild_public_look`; + assert.deepEqual([look.accent, look.background], ['#5865f2', 'upload']); + } finally { + await a.end({ timeout: 1 }); + await b.end({ timeout: 1 }); + } + } +); diff --git a/test/v2.accessLevels.test.js b/test/v2.accessLevels.test.js index 10936c04..92c167ea 100644 --- a/test/v2.accessLevels.test.js +++ b/test/v2.accessLevels.test.js @@ -148,6 +148,7 @@ const WRITES = [ ['/access', { viewRoleIds: [VIEW, OTHER_ROLE] }, 200], ['/setup/apply', { items: [] }, 400], ['/public-page-look', { accent: '', background: 'none' }, 200], + ['/public-page-look/image', {}, 415], ['/public-page-look/image/delete', {}, 200], ['/public-page-look/splash/refresh', {}, 200], ]; @@ -708,3 +709,28 @@ test("the server's look on its public pages is Edit only, the read too, on the w const fluxer = await person({ platform: 'fluxer', roles: [VIEW] }); assert.equal((await fluxer.app.get(`/guilds/${F_KEY}/public-page-look`)).status, 403); }); + +test("Fluxer: an Edit person saves the server's look, and its files answer at the fluxer- address", async () => { + await setBotMasterRoles(F_KEY, [MASTER]); + const { app } = await person({ platform: 'fluxer', roles: [MASTER] }); + const saved = await app.post(`/guilds/${F_KEY}/public-page-look`, { + accent: '#5865f2', + background: 'none', + }); + assert.equal(saved.status, 200); + const look = await saved.json(); + assert.equal(look.platform, 'fluxer'); + assert.match(look.effective.css, new RegExp(`^/look/fluxer-${F_GUILD}\\.[0-9a-f]{16}\\.css$`)); + const sheet = await browser().get(look.effective.css); + assert.equal(sheet.status, 200); + assert.match(await sheet.text(), /--accent: #5865f2;/); + // the Discord server with the same digits has no such look + assert.equal((await browser().get(look.effective.css.replace(`fluxer-${F_GUILD}`, F_GUILD))).status, 404); + // a page of that server renders it: the public leaderboard + await setGuildModule(F_KEY, 'leveling', { enabled: true, config: { publicLeaderboard: true } }); + const page = await browser().get(`/leaderboard/${encodeURIComponent(F_KEY)}`); + assert.equal(page.status, 200); + const html = await page.text(); + assert.ok(html.includes(look.effective.css)); + assert.match(html, //); +}); diff --git a/test/v2Apply.test.js b/test/v2Apply.test.js index c621214a..71f29fe6 100644 --- a/test/v2Apply.test.js +++ b/test/v2Apply.test.js @@ -493,3 +493,66 @@ test('a Fluxer server works with the Fluxer login, and a Discord login is not lo assert.equal((await discordOnly.get(path(FKEY, formId))).status, 404); assert.equal(profiles.discord.id, ME); }); + +// --- the server's own look (accent colour, background) in the page's data ------------------------------------ + +test("the page carries the server's look when it chose one, and null when it did not", async () => { + const { setPublicLook, putLookImage } = await import('../src/db/publicLook.js'); + const { imageHashOf } = await import('../src/lib/publicLook.js'); + await enable(); + const me = await signedIn('A'); + memberOf(dGuild, ME); + const formId = await makeForm(D_GUILD); + assert.equal((await (await me.get(path(D_GUILD, formId))).json()).look, null); + + await setPublicLook(D_GUILD, { accent: '#5865f2', background: 'none' }); + const accentOnly = (await (await me.get(path(D_GUILD, formId))).json()).look; + assert.match(accentOnly.css, new RegExp(`^/look/${D_GUILD}\\.[0-9a-f]{16}\\.css$`)); + assert.equal(accentOnly.image, false); + const sheet = await browser().get(accentOnly.css); + assert.equal(sheet.status, 200); + assert.match(await sheet.text(), /--accent: #5865f2;/); + + const data = Buffer.from('RIFF....WEBPVP8 not a real picture but the route does not decode'); + await putLookImage(D_GUILD, 'upload', { hash: imageHashOf(data), mime: 'image/webp', data }); + await setPublicLook(D_GUILD, { accent: '#5865f2', background: 'upload' }); + const withImage = (await (await me.get(path(D_GUILD, formId))).json()).look; + assert.equal(withImage.image, true); + assert.notEqual(withImage.css, accentOnly.css, 'a new picture is a new address'); + // the not-found answer never carries a look + const closed = await me.get(path('900000000000099999', formId)); + assert.deepEqual(await closed.json(), { error: 'Not found' }); +}); + +test('a Fluxer server takes its look end to end: the page data, the fluxer- files and the picture', async () => { + const { setPublicLook, putLookImage } = await import('../src/db/publicLook.js'); + const { imageHashOf } = await import('../src/lib/publicLook.js'); + await enable(FKEY); + const formId = await makeForm(FKEY); + ME = nextId('30000000000001'); + FME = nextId('40000000000001'); + setProfiles({ discordId: ME, fluxerId: FME }); + const b = browser(); + await signIn(b, 'fluxer'); + const headers = { accept: 'application/json' }; + memberOf(fGuild, FME); + + const data = Buffer.from('RIFF....WEBPVP8 stand-in bytes'); + await putLookImage(FKEY, 'upload', { hash: imageHashOf(data), mime: 'image/webp', data }); + await setPublicLook(FKEY, { accent: '#5865f2', background: 'upload' }); + + const page = await (await b.get(`/api/v2${path(FKEY, formId)}`, { headers })).json(); + assert.match(page.look.css, new RegExp(`^/look/fluxer-${F_GUILD}\\.[0-9a-f]{16}\\.css$`)); + assert.equal(page.look.image, true); + const sheet = await browser().get(page.look.css); + assert.equal(sheet.status, 200); + const css = await sheet.text(); + assert.match(css, /--accent: #5865f2;/); + const imageUrl = /url\('([^']+)'\)/.exec(css)[1]; + assert.match(imageUrl, new RegExp(`^/look/fluxer-${F_GUILD}\\.[0-9a-f]{16}\\.webp$`)); + const picture = await browser().get(imageUrl); + assert.equal(picture.status, 200); + assert.equal(picture.headers.get('cache-control'), 'public, max-age=86400'); + // the Discord address of the same digits is another server: nothing there + assert.equal((await browser().get(imageUrl.replace(`fluxer-${F_GUILD}`, F_GUILD))).status, 404); +}); diff --git a/test/v2WebShop.test.js b/test/v2WebShop.test.js index 14c0fd2a..3d9927d0 100644 --- a/test/v2WebShop.test.js +++ b/test/v2WebShop.test.js @@ -126,6 +126,13 @@ test('a member sees their balance, the items for sale (not the paused ones) and const page = await view(res); assert.deepEqual(page.currency, { name: 'gold', emoji: '💰' }); assert.deepEqual(page.balance, { cash: 250, bank: 0, total: 250 }); + // the server's own look (accent colour, background): none until it chose one + assert.equal(page.look, null); + const { setPublicLook } = await import('../src/db/publicLook.js'); + await setPublicLook(D_GUILD, { accent: '#5865f2', background: 'none' }); + const looked = await view(await me.get(`/shop/${D_GUILD}`)); + assert.match(looked.look.css, new RegExp(`^/look/${D_GUILD}\\.[0-9a-f]{16}\\.css$`)); + assert.equal(looked.look.image, false); assert.deepEqual( page.items.map((i) => i.name), ['Cheap', 'Dear', 'VIP'] diff --git a/web-v2/src/__tests__/PublicPagesSettings.test.jsx b/web-v2/src/__tests__/PublicPagesSettings.test.jsx index e1ced92f..e375524f 100644 --- a/web-v2/src/__tests__/PublicPagesSettings.test.jsx +++ b/web-v2/src/__tests__/PublicPagesSettings.test.jsx @@ -88,6 +88,9 @@ describe('Server settings: Public pages', () => { fireEvent.change(input, { target: { value: '#5865F2' } }); expect(preview.style.getPropertyValue('--accent')).toBe('#5865f2'); + // the link in the preview uses the text colour made from the accent (4.5:1), not the accent itself + expect(preview.style.getPropertyValue('--accent-text')).toMatch(/^#[0-9a-f]{6}$/); + expect(preview.style.getPropertyValue('--accent-text')).not.toBe('#5865f2'); expect(screen.queryByText(/too hard to read/)).toBeNull(); expect(screen.getByText('Submit application')).toBeTruthy(); expect(screen.getByText('Powered by Sylo', { selector: 'p' })).toBeTruthy(); diff --git a/web-v2/src/__tests__/publicLook.test.jsx b/web-v2/src/__tests__/publicLook.test.jsx index 1d7df038..8d8d5ce9 100644 --- a/web-v2/src/__tests__/publicLook.test.jsx +++ b/web-v2/src/__tests__/publicLook.test.jsx @@ -40,6 +40,9 @@ describe('the accent rules agree with the server', () => { expect(mine.light.color, c).toBe(theirs.light); expect(mine.dark.ok, c).toBe(check.dark.ok); expect(mine.light.ok, c).toBe(check.light.ok); + const text = server.effectiveAccentText(c); + expect(mine.dark.text, c).toBe(text.dark); + expect(mine.light.text, c).toBe(text.light); expect(accentNote(c), c).toBe(server.fallbackNote(c)); if (c) expect(onAccent(c), c).toBe(server.onAccent(c)); } @@ -97,7 +100,7 @@ describe('the Powered by Sylo link', () => { ); const link = container.querySelector('footer a'); expect(link.textContent).toBe('Powered by Sylo'); - expect(link.getAttribute('href')).toBe('https://github.com/Ferdinand99/Sylo'); + expect(link.getAttribute('href')).toBe('https://sylobot.com'); expect(link.getAttribute('rel')).toBe('noopener noreferrer'); unmount(); } diff --git a/web-v2/src/components/PoweredBy.jsx b/web-v2/src/components/PoweredBy.jsx index e2216967..90041710 100644 --- a/web-v2/src/components/PoweredBy.jsx +++ b/web-v2/src/components/PoweredBy.jsx @@ -3,7 +3,7 @@ export default function PoweredBy() { return (

diff --git a/web-v2/src/components/PublicPagesSettings.jsx b/web-v2/src/components/PublicPagesSettings.jsx index 4cf44349..8f4dcad5 100644 --- a/web-v2/src/components/PublicPagesSettings.jsx +++ b/web-v2/src/components/PublicPagesSettings.jsx @@ -22,7 +22,8 @@ const currentTheme = () => /** * Server settings → Public pages: the server's own accent colour and background on the pages its members open - * without the dashboard (the application form, the ban appeal, the event and quote pages, the web shop). Only + * without the dashboard (the application form, the web shop, the ban appeal, the quote page and the leaderboards; + * the event pages carry no server address and take no look). Only * these two things change; the layout, the type, the light and dark themes and the "Powered by Sylo" link stay * Sylo's. The preview is the application form page. Edit level only (the section is not shown below it). */ @@ -57,6 +58,7 @@ export default function PublicPagesSettings({ guildId }) { const theme = currentTheme(); const outcome = accentOutcome(invalid ? '' : normalised); const shown = outcome[theme].color; + const shownText = outcome[theme].text; const splash = data.splash; const image = @@ -113,9 +115,10 @@ export default function PublicPagesSettings({ guildId }) {

Public pages

- Give the pages your members open without the dashboard (application forms, ban appeals, events, quotes - and the web shop) your server's accent colour and a background. Only these two things change: the - layout, the type, the light and dark themes and the "Powered by Sylo" link stay as they are. + Give the pages your members open without the dashboard (application forms, the web shop, ban appeals, + the quote page and the leaderboards) your server's accent colour and a background. Only these two + things change: the layout, the type, the light and dark themes and the "Powered by Sylo" + link stay as they are.

@@ -222,6 +225,7 @@ export default function PublicPagesSettings({ guildId }) { aria-label="Preview of an application form page with this accent colour and background" style={{ '--accent': shown, + '--accent-text': shownText, '--on-accent': onAccent(shown), ...(image ? { backgroundImage: `linear-gradient(var(--look-dim), var(--look-dim)), url("${image}")` } diff --git a/web-v2/src/publicLook.js b/web-v2/src/publicLook.js index 72e14880..379516b0 100644 --- a/web-v2/src/publicLook.js +++ b/web-v2/src/publicLook.js @@ -1,9 +1,9 @@ // The server's own look on the public member pages, on the page side (the server's half is -// src/lib/publicLook.js, which has the last word; the contrast rule below is the same, so the settings preview can +// src/lib/publicLook.js, which has the last word; the contrast rules below are the same, so the settings preview can // say at once what a colour will do). Two things: // - useServerLook(look): the pages a member opens inside the dashboard (the application form, the web shop) // load the server's style sheet (custom properties only) and mark , the same way the server renders the -// appeal, event and quote pages. +// appeal, quote and leaderboard pages (the event pages take no look: they carry no server address). // - the accent rules the "Public pages" settings preview uses. import { useEffect } from 'react'; @@ -12,6 +12,10 @@ export const SYLO_ACCENT = { dark: '#38c8f0', light: '#076787' }; export const CARD = { dark: '#161618', light: '#ffffff' }; /** The least contrast of an accent against the card (3:1, see src/lib/publicLook.js). */ export const MIN_CONTRAST = 3; +/** WCAG AA for text, what accent text is held to. */ +export const MIN_TEXT_CONTRAST = 4.5; +/** The page colour behind the card, per theme. */ +export const PAGE = { dark: '#0b0b0d', light: '#f5f5f7' }; /** '#rrggbb' in lower case, '' for none, null when it is not a colour. */ export function normaliseAccent(value) { @@ -40,6 +44,34 @@ export function contrast(a, b) { return (hi + 0.05) / (lo + 0.05); } +const hex2 = (n) => + Math.round(Math.min(255, Math.max(0, n))) + .toString(16) + .padStart(2, '0'); +const channels = (hex) => { + const n = parseInt(hex.slice(1), 16); + return [(n >> 16) & 255, (n >> 8) & 255, n & 255]; +}; + +/** The colour `t` of the way from `a` to `b`, both '#rrggbb'. */ +export function mixHex(a, b, t) { + const [x, y] = [channels(a), channels(b)]; + return `#${x.map((c, i) => hex2(c + (y[i] - c) * t)).join('')}`; +} + +/** The accent as a text colour in a theme (the same rule as the server: 4.5:1 on card, page and tinted card). */ +export function accentText(accent, theme) { + const backs = [CARD[theme], PAGE[theme], mixHex(CARD[theme], accent, 0.14)]; + const ok = (c) => backs.every((b) => contrast(c, b) >= MIN_TEXT_CONTRAST); + if (ok(accent)) return accent; + const target = theme === 'dark' ? '#ffffff' : '#000000'; + for (let t = 0.02; t < 1; t += 0.02) { + const c = mixHex(accent, target, t); + if (ok(c)) return c; + } + return target; +} + /** The text colour on a fill of this accent. */ export const onAccent = (accent) => contrast(accent, '#ffffff') >= contrast(accent, '#000000') ? '#ffffff' : '#000000'; @@ -54,6 +86,7 @@ export function accentOutcome(accent) { ratio: ratio == null ? null : Math.round(ratio * 100) / 100, ok, color: accent && ok ? accent : SYLO_ACCENT[theme], + text: accent && ok ? accentText(accent, theme) : SYLO_ACCENT[theme], }; } return out; diff --git a/web-v2/src/styles.css b/web-v2/src/styles.css index 9c21d66f..a07f585f 100644 --- a/web-v2/src/styles.css +++ b/web-v2/src/styles.css @@ -174,7 +174,7 @@ h4 { } a { - color: var(--accent); + color: var(--accent-text, var(--accent)); text-decoration: none; text-decoration-thickness: 1px; text-underline-offset: 3px; diff --git a/web-v2/src/styles/p3-look.css b/web-v2/src/styles/p3-look.css index 2eaa8329..616fd641 100644 --- a/web-v2/src/styles/p3-look.css +++ b/web-v2/src/styles/p3-look.css @@ -1,13 +1,16 @@ /* The look of a server's public pages inside the dashboard (the application form, the web shop) and the - "Powered by Sylo" line. The server's style sheet (/look/...) sets only custom properties: --accent and - --on-accent (the dashboard already reads them) and --look-image. Everything here is Sylo's: the dim overlay, the + "Powered by Sylo" line. The server's style sheet (/look/...) sets only custom properties: --accent, + --on-accent, --accent-hover and --accent-text (the dashboard already reads them) and --look-image. Everything here is Sylo's: the dim overlay, the panel the page sits on, the primary button taking the accent. public.css has the same for the EJS pages. */ :root { --look-dim: rgba(0, 0, 0, 0.58); --look-panel: 90%; } +/* Light theme: the picture is veiled with light, not black, and the panel is all but opaque, so Sylo's own text + keeps 4.5:1 whatever the picture is (tested in __tests__/lookPanel.test.js). */ :root[data-theme='light'] { - --look-dim: rgba(0, 0, 0, 0.42); + --look-dim: rgba(245, 245, 247, 0.5); + --look-panel: 99%; } .v2-powered { @@ -48,6 +51,11 @@ body.has-look-image .v2-public-page { -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); } +/* Over a picture the top bar's glass is always on (it is otherwise only on once the page scrolls), so the brand + and the theme switch never sit directly on the picture. */ +body.has-look-image .v2-topbar::before { + opacity: 1; +} body.has-look-image .v2-powered { padding-top: 0; } @@ -55,7 +63,7 @@ body.has-look-image .v2-powered a { display: inline-block; padding: 3px 12px; border-radius: var(--radius-pill); - background: color-mix(in srgb, var(--bg-main) 88%, transparent); + background: color-mix(in srgb, var(--bg-main) var(--look-panel), transparent); } @media (prefers-reduced-transparency: reduce) { body.has-look-image .v2-public-page, @@ -122,7 +130,7 @@ body.has-look-image .v2-powered a { font-size: var(--fs-sm); } .v2-look-preview-link { - color: var(--accent); + color: var(--accent-text); text-decoration: underline; } .v2-look-preview-field { From b42f4f6ca8ce93409092c3438b767f86620aab87 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Mon, 16 Nov 2026 02:10:00 +0100 Subject: [PATCH 4/9] fix(public-pages): a theme where the accent falls back keeps Sylo's text colour - --accent-text is declared in both themes of public.css and dashux.css, so a look sheet that only has a dark block can no longer leak its text colour into the light theme - accent text is also held to 4.5:1 on the page tinted with the accent (the active pill) - test resolves the cascade per theme for the server-rendered and the dashboard pages - comments point at the real contrast test; a slow settings test gets a longer wait --- src/lib/publicLook.js | 9 ++- src/web/public/public.css | 4 +- test/publicLook.readability.test.js | 75 ++++++++++++++++++- .../__tests__/PublicPagesSettings.test.jsx | 5 +- web-v2/src/dashux.css | 4 + web-v2/src/publicLook.js | 9 ++- web-v2/src/styles/p3-look.css | 2 +- 7 files changed, 98 insertions(+), 10 deletions(-) diff --git a/src/lib/publicLook.js b/src/lib/publicLook.js index 6b26cb83..9c302e66 100644 --- a/src/lib/publicLook.js +++ b/src/lib/publicLook.js @@ -89,14 +89,19 @@ export function mixHex(a, b, t) { /** * The accent as a text colour in a theme: the accent itself when it reaches 4.5:1 against the card, the page and - * the accent-tinted card (the active pill), else the same hue mixed toward white (dark theme) or black (light + * both accent-tinted (the active pill sits on the page or the card), else the same hue mixed toward white (dark theme) or black (light * theme) in small steps until it does. Always reaches 4.5:1 on all three, so the server's colour stays * recognisable and the text stays readable. * @param {string} accent '#rrggbb' * @param {'dark' | 'light'} theme */ export function accentText(accent, theme) { - const backs = [CARD[theme], PAGE[theme], mixHex(CARD[theme], accent, 0.14)]; + const backs = [ + CARD[theme], + PAGE[theme], + mixHex(CARD[theme], accent, 0.14), + mixHex(PAGE[theme], accent, 0.14), + ]; const ok = (c) => backs.every((b) => contrast(c, b) >= MIN_TEXT_CONTRAST); if (ok(accent)) return accent; const target = theme === 'dark' ? '#ffffff' : '#000000'; diff --git a/src/web/public/public.css b/src/web/public/public.css index 0f947e9b..f8cbfcdb 100644 --- a/src/web/public/public.css +++ b/src/web/public/public.css @@ -59,6 +59,8 @@ --text: #1d1d1f; --text-muted: #6e6e73; --accent: #076787; + /* Declared in both themes: a look that only has a dark block must not leak its text colour into this one. */ + --accent-text: var(--accent); --accent-hover: color-mix(in srgb, var(--accent) 88%, #000); --on-accent: #ffffff; --success: #1e7f36; @@ -605,7 +607,7 @@ textarea:focus { --look-panel: 90%; } /* In the light theme the picture is veiled with light, not black, and the panel is all but opaque, so Sylo's own - text (muted text included) keeps 4.5:1 whatever the picture is (tested in web-v2/src/__tests__/lookPanel.test.js). */ + text (muted text included) keeps 4.5:1 whatever the picture is (tested in test/publicLook.readability.test.js). */ :root[data-theme='light'] { --look-dim: rgba(245, 245, 247, 0.5); --look-panel: 99%; diff --git a/test/publicLook.readability.test.js b/test/publicLook.readability.test.js index 9be5db97..af15b355 100644 --- a/test/publicLook.readability.test.js +++ b/test/publicLook.readability.test.js @@ -29,18 +29,31 @@ for (let r = 0; r <= 255; r += 51) for (let b = 0; b <= 255; b += 51) { sweep.push(`#${[r, g, b].map((c) => c.toString(16).padStart(2, '0')).join('')}`); } -const edge = ['#5865f2', '#757575', '#787878', '#ffe14d', '#1a2a6c', '#ff0000', '#00ff00', '#0000ff', '#07a']; +const edge = [ + '#5865f2', + '#757575', + '#787878', + '#ffe14d', + '#1a2a6c', + '#ff0000', + '#00ff00', + '#0000ff', + '#07a', + '#cc2266', +]; const colours = [...new Set([...sweep, ...edge.map(normaliseAccent)])]; -test('accent text reaches 4.5:1 on the card, the page and the tinted card in both themes, for every colour', () => { +test('accent text reaches 4.5:1 on the card, the page and both tinted backgrounds in both themes, for every colour', () => { for (const c of colours) { for (const theme of ['dark', 'light']) { const text = accentText(c, theme); const tint = mixHex(CARD[theme], c, 0.14); + const pageTint = mixHex(PAGE[theme], c, 0.14); // the active period pill sits on the page or the panel for (const [name, back] of [ ['card', CARD[theme]], ['page', PAGE[theme]], - ['tint', tint], + ['card tint', tint], + ['page tint', pageTint], ]) { assert.ok( contrast(text, back) >= 4.5, @@ -182,3 +195,59 @@ test('the accent is read as text only through --accent-text', () => { assert.match(dashCss, /^a \{\s*color: var\(--accent-text, var\(--accent\)\);/m); assert.match(publicCss, /\.btn:hover \{\s*background: var\(--accent-hover\);/); }); + +// --- the cascade: a theme where the accent falls back keeps Sylo's own text colour ------------------------------ + +/** + * The custom properties of a theme after the cascade over the given style sheets in order, "var(--x)" resolved: + * `:root` counts for both themes, `:root[data-theme='light']` (more specific) only for the light one; at equal + * specificity the later sheet wins. + */ +function cascade(theme, sheets) { + const won = {}; + for (const css of sheets) { + const blocks = [[1, tokens(css, ':root')]]; + if (theme === 'light') blocks.push([2, tokens(css, ":root[data-theme='light']")]); + for (const [spec, map] of blocks) { + for (const [name, value] of Object.entries(map)) { + if (!won[name] || spec >= won[name].spec) won[name] = { spec, value }; + } + } + } + const resolve = (name, depth = 0) => { + const raw = won[name]?.value; + if (raw == null || depth > 8) return raw; + const ref = /^var\((--[a-z0-9-]+)\)$/.exec(raw); + return ref ? resolve(ref[1], depth + 1) : raw; + }; + return (name) => resolve(name); +} + +const SYLO = { dark: '#38c8f0', light: '#076787' }; +const surfaces = { + 'the server-rendered pages': [publicCss], + 'the dashboard pages': [dashCss, read('web-v2/src/dashux.css')], +}; + +for (const [where, sheets] of Object.entries(surfaces)) { + for (const accent of ['#ffe14d', '#00ff00', '#1a2a6c', '#5865f2']) { + for (const theme of ['dark', 'light']) { + test(`${where}: ${accent} in the ${theme} theme resolves its text colour like the rule says`, () => { + const look = lookCss({ accent, imageUrl: null }); + const get = cascade(theme, [...sheets, look]); + const used = accentCheck(accent)[theme].ok; + const accentTextHere = get('--accent-text'); + if (used) { + assert.equal(get('--accent'), accent); + assert.equal(accentTextHere, accentText(accent, theme)); + } else { + // the accent falls back here: Sylo's own colour, for the fill AND for text and hover + assert.equal(get('--accent'), SYLO[theme]); + assert.equal(accentTextHere, SYLO[theme], `${accent} leaked into ${theme} as text`); + } + assert.ok(contrast(accentTextHere, CARD[theme]) >= 4.5, `${accent} ${theme} link on the card`); + assert.ok(contrast(accentTextHere, PAGE[theme]) >= 4.5, `${accent} ${theme} link on the page`); + }); + } + } +} diff --git a/web-v2/src/__tests__/PublicPagesSettings.test.jsx b/web-v2/src/__tests__/PublicPagesSettings.test.jsx index e375524f..a412089c 100644 --- a/web-v2/src/__tests__/PublicPagesSettings.test.jsx +++ b/web-v2/src/__tests__/PublicPagesSettings.test.jsx @@ -1,8 +1,11 @@ -import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { configure, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import PublicPagesSettings from '../components/PublicPagesSettings.jsx'; import { AccessProvider } from '../access.jsx'; +// the whole suite runs on two busy CPUs in CI: role queries with names are slow in jsdom +configure({ asyncUtilTimeout: 5000 }); + vi.mock('../api.js', () => ({ ApiError: class ApiError extends Error {}, getPublicLook: vi.fn(), diff --git a/web-v2/src/dashux.css b/web-v2/src/dashux.css index 6bfb48c5..467677f4 100644 --- a/web-v2/src/dashux.css +++ b/web-v2/src/dashux.css @@ -5,10 +5,14 @@ :root { /* Text on an accent fill: near-black on the bright dark-theme cyan, white on the deeper light-theme one. */ --on-accent: #04141a; + /* The accent as text; a server's look sets its own per theme (src/lib/publicLook.js). Declared in both themes so + a look that only has a dark block never leaks its text colour into the light one. */ + --accent-text: var(--accent); --accent-hover: color-mix(in srgb, var(--accent) 86%, #fff); } :root[data-theme='light'] { --on-accent: #ffffff; + --accent-text: var(--accent); --accent-hover: color-mix(in srgb, var(--accent) 88%, #000); } diff --git a/web-v2/src/publicLook.js b/web-v2/src/publicLook.js index 379516b0..290b5a21 100644 --- a/web-v2/src/publicLook.js +++ b/web-v2/src/publicLook.js @@ -59,9 +59,14 @@ export function mixHex(a, b, t) { return `#${x.map((c, i) => hex2(c + (y[i] - c) * t)).join('')}`; } -/** The accent as a text colour in a theme (the same rule as the server: 4.5:1 on card, page and tinted card). */ +/** The accent as a text colour in a theme (the same rule as the server: 4.5:1 on card, page and both tinted). */ export function accentText(accent, theme) { - const backs = [CARD[theme], PAGE[theme], mixHex(CARD[theme], accent, 0.14)]; + const backs = [ + CARD[theme], + PAGE[theme], + mixHex(CARD[theme], accent, 0.14), + mixHex(PAGE[theme], accent, 0.14), + ]; const ok = (c) => backs.every((b) => contrast(c, b) >= MIN_TEXT_CONTRAST); if (ok(accent)) return accent; const target = theme === 'dark' ? '#ffffff' : '#000000'; diff --git a/web-v2/src/styles/p3-look.css b/web-v2/src/styles/p3-look.css index 616fd641..ce4d16c4 100644 --- a/web-v2/src/styles/p3-look.css +++ b/web-v2/src/styles/p3-look.css @@ -7,7 +7,7 @@ --look-panel: 90%; } /* Light theme: the picture is veiled with light, not black, and the panel is all but opaque, so Sylo's own text - keeps 4.5:1 whatever the picture is (tested in __tests__/lookPanel.test.js). */ + keeps 4.5:1 whatever the picture is (tested in test/publicLook.readability.test.js). */ :root[data-theme='light'] { --look-dim: rgba(245, 245, 247, 0.5); --look-panel: 99%; From 865e1b77ae8312de71f130fd58b5fd6b880506f2 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Mon, 16 Nov 2026 02:16:19 +0100 Subject: [PATCH 5/9] fix(public-pages): keep the settings form's edits in a draft instead of copying the saved values in an effect --- .../__tests__/PublicPagesSettings.test.jsx | 1 - web-v2/src/components/PublicPagesSettings.jsx | 22 +++++++++---------- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/web-v2/src/__tests__/PublicPagesSettings.test.jsx b/web-v2/src/__tests__/PublicPagesSettings.test.jsx index a412089c..6a9f5c51 100644 --- a/web-v2/src/__tests__/PublicPagesSettings.test.jsx +++ b/web-v2/src/__tests__/PublicPagesSettings.test.jsx @@ -72,7 +72,6 @@ describe('Server settings: Public pages', () => { api.getPublicLook.mockResolvedValue(look({ accent: '#5865f2' })); renderSection(); expect(await screen.findByText('Public pages')).toBeTruthy(); - // the form takes the saved value in an effect, right after the first render with the data await waitFor(() => expect(screen.getByLabelText('Accent colour').value).toBe('#5865f2')); expect( screen.getByText( diff --git a/web-v2/src/components/PublicPagesSettings.jsx b/web-v2/src/components/PublicPagesSettings.jsx index 8f4dcad5..3107c209 100644 --- a/web-v2/src/components/PublicPagesSettings.jsx +++ b/web-v2/src/components/PublicPagesSettings.jsx @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react'; +import { useRef, useState } from 'react'; import { deletePublicLookImage, getPublicLook, @@ -34,20 +34,18 @@ export default function PublicPagesSettings({ guildId }) { () => (allowed ? Promise.resolve().then(() => getPublicLook(guildId)) : Promise.resolve(null)), [guildId, allowed] ); - const [accent, setAccent] = useState(''); - const [background, setBackground] = useState('none'); + // What the person has typed or chosen, on top of what is saved. It belongs to one saved state (the server and its + // saved colour and background): a new one (another server, or a save) starts the form from it again. No effect is + // needed to copy the saved values in, so there is no moment where a late copy overwrites an edit. + const [draft, setDraft] = useState(null); const [busy, setBusy] = useState(false); const fileInput = useRef(null); - - // Start from what is saved, and again when another server's answer arrives. const savedFor = data ? `${guildId}|${data.accent}|${data.background}` : null; - useEffect(() => { - if (!data) return; - setAccent(data.accent); - setBackground(data.background); - // only a new saved state resets the form, not every answer (an upload changes the picture, not the choice) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [savedFor]); + const mine = draft && draft.for === savedFor ? draft : null; + const accent = mine?.accent ?? data?.accent ?? ''; + const background = mine?.background ?? data?.background ?? 'none'; + const setAccent = (value) => setDraft({ for: savedFor, accent: value, background }); + const setBackground = (value) => setDraft({ for: savedFor, accent, background: value }); if (!allowed || error || !data) return null; From 84cdc921c6068ef32876461c247cd66c545fff56 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Mon, 16 Nov 2026 02:25:18 +0100 Subject: [PATCH 6/9] fix(public-pages): keep a colour typed during an upload or a removal in the settings form --- .../__tests__/PublicPagesSettings.test.jsx | 54 +++++++++++++++++++ web-v2/src/components/PublicPagesSettings.jsx | 27 ++++++---- 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/web-v2/src/__tests__/PublicPagesSettings.test.jsx b/web-v2/src/__tests__/PublicPagesSettings.test.jsx index 6a9f5c51..9e123756 100644 --- a/web-v2/src/__tests__/PublicPagesSettings.test.jsx +++ b/web-v2/src/__tests__/PublicPagesSettings.test.jsx @@ -181,4 +181,58 @@ describe('Server settings: Public pages', () => { await waitFor(() => expect(notify).toHaveBeenCalledWith('The picture is larger than 2 MB.')); expect(api.uploadPublicLookImage).not.toHaveBeenCalled(); }); + + it('keeps a colour typed while a picture is uploading, and chooses the picture when it arrives', async () => { + api.getPublicLook.mockResolvedValue(look()); + let finish; + api.uploadPublicLookImage.mockReturnValue( + new Promise((resolve) => { + finish = resolve; + }) + ); + const { container } = renderSection(); + const input = await screen.findByLabelText('Accent colour'); + const file = new File([new Uint8Array(10)], 'bg.png', { type: 'image/png' }); + fireEvent.change(container.querySelector('input[type=file]'), { target: { files: [file] } }); + await waitFor(() => expect(api.uploadPublicLookImage).toHaveBeenCalled()); + // typed while the upload is on its way + fireEvent.change(input, { target: { value: '#5865f2' } }); + finish( + look({ upload: { bytes: 9, url: '/look/123456789012345678.0123456789abcdef.webp', updatedAt: 1 } }) + ); + await waitFor(() => expect(screen.getByLabelText('Background').value).toBe('upload')); + expect(screen.getByLabelText('Accent colour').value).toBe('#5865f2'); + expect(screen.getByRole('button', { name: 'Save public pages' }).disabled).toBe(false); + }); + + it('keeps a typed colour when the picture is removed', async () => { + api.getPublicLook.mockResolvedValue( + look({ + background: 'upload', + upload: { bytes: 9, url: '/look/123456789012345678.0123456789abcdef.webp', updatedAt: 1 }, + }) + ); + api.deletePublicLookImage.mockResolvedValue(look()); + renderSection(); + const input = await screen.findByLabelText('Accent colour'); + fireEvent.change(input, { target: { value: '#5865f2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Remove picture' })); + await waitFor(() => expect(api.deletePublicLookImage).toHaveBeenCalled()); + await waitFor(() => expect(screen.getByLabelText('Background').value).toBe('none')); + expect(screen.getByLabelText('Accent colour').value).toBe('#5865f2'); + }); + + it('starts the form from the saved state again after a save', async () => { + api.getPublicLook.mockResolvedValue(look()); + api.savePublicLook.mockResolvedValue(look({ accent: '#5865f2' })); + renderSection(); + const input = await screen.findByLabelText('Accent colour'); + fireEvent.change(input, { target: { value: '#5865f2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save public pages' })); + await waitFor(() => expect(api.savePublicLook).toHaveBeenCalled()); + await waitFor(() => + expect(screen.getByRole('button', { name: 'Save public pages' }).disabled).toBe(true) + ); + expect(screen.getByLabelText('Accent colour').value).toBe('#5865f2'); + }); }); diff --git a/web-v2/src/components/PublicPagesSettings.jsx b/web-v2/src/components/PublicPagesSettings.jsx index 3107c209..40162ea4 100644 --- a/web-v2/src/components/PublicPagesSettings.jsx +++ b/web-v2/src/components/PublicPagesSettings.jsx @@ -34,18 +34,24 @@ export default function PublicPagesSettings({ guildId }) { () => (allowed ? Promise.resolve().then(() => getPublicLook(guildId)) : Promise.resolve(null)), [guildId, allowed] ); - // What the person has typed or chosen, on top of what is saved. It belongs to one saved state (the server and its - // saved colour and background): a new one (another server, or a save) starts the form from it again. No effect is - // needed to copy the saved values in, so there is no moment where a late copy overwrites an edit. + // What the person has typed or chosen, on top of what is saved, for this server. It is cleared by a save and by + // another server. No effect copies the saved values in (a late copy would overwrite an edit), and every change + // is a functional update that touches only its own fields, so an answer that arrives later (an upload, a removal) + // never overwrites what was typed meanwhile. const [draft, setDraft] = useState(null); const [busy, setBusy] = useState(false); const fileInput = useRef(null); - const savedFor = data ? `${guildId}|${data.accent}|${data.background}` : null; - const mine = draft && draft.for === savedFor ? draft : null; + const mine = draft && draft.for === guildId ? draft : null; const accent = mine?.accent ?? data?.accent ?? ''; const background = mine?.background ?? data?.background ?? 'none'; - const setAccent = (value) => setDraft({ for: savedFor, accent: value, background }); - const setBackground = (value) => setDraft({ for: savedFor, accent, background: value }); + const change = (fields) => + setDraft((d) => { + const base = + d && d.for === guildId ? d : { for: guildId, accent: data.accent, background: data.background }; + return { ...base, ...(typeof fields === 'function' ? fields(base) : fields) }; + }); + const setAccent = (value) => change({ accent: value }); + const setBackground = (value) => change({ background: value }); if (!allowed || error || !data) return null; @@ -81,7 +87,9 @@ export default function PublicPagesSettings({ guildId }) { const onSave = (e) => { e.preventDefault(); if (!dirty) return; - run(() => savePublicLook(guildId, { accent: normalised, background }), 'Public pages saved.'); + run(() => savePublicLook(guildId, { accent: normalised, background }), 'Public pages saved.').then( + (out) => out && setDraft(null) + ); }; async function onFile(e) { @@ -101,7 +109,8 @@ export default function PublicPagesSettings({ guildId }) { async function onRemove() { const out = await run(() => deletePublicLookImage(guildId), 'Picture removed.'); - if (out && background === 'upload') setBackground('none'); + // a picture that is gone cannot stay chosen; whatever else was typed stays + if (out) change((d) => (d.background === 'upload' ? { background: 'none' } : {})); } const platformName = data.platform === 'fluxer' ? 'Fluxer' : 'Discord'; From 2b8e5c997f5aad912cc8916b02c29fdaf45fa6ab Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Mon, 16 Nov 2026 23:41:55 +0100 Subject: [PATCH 7/9] fix(public-pages): keep the picture visible on phones, save the look with the page, say it in plain words On a phone the panel over a background picture now has a 12px margin all round, and the dashboard-app pages size the panel to their content so a short page leaves the picture showing. The Public pages settings are saved with the Settings page's save bar, so leaving with unsaved changes asks first. The contrast numbers give way to plain wording (readable in both themes, too dark or too light for a theme) with the figures in a tooltip, and a colour that is replaced is shown as a warning. The application page shows the **bold** words of its intro as bold text instead of raw markdown, and the leaderboard period pills are no longer underlined. --- docs/dashboard-v2.md | 4 +- src/web/public/public.css | 10 ++ test/publicLook.layout.test.js | 33 +++++ web-v2/src/__tests__/Apply.test.jsx | 24 ++++ .../__tests__/PublicPagesSettings.test.jsx | 42 +++++- web-v2/src/__tests__/Settings.test.jsx | 72 ++++++++++- web-v2/src/components/InlineMarkdown.jsx | 20 +++ web-v2/src/components/PublicPagesSettings.jsx | 120 +++++------------- web-v2/src/components/usePublicLookForm.js | 96 ++++++++++++++ web-v2/src/pages/Apply.jsx | 7 +- web-v2/src/pages/Settings.jsx | 25 +++- web-v2/src/publicLook.js | 36 ++++++ web-v2/src/styles/p3-look.css | 18 ++- 13 files changed, 404 insertions(+), 103 deletions(-) create mode 100644 test/publicLook.layout.test.js create mode 100644 web-v2/src/components/InlineMarkdown.jsx create mode 100644 web-v2/src/components/usePublicLookForm.js diff --git a/docs/dashboard-v2.md b/docs/dashboard-v2.md index f7200ed8..748e69b1 100644 --- a/docs/dashboard-v2.md +++ b/docs/dashboard-v2.md @@ -87,7 +87,9 @@ things change and nothing else: the **accent colour** (buttons, links and highli background is none, a picture you upload (PNG, JPEG or WebP, at most 2 MB; Sylo stores a re-encoded copy without metadata, at most 1920 pixels wide, and serves it itself), or the server's **invite background** on Discord or Fluxer: Sylo downloads it once, keeps its own copy, checks it once a day and serves it itself, so a visitor's -browser never talks to Discord or Fluxer. The settings show a live preview of the application form page. +browser never talks to Discord or Fluxer. The settings show a live preview of the application form page. The section +is saved with the Settings page's own Save bar, so leaving the page with unsaved changes here asks first, like any other +form. On a phone the page keeps a margin around its panel so the picture shows on every side. What stays Sylo's: the layout, the type, the components, the light and dark themes, the readability and the small "Powered by Sylo" link (to sylobot.com) at the bottom of every public page, which cannot be turned off. The page always diff --git a/src/web/public/public.css b/src/web/public/public.css index f8cbfcdb..de06ac7e 100644 --- a/src/web/public/public.css +++ b/src/web/public/public.css @@ -632,6 +632,12 @@ body.has-look-image main { body.has-look-image .auth-wrap { min-height: 0; } +/* On a phone the panel is not edge to edge: a margin all round lets the picture show on every side. */ +@media (max-width: 600px) { + body.has-look-image main { + margin: 12px; + } +} @media (prefers-reduced-transparency: reduce) { body.has-look-image main { background: var(--bg-main); @@ -644,6 +650,10 @@ body.has-look main a:not(.btn) { text-decoration: underline; text-underline-offset: 3px; } +/* The period pills are not running text: they show their state with a border and a tint. */ +body.has-look main .lb-periods a { + text-decoration: none; +} /* The "Powered by Sylo" line is the frame's: the same muted, underlined link on every page, whatever the accent. */ body .lb-foot a, body .auth-foot a { diff --git a/test/publicLook.layout.test.js b/test/publicLook.layout.test.js new file mode 100644 index 00000000..eafde2fd --- /dev/null +++ b/test/publicLook.layout.test.js @@ -0,0 +1,33 @@ +// The panel a server's background picture shows through: on a phone it keeps a margin all round (so the picture is +// seen on every side, not just as a strip above and below), and on the dashboard-app pages it is as tall as its page +// instead of the window. Read from the style sheets themselves. +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n'); + +/** The declarations of the first rule whose selector is exactly `selector`, inside the text `css`. */ +function ruleBody(css, selector) { + const at = css.indexOf(`${selector} {`); + assert.notEqual(at, -1, `no rule for ${selector}`); + return css.slice(at, css.indexOf('}', at)); +} + +test('the server-rendered pages (public.css) keep a margin round the panel on a phone', () => { + const css = read('src/web/public/public.css'); + const media = css.slice(css.indexOf('@media (max-width: 600px) {\n body.has-look-image main')); + assert.match(ruleBody(media, ' body.has-look-image main'), /margin: 12px;/); +}); + +test('the pages of the dashboard app (p3-look.css) keep the margin and are as tall as their content', () => { + const css = read('web-v2/src/styles/p3-look.css'); + const media = css.slice(css.indexOf('@media (max-width: 600px) {\n body.has-look-image .v2-public-page')); + assert.match(ruleBody(media, ' body.has-look-image .v2-public-page'), /margin: 12px;/); + assert.match(ruleBody(css, 'body.has-look-image .v2-public-page'), /flex: none;/); +}); + +test('the period pills of the leaderboard are not underlined like running text', () => { + const css = read('src/web/public/public.css'); + assert.match(ruleBody(css, 'body.has-look main .lb-periods a'), /text-decoration: none;/); +}); diff --git a/web-v2/src/__tests__/Apply.test.jsx b/web-v2/src/__tests__/Apply.test.jsx index 05693399..60514056 100644 --- a/web-v2/src/__tests__/Apply.test.jsx +++ b/web-v2/src/__tests__/Apply.test.jsx @@ -127,6 +127,30 @@ describe('the web form of an application', () => { expect(screen.getByText('Hobbies').parentElement.textContent).toMatch(/optional/); }); + it('shows the intro with its **bold** words as bold text, never as raw markdown or HTML', async () => { + api.getWebApply.mockResolvedValue( + view({ + form: { + id: FORM, + name: 'Staff', + description: 'Join the team', + version: 100, + intro: + 'Applying for **Streamer role** in **Pixel Harbor**. See [the rules](https://example.com/r) x.', + }, + }) + ); + const { container } = renderPage(); + const bold = await screen.findByText('Streamer role'); + expect(bold.tagName).toBe('STRONG'); + expect(screen.getByText('Pixel Harbor').tagName).toBe('STRONG'); + expect(container.textContent).not.toContain('**'); + expect(screen.getByRole('link', { name: 'the rules' }).getAttribute('href')).toBe( + 'https://example.com/r' + ); + expect(container.querySelector('b')).toBeNull(); + }); + it('checks required answers in the browser first and sends nothing until they are fine', async () => { renderPage(); fireEvent.click(await screen.findByRole('button', { name: 'Submit application' })); diff --git a/web-v2/src/__tests__/PublicPagesSettings.test.jsx b/web-v2/src/__tests__/PublicPagesSettings.test.jsx index 9e123756..53b41d61 100644 --- a/web-v2/src/__tests__/PublicPagesSettings.test.jsx +++ b/web-v2/src/__tests__/PublicPagesSettings.test.jsx @@ -1,6 +1,7 @@ import { configure, fireEvent, render, screen, waitFor } from '@testing-library/react'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import PublicPagesSettings from '../components/PublicPagesSettings.jsx'; +import { usePublicLookForm } from '../components/usePublicLookForm.js'; import { AccessProvider } from '../access.jsx'; // the whole suite runs on two busy CPUs in CI: role queries with names are slow in jsdom @@ -35,11 +36,24 @@ const look = (over = {}) => ({ ...over, }); +// The page (Settings.jsx) keeps the section's state and saves it with its bar; this stands in for the bar. +function Harness() { + const look = usePublicLookForm(GUILD); + return ( + <> + + + + ); +} + function renderSection(level = 'edit') { api.getGuildAccess.mockResolvedValue({ level }); return render( - + ); } @@ -93,16 +107,19 @@ describe('Server settings: Public pages', () => { // the link in the preview uses the text colour made from the accent (4.5:1), not the accent itself expect(preview.style.getPropertyValue('--accent-text')).toMatch(/^#[0-9a-f]{6}$/); expect(preview.style.getPropertyValue('--accent-text')).not.toBe('#5865f2'); - expect(screen.queryByText(/too hard to read/)).toBeNull(); + expect(screen.queryByText(/to read on the card/)).toBeNull(); + expect(screen.getByText(/Readable in both themes\./)).toBeTruthy(); expect(screen.getByText('Submit application')).toBeTruthy(); expect(screen.getByText('Powered by Sylo', { selector: 'p' })).toBeTruthy(); - // a deep blue is hard to read on the dark card (the theme now shown): Sylo's colour, and the note says so + // a deep blue is hard to read on the dark card (the theme now shown): Sylo's colour, and a warning says so fireEvent.change(input, { target: { value: '#1a2a6c' } }); expect(preview.style.getPropertyValue('--accent')).toBe(SYLO.dark); - expect( - screen.getByText(/too hard to read on the card in the dark theme, so public pages use Sylo/) - ).toBeTruthy(); + const warning = screen.getByText( + /too dark to read on the card in the dark theme, so public pages use Sylo's own colour there\. Pick a lighter shade for the dark theme\./ + ); + expect(warning.closest('.v2-callout').classList.contains('is-warning')).toBe(true); + expect(screen.getByText(/Too dark for the dark theme\./)).toBeTruthy(); // the light theme reads it, and the preview follows the theme of the dashboard document.documentElement.setAttribute('data-theme', 'light'); @@ -110,6 +127,19 @@ describe('Server settings: Public pages', () => { expect(preview.style.getPropertyValue('--accent')).toBe('#1a2a6d'); }); + it('says it in plain words, with no contrast ratios on the page', async () => { + api.getPublicLook.mockResolvedValue(look()); + const { container } = renderSection(); + const input = await screen.findByLabelText('Accent colour'); + // a pale yellow is fine on the dark card but too light for the light theme + fireEvent.change(input, { target: { value: '#ffd166' } }); + expect(screen.getByText(/Too light for the light theme\./)).toBeTruthy(); + expect(screen.getByText(/Pick a darker shade for the light theme\./)).toBeTruthy(); + expect(container.textContent).not.toMatch(/\d:1/); + // the numbers are for the tooltip + expect(screen.getByText(/Shown in the dark theme\./).getAttribute('title')).toMatch(/light: 1\.\d+:1/); + }); + it('refuses a colour that is not one and keeps the save button off', async () => { api.getPublicLook.mockResolvedValue(look()); renderSection(); diff --git a/web-v2/src/__tests__/Settings.test.jsx b/web-v2/src/__tests__/Settings.test.jsx index 2c2d0b09..46c26a32 100644 --- a/web-v2/src/__tests__/Settings.test.jsx +++ b/web-v2/src/__tests__/Settings.test.jsx @@ -10,9 +10,14 @@ vi.mock('../api.js', () => ({ exportGuildConfig: vi.fn(), getGuildAccess: vi.fn(), saveGuildAccess: vi.fn(), + getPublicLook: vi.fn(), + savePublicLook: vi.fn(), + uploadPublicLookImage: vi.fn(), + deletePublicLookImage: vi.fn(), + refreshPublicLookSplash: vi.fn(), })); vi.mock('../notify.js', () => ({ notify: vi.fn() })); -const { getGuildSettings, saveGuildSettings } = await import('../api.js'); +const { getGuildSettings, saveGuildSettings, getPublicLook, savePublicLook } = await import('../api.js'); const { notify } = await import('../notify.js'); const GUILD = '123456789012345678'; @@ -37,6 +42,71 @@ beforeEach(() => { saveGuildSettings.mockResolvedValue({ ok: true }); }); +const look = (over = {}) => ({ + platform: 'discord', + accent: '', + background: 'none', + upload: null, + splash: { available: false, copied: null }, + ...over, +}); + +describe('Settings: public pages share the page save bar', () => { + it('an edit in "Public pages" shows the bar, and Save writes only the public pages when nothing else changed', async () => { + getGuildSettings.mockResolvedValue(settings()); + getPublicLook.mockResolvedValue(look()); + savePublicLook.mockResolvedValue(look({ accent: '#5865f2' })); + renderAtGuild(, GUILD); + const accent = await screen.findByLabelText('Accent colour'); + expect(screen.queryByText('Unsaved changes')).toBeNull(); + expect(screen.queryByRole('button', { name: 'Save public pages' })).toBeNull(); + + fireEvent.change(accent, { target: { value: '#5865f2' } }); + expect(await screen.findByText('Unsaved changes')).toBeTruthy(); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => + expect(savePublicLook).toHaveBeenCalledWith(GUILD, { accent: '#5865f2', background: 'none' }) + ); + expect(saveGuildSettings).not.toHaveBeenCalled(); + await waitFor(() => expect(screen.getByRole('button', { name: 'Save' }).disabled).toBe(true)); + }); + + it('saves the settings first and then the public pages when both changed', async () => { + getGuildSettings.mockResolvedValue(settings({ platform: 'fluxer' })); + getPublicLook.mockResolvedValue(look()); + savePublicLook.mockResolvedValue(look({ background: 'none', accent: '#5865f2' })); + renderAtGuild(, GUILD); + fireEvent.change(await screen.findByLabelText(/Command prefix/), { target: { value: '>>' } }); + fireEvent.change(await screen.findByLabelText('Accent colour'), { target: { value: '#5865f2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(savePublicLook).toHaveBeenCalledTimes(1)); + expect(saveGuildSettings).toHaveBeenCalledTimes(1); + }); + + it('does not save the public pages when the settings are refused', async () => { + getGuildSettings.mockResolvedValue(settings({ platform: 'fluxer' })); + getPublicLook.mockResolvedValue(look()); + renderAtGuild(, GUILD); + fireEvent.change(await screen.findByLabelText(/Command prefix/), { target: { value: 'a b' } }); + fireEvent.change(await screen.findByLabelText('Accent colour'), { target: { value: '#5865f2' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + await waitFor(() => expect(notify).toHaveBeenCalledWith('The prefix can not contain spaces.')); + expect(savePublicLook).not.toHaveBeenCalled(); + }); + + it('Reset drops the edit in "Public pages" too', async () => { + getGuildSettings.mockResolvedValue(settings()); + getPublicLook.mockResolvedValue(look()); + renderAtGuild(, GUILD); + const accent = await screen.findByLabelText('Accent colour'); + fireEvent.change(accent, { target: { value: '#5865f2' } }); + expect(accent.value).toBe('#5865f2'); + fireEvent.click(screen.getByRole('button', { name: 'Reset' })); + await waitFor(() => expect(screen.getByLabelText('Accent colour').value).toBe('')); + expect(screen.getByRole('button', { name: 'Save' }).disabled).toBe(true); + }); +}); + describe('Settings: command prefix', () => { it('is not shown for a Discord server', async () => { getGuildSettings.mockResolvedValue(settings()); diff --git a/web-v2/src/components/InlineMarkdown.jsx b/web-v2/src/components/InlineMarkdown.jsx new file mode 100644 index 00000000..36edf9cb --- /dev/null +++ b/web-v2/src/components/InlineMarkdown.jsx @@ -0,0 +1,20 @@ +import { parseInline } from '../../../src/lib/changelog.js'; + +/** + * A line of text with the inline markdown a server admin writes in a Discord message (**bold**, `code` and + * [links](https://…)) shown as such. It never makes HTML: the text goes through the same parser as the changelog + * (src/lib/changelog.js), which hands back plain segments, and a link is only made for an http(s) address. + */ +export default function InlineMarkdown({ text }) { + return parseInline(String(text ?? '')).map((s, i) => { + if (s.code) return {s.code}; + if (s.href) + return ( + + {s.text} + + ); + if (s.bold) return {s.text}; + return {s.text}; + }); +} diff --git a/web-v2/src/components/PublicPagesSettings.jsx b/web-v2/src/components/PublicPagesSettings.jsx index 40162ea4..1f028400 100644 --- a/web-v2/src/components/PublicPagesSettings.jsx +++ b/web-v2/src/components/PublicPagesSettings.jsx @@ -1,16 +1,9 @@ -import { useRef, useState } from 'react'; -import { - deletePublicLookImage, - getPublicLook, - refreshPublicLookSplash, - savePublicLook, - uploadPublicLookImage, -} from '../api.js'; -import { useApiData } from '../useApiData.js'; +import { useRef } from 'react'; +import { deletePublicLookImage, refreshPublicLookSplash, uploadPublicLookImage } from '../api.js'; import { notify } from '../notify.js'; -import { useAccess } from '../access.jsx'; +import Callout from './Callout.jsx'; import Field from './Field.jsx'; -import { SYLO_ACCENT, accentNote, accentOutcome, normaliseAccent, onAccent } from '../publicLook.js'; +import { SYLO_ACCENT, accentAdvice, accentOutcome, onAccent } from '../publicLook.js'; const MAX_BYTES = 2 * 1024 * 1024; @@ -26,39 +19,17 @@ const currentTheme = () => * the event pages carry no server address and take no look). Only * these two things change; the layout, the type, the light and dark themes and the "Powered by Sylo" link stay * Sylo's. The preview is the application form page. Edit level only (the section is not shown below it). + * + * The edits are kept by the page (`look` is usePublicLookForm's result) and saved with its save bar, so leaving the + * page with unsaved edits here is warned about like any other form. A picture is uploaded or removed at once. */ -export default function PublicPagesSettings({ guildId }) { - const { can } = useAccess(); - const allowed = can('edit'); - const { data, error, setData } = useApiData( - () => (allowed ? Promise.resolve().then(() => getPublicLook(guildId)) : Promise.resolve(null)), - [guildId, allowed] - ); - // What the person has typed or chosen, on top of what is saved, for this server. It is cleared by a save and by - // another server. No effect copies the saved values in (a late copy would overwrite an edit), and every change - // is a functional update that touches only its own fields, so an answer that arrives later (an upload, a removal) - // never overwrites what was typed meanwhile. - const [draft, setDraft] = useState(null); - const [busy, setBusy] = useState(false); +export default function PublicPagesSettings({ look }) { const fileInput = useRef(null); - const mine = draft && draft.for === guildId ? draft : null; - const accent = mine?.accent ?? data?.accent ?? ''; - const background = mine?.background ?? data?.background ?? 'none'; - const change = (fields) => - setDraft((d) => { - const base = - d && d.for === guildId ? d : { for: guildId, accent: data.accent, background: data.background }; - return { ...base, ...(typeof fields === 'function' ? fields(base) : fields) }; - }); - const setAccent = (value) => change({ accent: value }); - const setBackground = (value) => change({ background: value }); - - if (!allowed || error || !data) return null; + const { ready, guildId, data, accent, background, normalised, invalid, busy, setAccent, setBackground } = + look; + if (!ready) return null; - const normalised = normaliseAccent(accent); - const invalid = normalised === null; - const dirty = !invalid && (normalised !== data.accent || background !== data.background); - const note = invalid ? null : accentNote(normalised); + const advice = invalid || !normalised ? null : accentAdvice(normalised); const theme = currentTheme(); const outcome = accentOutcome(invalid ? '' : normalised); const shown = outcome[theme].color; @@ -69,29 +40,6 @@ export default function PublicPagesSettings({ guildId }) { background === 'upload' ? data.upload?.url : background === 'discord-splash' ? splash.copied?.url : null; const waitingSplash = background === 'discord-splash' && !splash.copied; - async function run(fn, done) { - setBusy(true); - try { - const out = await fn(); - if (out) setData(out); - if (done) notify(done, 'info'); - return out; - } catch (err) { - notify(err.message); - return null; - } finally { - setBusy(false); - } - } - - const onSave = (e) => { - e.preventDefault(); - if (!dirty) return; - run(() => savePublicLook(guildId, { accent: normalised, background }), 'Public pages saved.').then( - (out) => out && setDraft(null) - ); - }; - async function onFile(e) { const file = e.target.files?.[0]; e.target.value = ''; @@ -100,7 +48,7 @@ export default function PublicPagesSettings({ guildId }) { notify('The picture is larger than 2 MB.'); return; } - const out = await run(() => uploadPublicLookImage(guildId, file)); + const out = await look.run(() => uploadPublicLookImage(guildId, file)); if (out) { setBackground('upload'); notify('Picture uploaded. Save to use it.', 'info'); @@ -108,9 +56,9 @@ export default function PublicPagesSettings({ guildId }) { } async function onRemove() { - const out = await run(() => deletePublicLookImage(guildId), 'Picture removed.'); + const out = await look.run(() => deletePublicLookImage(guildId), 'Picture removed.'); // a picture that is gone cannot stay chosen; whatever else was typed stays - if (out) change((d) => (d.background === 'upload' ? { background: 'none' } : {})); + if (out) look.change((d) => (d.background === 'upload' ? { background: 'none' } : {})); } const platformName = data.platform === 'fluxer' ? 'Fluxer' : 'Discord'; @@ -118,16 +66,21 @@ export default function PublicPagesSettings({ guildId }) { ? `This server has no invite background on ${platformName}. Set one there to use it here.` : `Sylo keeps its own copy of the server's ${platformName} invite background and checks it once a day, so visitors never load it from ${platformName}.`; + let readability = null; + if (advice?.readable) readability = 'Readable in both themes.'; + else if (advice?.problems.length) readability = `${advice.problems.map((p) => p.label).join('. ')}.`; + return (

Public pages

-

+

Give the pages your members open without the dashboard (application forms, the web shop, ban appeals, the quote page and the leaderboards) your server's accent colour and a background. Only these two things change: the layout, the type, the light and dark themes and the "Powered by Sylo" link stay as they are.

- + {/* No submit button: the page's save bar saves (Enter in the colour field too). */} + e.preventDefault()} data-savebar>
@@ -165,10 +118,10 @@ export default function PublicPagesSettings({ guildId }) { ? 'Use a colour like #5865f2.' : 'Used for buttons, links and highlights. Leave it empty for Sylo’s own colour.'}

- {note ? ( -

- {note} -

+ {advice?.warning ? ( + +

{advice.warning}

+
) : null}
@@ -211,7 +164,7 @@ export default function PublicPagesSettings({ guildId }) { type="button" className="v2-btn-ghost" disabled={busy} - onClick={() => run(() => refreshPublicLookSplash(guildId), 'Invite background checked.')} + onClick={() => look.run(() => refreshPublicLookSplash(guildId), 'Invite background checked.')} > Check the invite background now @@ -256,23 +209,10 @@ export default function PublicPagesSettings({ guildId }) { {waitingSplash ? (

The invite background is downloaded when you save.

) : null} -

- Shown in the {theme} theme.{' '} - {['dark', 'light'].map((t) => ( - - {t}:{' '} - {outcome[t].ratio == null - ? 'Sylo’s colour' - : `${outcome[t].ratio}:1${outcome[t].ok ? '' : ' (too low)'}`}{' '} - - ))} +

+ Shown in the {theme} theme. + {readability ? ` ${readability}` : ''}

- -
- -
); diff --git a/web-v2/src/components/usePublicLookForm.js b/web-v2/src/components/usePublicLookForm.js new file mode 100644 index 00000000..13c3d356 --- /dev/null +++ b/web-v2/src/components/usePublicLookForm.js @@ -0,0 +1,96 @@ +import { useCallback, useState } from 'react'; +import { getPublicLook, savePublicLook } from '../api.js'; +import { useApiData } from '../useApiData.js'; +import { notify } from '../notify.js'; +import { useAccess } from '../access.jsx'; +import { normaliseAccent } from '../publicLook.js'; + +/** + * State of the server settings' "Public pages" section, kept by the page so that its edits count towards the page's + * save bar (Settings.jsx): `dirty` joins the page's own, `save()` and `reset()` are called by the bar. + * + * What the person has typed or chosen is a draft on top of what is saved, for this server. It is cleared by a save, a + * reset and another server. No effect copies the saved values in (a late copy would overwrite an edit), and every + * change is a functional update that touches only its own fields, so an answer that arrives later (an upload, a + * removal) never overwrites what was typed meanwhile. + * + * Edit level only: below it nothing is asked of the server and `ready` stays false. + */ +export function usePublicLookForm(guildId) { + const { can } = useAccess(); + const allowed = can('edit'); + const { data, error, setData } = useApiData( + () => (allowed ? Promise.resolve().then(() => getPublicLook(guildId)) : Promise.resolve(null)), + [guildId, allowed] + ); + const [draft, setDraft] = useState(null); + const [busy, setBusy] = useState(false); + const mine = draft && draft.for === guildId ? draft : null; + const accent = mine?.accent ?? data?.accent ?? ''; + const background = mine?.background ?? data?.background ?? 'none'; + const ready = Boolean(allowed && !error && data); + + const change = useCallback( + (fields) => + setDraft((d) => { + const base = + d && d.for === guildId ? d : { for: guildId, accent: data.accent, background: data.background }; + return { ...base, ...(typeof fields === 'function' ? fields(base) : fields) }; + }), + [guildId, data] + ); + + const normalised = normaliseAccent(accent); + const invalid = normalised === null; + const dirty = ready && !invalid && (normalised !== data.accent || background !== data.background); + + /** Runs one request (an upload, a removal, a save) with the section's controls off meanwhile. */ + const run = useCallback( + async (fn, done) => { + setBusy(true); + try { + const out = await fn(); + if (out) setData(out); + if (done) notify(done, 'info'); + return out; + } catch (err) { + notify(err.message); + return null; + } finally { + setBusy(false); + } + }, + [setData] + ); + + /** Saves the colour and the background; resolves to true when it was saved (or there was nothing to save). */ + const save = useCallback(async () => { + if (!dirty) return true; + const out = await run( + () => savePublicLook(guildId, { accent: normalised, background }), + 'Public pages saved.' + ); + if (out) setDraft(null); + return Boolean(out); + }, [dirty, run, guildId, normalised, background]); + + const reset = useCallback(() => setDraft(null), []); + + return { + ready, + guildId, + data, + accent, + background, + normalised, + invalid, + dirty, + busy, + change, + setAccent: (value) => change({ accent: value }), + setBackground: (value) => change({ background: value }), + run, + save, + reset, + }; +} diff --git a/web-v2/src/pages/Apply.jsx b/web-v2/src/pages/Apply.jsx index d7bf254e..ca4c3bf5 100644 --- a/web-v2/src/pages/Apply.jsx +++ b/web-v2/src/pages/Apply.jsx @@ -6,6 +6,7 @@ import { notify } from '../notify.js'; import { useServerLook } from '../publicLook.js'; import { confirmDialog } from '../components/ConfirmDialog.jsx'; import ApplicationQuestion from '../components/ApplicationQuestion.jsx'; +import InlineMarkdown from '../components/InlineMarkdown.jsx'; import Time from '../components/Time.jsx'; import { answerProblems, @@ -152,7 +153,11 @@ export default function Apply() { {!problem && !pending && answers ? (
- {form.intro ?

{form.intro}

: null} + {form.intro ? ( +

+ +

+ ) : null} {note ? (

{note} diff --git a/web-v2/src/pages/Settings.jsx b/web-v2/src/pages/Settings.jsx index b37e98b6..e95b04c7 100644 --- a/web-v2/src/pages/Settings.jsx +++ b/web-v2/src/pages/Settings.jsx @@ -17,6 +17,7 @@ import { notify } from '../notify.js'; import Reveal from '../components/Reveal.jsx'; import ConfigImport from '../components/ConfigImport.jsx'; import PublicPagesSettings from '../components/PublicPagesSettings.jsx'; +import { usePublicLookForm } from '../components/usePublicLookForm.js'; import { useCanSetUp } from '../setupAccess.js'; import { AccessLock, useAccess } from '../access.jsx'; @@ -101,6 +102,9 @@ export default function Settings() { afterSave: (_result, sent) => sent, } ); + // The "Public pages" section below keeps its edits here, so they count towards the one save bar and its + // leave-the-page warning like the form above. + const look = usePublicLookForm(guildId); const [resettingColor, setResettingColor] = useState(false); const [exporting, setExporting] = useState(false); useEffect(() => { @@ -117,6 +121,18 @@ export default function Settings() { ); + // The bar saves both: the settings above, then the public pages. If the settings cannot be saved, the public + // pages stay unsaved (and the bar stays up) rather than half the page being written. + async function saveEverything(e) { + if (e && typeof e.preventDefault === 'function') e.preventDefault(); + if (dirty && !(await save())) return false; + return look.save(); + } + const resetEverything = () => { + reset(); + look.reset(); + }; + // Saves the form as it stands plus the colour reset, then reads back the // default colour — so afterwards everything on the page is saved. async function onResetColor() { @@ -286,7 +302,7 @@ export default function Settings() { {/* The server's own accent colour and background on its public member pages (Edit access only). */} - +

Server data

@@ -348,7 +364,12 @@ export default function Settings() {
- + ); } diff --git a/web-v2/src/publicLook.js b/web-v2/src/publicLook.js index 290b5a21..df9f0d6a 100644 --- a/web-v2/src/publicLook.js +++ b/web-v2/src/publicLook.js @@ -107,6 +107,42 @@ export function accentNote(accent) { return `This colour is too hard to read on the card in ${where}, so public pages use Sylo's own colour there. Pick a darker or lighter shade.`; } +/** + * What the settings page tells a server admin about a colour, in plain words: `readable` when both themes use + * it, otherwise `problems` ("Too light for the light theme", with the way to go) and the `warning` sentence. A + * colour that is hard to read on the card is too dark for the dark theme or too light for the light one. + * (The server's own sentence, `accentNote`, stays the one the API and the apps get.) + */ +export function accentAdvice(accent) { + const out = accentOutcome(accent); + const problems = ['dark', 'light'] + .filter((t) => !out[t].ok) + .map((theme) => { + const tooDark = theme === 'dark'; + const word = tooDark ? 'dark' : 'light'; + return { + theme, + word, + label: `Too ${word} for the ${theme} theme`, + advice: `Pick a ${tooDark ? 'lighter' : 'darker'} shade for the ${theme} theme.`, + }; + }); + const first = problems[0]; + const warning = first + ? `This colour is too ${first.word} to read on the card in the ${first.theme} theme, so public pages use Sylo's own colour there. ${first.advice}` + : null; + return { + readable: Boolean(accent) && problems.length === 0, + problems, + warning, + // The exact contrast, for a tooltip: it is not something to read out to a server admin. + detail: ['dark', 'light'] + .map((t) => (out[t].ratio == null ? null : `${t}: ${out[t].ratio}:1`)) + .filter(Boolean) + .join(', '), + }; +} + /** * Load the server's look for the page that is open: its style sheet and the marks on that the dim * overlay and the panel hang on (styles/p3-look.css). `look` is `{ css, image }` from the page's data, or diff --git a/web-v2/src/styles/p3-look.css b/web-v2/src/styles/p3-look.css index ce4d16c4..88a1af25 100644 --- a/web-v2/src/styles/p3-look.css +++ b/web-v2/src/styles/p3-look.css @@ -46,11 +46,20 @@ body.has-look-image { body.has-look-image .v2-public-page { margin-top: 16px; margin-bottom: 16px; + /* The panel is as tall as its page, not the window, so a short page leaves the picture showing. */ + flex: none; border-radius: var(--radius); background: color-mix(in srgb, var(--bg-main) var(--look-panel), transparent); -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px); } +/* On a phone the panel is not edge to edge: a margin all round lets the picture show on every side. */ +@media (max-width: 600px) { + body.has-look-image .v2-public-page { + margin: 12px; + width: auto; + } +} /* Over a picture the top bar's glass is always on (it is otherwise only on once the page scrolls), so the brand and the theme switch never sit directly on the picture. */ body.has-look-image .v2-topbar::before { @@ -154,8 +163,13 @@ body.has-look-image .v2-powered a { font-size: var(--fs-xs); color: var(--text-muted); } -.v2-look-ratio { - white-space: nowrap; +/* Air between the intro and the first field, and around the warning about a hard-to-read colour. */ +.v2-look-intro { + margin-bottom: 16px; +} +.v2-look-warning { + margin-top: 12px; + margin-bottom: 0; } @media (prefers-reduced-transparency: reduce) { .v2-look-preview.has-image .v2-look-preview-panel, From 8931a244c11d5c38b57393d46329120d9ba9d476 Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Tue, 17 Nov 2026 00:19:06 +0100 Subject: [PATCH 8/9] fix(public-pages): rate limit saving the invite background and keep its retry gate Saving the look with the invite background forced a download of the server's splash on every save, outside the check button's limit and past the 15-minute failure gate, so a save loop could start many downloads. The save now counts against the same per-minute limit as the check button and no longer forces the download; only the check button does. --- src/web/routes/v2PublicLook.js | 9 ++++++++- test/publicLook.web.test.js | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/web/routes/v2PublicLook.js b/src/web/routes/v2PublicLook.js index 375f8b92..8bccccf1 100644 --- a/src/web/routes/v2PublicLook.js +++ b/src/web/routes/v2PublicLook.js @@ -46,6 +46,10 @@ const splashLimit = rateLimit({ keyFn: (req) => `look-splash|${req.params?.guildId ?? ''}|${clientKey(req)}`, }); +// Saving the invite background can start a download too, so it counts against the same limit as the check button. +const saveLimit = (req, res, next) => + req.body?.background === 'discord-splash' ? splashLimit(req, res, next) : next(); + const send = async (res, req) => res.json(await lookView(req.guild, req.guild.id)); router.get( @@ -55,6 +59,7 @@ router.get( router.post( '/public-page-look', + saveLimit, asyncHandler(async (req, res) => { const guildId = req.guild.id; const accent = normaliseAccent(req.body?.accent); @@ -73,7 +78,9 @@ router.post( 'This server has no invite background. Set one in the server settings, or choose another.' ); } - const out = await refreshSplash(req.guild, { force: true }); + // Not forced: a copy that is current costs nothing, and a download that failed lately is not tried again + // for a while. Only the check button (below) skips that wait. + const out = await refreshSplash(req.guild); if (out.status === 'failed' || out.status === 'none') { return fail( res, diff --git a/test/publicLook.web.test.js b/test/publicLook.web.test.js index 953eeb2c..d29e13fd 100644 --- a/test/publicLook.web.test.js +++ b/test/publicLook.web.test.js @@ -476,3 +476,20 @@ test('the "Powered by Sylo" line is the same muted frame link on every page, wha const css = await (await get('/public.css')).text(); assert.match(css, /body \.lb-foot a,\s*body \.auth-foot a \{\s*color: var\(--text-muted\);/); }); + +test('saving the invite background keeps the retry gate and the check limit, so a save loop cannot start downloads', async () => { + cdnBody = await pic(100, 100, 'webp'); + app.guild.splash = 'loop'; + cdnStatus = 500; + const statuses = []; + for (let i = 0; i < 9; i++) + statuses.push((await save({ accent: '', background: 'discord-splash' })).status); + // The first save tried a download and failed; the saves right behind it stopped at the 15-minute gate + // (no new download), and past six a minute the limit answers before anything runs. + assert.equal(statuses[0], 502); + assert.equal(cdnHits, 1, `one download, not one per save: ${statuses}`); + assert.ok(statuses.includes(429), `the limit answers a save loop: ${statuses}`); + assert.equal((await getPublicLook(GID)).background, 'none'); + // A save that does not touch the splash is not counted against that limit. + assert.equal((await save({ accent: '#5865f2', background: 'none' })).status, 200); +}); From 1a57947b7ba0ef7571fa14d6807139825738d52a Mon Sep 17 00:00:00 2001 From: Ferdinand99 Date: Tue, 17 Nov 2026 00:19:49 +0100 Subject: [PATCH 9/9] fix(public-pages): serve stored look pictures as image/webp The picture route sent the mime column as Content-Type. Sylo only writes image/webp, but a restored or imported row could carry another value, so the type is now a constant. --- src/web/routes/publicLook.js | 4 +++- test/publicLook.web.test.js | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/src/web/routes/publicLook.js b/src/web/routes/publicLook.js index c46cfed7..a3d798da 100644 --- a/src/web/routes/publicLook.js +++ b/src/web/routes/publicLook.js @@ -56,7 +56,9 @@ router.get('/:file', async (req, res, next) => { res.set({ ...FILE_HEADERS, 'Cache-Control': 'public, max-age=86400', - 'Content-Type': image.mime, + // Sylo only ever stores WebP; the stored column is not trusted as a type (a restored or imported row could + // carry another one). + 'Content-Type': 'image/webp', 'Content-Length': String(image.data.length), }); return res.end(image.data); diff --git a/test/publicLook.web.test.js b/test/publicLook.web.test.js index d29e13fd..d64a45d3 100644 --- a/test/publicLook.web.test.js +++ b/test/publicLook.web.test.js @@ -493,3 +493,16 @@ test('saving the invite background keeps the retry gate and the check limit, so // A save that does not touch the splash is not counted against that limit. assert.equal((await save({ accent: '#5865f2', background: 'none' })).status, 200); }); + +test('a stored picture is always served as image/webp, whatever its mime column says', async () => { + await putLookImage(GID, 'splash', { + hash: '0123456789abcdef', + mime: 'text/html', + data: await pic(10, 10, 'webp'), + origin: 'o', + }); + const res = await get(`/look/${GID}.0123456789abcdef.webp`); + assert.equal(res.status, 200); + assert.equal(res.headers.get('content-type'), 'image/webp'); + assert.equal(res.headers.get('x-content-type-options'), 'nosniff'); +});