From 40fc0808f0a64fb98cc9df68bb6f34d9ad106411 Mon Sep 17 00:00:00 2001 From: antoine-debroye <144667691+antoine-debroye@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:51:31 +0100 Subject: [PATCH 1/8] Refuse giant images, hide shows from strangers, and sign other sessions out on a password change Tier 2 of the October audit: the security findings that matter under SelfPod's threat model, where the shows folder is a share other people can write to and the admin UI sits behind a public tunnel hostname. - Every sharp decode now stops at 40 megapixels, at the header. A 60 KB PNG of one colour declaring 16000x16000 decodes to a gigabyte, the scanner decodes sidecars on its own on every scan, and the result was a crash loop with no banner. The scan log now says the image was too large rather than "could not be read", and a cover upload gets the same sentence. - The sign-in page and the anonymous half of /api/status show only the permission banners. The others name a show's title or a followed feed's host, which feeds-private-by-token should not hand to whoever finds the hostname. - Changing the password signs every other session out, keeping only the one that made the change. The reset script already did this; the UI did not. - A sign-in regenerates the session id (belt and braces; nothing was exploitable). - The account-level login backoff is capped at a minute, and a per-source backoff carries the five-minute wait instead, so a stranger holding the URL can no longer keep the owner locked out by guessing once every few minutes. A throttled attempt answers 429 with Retry-After, not 401. Co-Authored-By: Claude Fable 5.1 --- CHANGELOG.md | 27 ++++++ src/constants.js | 11 +++ src/lib/errors.js | 3 + src/plugins/auth.js | 63 +++++++++--- src/plugins/session.js | 14 +++ src/routes/api/auth.js | 12 ++- src/routes/api/settings.js | 2 +- src/routes/api/setup.js | 2 +- src/routes/api/status.js | 6 +- src/services/covers.js | 20 +++- src/services/episode-art.js | 37 ++++++- src/services/health.js | 28 ++++++ src/web/routes/fragments.js | 2 +- src/web/routes/pages.js | 14 ++- test/integration/http.test.js | 4 +- test/security/auth-and-headers.test.js | 129 ++++++++++++++++++++++++- test/security/image-bomb.test.js | 105 ++++++++++++++++++++ 17 files changed, 446 insertions(+), 33 deletions(-) create mode 100644 test/security/image-bomb.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index dc03f84..9dacf85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,33 @@ changes what your listeners see, it says so. range it had asked for before the row was written, so the log could not show why. The range is kept. +### Security — hardening from the October audit + +- **An oversized image on the share could take the container down.** The shows folder is a + network share other people can write to, and SelfPod decoded whatever image it found there + — a cover, an episode's sidecar, the artwork embedded in an MP3 — at sharp's own ceiling of + roughly 268 megapixels. A 60 KB PNG of one colour declaring 16000×16000 decodes to a + gigabyte, and the scanner decodes sidecars on its own, on every scan: one such file was a + crash loop with no banner to explain it. Every decode now stops at 40 megapixels, at the + header, and the scan log says the image was too large rather than "could not be read". +- **Before sign-in, only the permission banners are shown.** The sign-in page and the + anonymous half of `/api/status` carried every health banner, and those name things: a + show's title when its cut copy goes missing, the host of a feed being followed. Feeds are + private by their token, so their names should not be readable by whoever finds the tunnel + hostname. The banners about `/data` and the shows folder — the ones that have to be visible + before anyone can sign in — still are. +- **Changing the password signs every other session out.** It used to leave them valid for + up to thirty days, which is the opposite of what someone changing their password because + they suspect a stolen session wants. The session that made the change stays signed in. +- **A sign-in always gets a fresh session id**, rather than promoting whatever cookie it was + handed. Nothing was exploitable before — no session exists until the password is proved — + so this is belt and braces. +- **A stranger can no longer keep you locked out.** The account-level backoff reached five + minutes and reset on every wrong guess, so one wrong password every few minutes from + anywhere held the door shut indefinitely. The account now waits at most a minute; the + address doing the guessing waits up to five. A throttled attempt answers 429 with + `Retry-After` instead of 401, so it can be told apart from a wrong password. + ### Changed - Dependencies brought up to patched releases: Fastify 5.12.5 (seven advisories, including an diff --git a/src/constants.js b/src/constants.js index 5ecf3da..95ab855 100644 --- a/src/constants.js +++ b/src/constants.js @@ -355,6 +355,17 @@ export const REMOTE_IMAGE_MAX_BYTES = 10 * 1024 * 1024; */ export const REMOTE_IMAGE_MAX_PIXELS = 40 * 1000 * 1000; +/** + * The same ceiling for every image sharp decodes, wherever it came from. + * + * The shows folder is a network share that other people can write to, so a cover + * or an episode sidecar dropped there is as much a stranger's choice as a remote + * image is — and an image embedded in an MP3's tag arrives the same way. A 300 KB + * WebP declaring 16000×16000 decodes to a gigabyte; passing this to `sharp()` makes + * it refuse at the header, before a byte is decoded. + */ +export const IMAGE_MAX_INPUT_PIXELS = REMOTE_IMAGE_MAX_PIXELS; + /** * Four timers, not one, because they catch four different failures. * diff --git a/src/lib/errors.js b/src/lib/errors.js index 1f80958..20948bd 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -19,6 +19,9 @@ export const badRequest = (message, code = 'bad_request') => export const unauthorized = (message = 'Please sign in to continue.', code = 'unauthorized') => new AppError(message, { code, status: 401 }); +export const tooManyRequests = (message = 'Too many attempts. Try again shortly.', code = 'rate_limited') => + new AppError(message, { code, status: 429 }); + export const forbidden = (message, code = 'forbidden') => new AppError(message, { code, status: 403 }); diff --git a/src/plugins/auth.js b/src/plugins/auth.js index a2cbed0..4dd7df8 100644 --- a/src/plugins/auth.js +++ b/src/plugins/auth.js @@ -28,10 +28,25 @@ import { SETTING_KEYS } from '../services/settings.js'; */ const WINDOW_MS = 15 * 60 * 1000; -const MAX_ATTEMPTS_PER_WINDOW = 5; -/** Backoff after consecutive failures, in seconds, regardless of source address. */ -const BACKOFF_STEPS = [0, 0, 1, 3, 10, 30, 60, 120, 300]; +/** + * Two backoffs, because they protect against different people. + * + * The account-level one holds *everyone* back after failures from anywhere, so it + * is what stops a slow guess spread across many addresses — and also what lets a + * stranger who holds the public URL keep the owner out: one wrong password every + * few minutes used to reset a five-minute lock for ever. It is therefore capped at + * a minute, which is still one guess a minute for a patient attacker. + * + * The per-source one is allowed to grow to five minutes, because it only ever + * holds back the address that earned it. Behind Cloudflare the source is the + * edge-set client address; on a LAN it is the socket; behind another proxy that + * sets neither header every visitor shares one source, which is no worse than the + * old account-level lock. + */ +const ACCOUNT_BACKOFF_STEPS = [0, 0, 1, 3, 10, 30, 60]; +const SOURCE_BACKOFF_STEPS = [0, 0, 1, 3, 10, 30, 60, 120, 300]; +const MAX_ACCOUNT_LOCK_SECONDS = ACCOUNT_BACKOFF_STEPS[ACCOUNT_BACKOFF_STEPS.length - 1]; async function authPlugin(fastify, { db, settings, config, logger }) { const recordAttempt = db.prepare( @@ -41,6 +56,10 @@ async function authPlugin(fastify, { db, settings, config, logger }) { `SELECT COUNT(*) AS n, MAX(attempted_at) AS last FROM login_attempts WHERE username = ? AND succeeded = 0 AND attempted_at > ?`, ); + const recentFailuresFromSource = db.prepare( + `SELECT COUNT(*) AS n, MAX(attempted_at) AS last FROM login_attempts + WHERE username = ? AND source = ? AND succeeded = 0 AND attempted_at > ?`, + ); const clearAttempts = db.prepare('DELETE FROM login_attempts WHERE username = ?'); const trimAttempts = db.prepare('DELETE FROM login_attempts WHERE attempted_at < ?'); @@ -57,16 +76,27 @@ async function authPlugin(fastify, { db, settings, config, logger }) { fastify.decorate('loginSourceKey', sourceKey); - /** Seconds the account must wait before another attempt, 0 when clear. */ - fastify.decorate('loginBackoffSeconds', (username) => { - const since = new Date(Date.now() - WINDOW_MS).toISOString(); - const row = recentFailures.get(username, since); + /** Seconds still to wait after the failures in `row`, on the given ladder. */ + function waitFor(steps, row) { const failures = row?.n ?? 0; if (!failures || !row.last) return 0; - const step = BACKOFF_STEPS[Math.min(failures, BACKOFF_STEPS.length - 1)]; + const step = steps[Math.min(failures, steps.length - 1)]; if (!step) return 0; const elapsed = (Date.now() - new Date(row.last).getTime()) / 1000; return Math.max(0, Math.ceil(step - elapsed)); + } + + /** + * Seconds this caller must wait before another attempt, 0 when clear: the longer + * of the account's own wait and the wait this source has earned for itself. + */ + fastify.decorate('loginBackoffSeconds', (username, source = null) => { + const since = new Date(Date.now() - WINDOW_MS).toISOString(); + const account = waitFor(ACCOUNT_BACKOFF_STEPS, recentFailures.get(username, since)); + const bySource = source + ? waitFor(SOURCE_BACKOFF_STEPS, recentFailuresFromSource.get(username, source, since)) + : 0; + return Math.max(account, bySource); }); fastify.decorate('recentFailureCount', (username) => { @@ -83,7 +113,7 @@ async function authPlugin(fastify, { db, settings, config, logger }) { const hash = settings.adminPasswordHash(); const source = request ? sourceKey(request) : null; - const backoff = fastify.loginBackoffSeconds(expectedUser); + const backoff = fastify.loginBackoffSeconds(expectedUser, source); if (backoff > 0) { return { ok: false, @@ -110,12 +140,23 @@ async function authPlugin(fastify, { db, settings, config, logger }) { return { ok: true, username: expectedUser }; }); - fastify.decorate('setAdminPassword', async (password) => { + /** + * Sets the password and signs every *other* session out. + * + * Someone changing their password because they suspect a session was stolen + * expects the thief to be gone; until now the thief stayed signed in for up to + * thirty days. `keepSessionId` is the session doing the changing — the setup + * wizard and the Settings modal pass their own — and `null` means sign out + * everyone, which is what the reset script wants. + */ + fastify.decorate('setAdminPassword', async (password, { keepSessionId = null } = {}) => { const hash = await bcrypt.hash(String(password), BCRYPT_ROUNDS); settings.update( { [SETTING_KEYS.ADMIN_PASSWORD_HASH]: hash, [SETTING_KEYS.MUST_CHANGE_PASSWORD]: '0' }, { skipExport: true }, ); + const endedSessions = fastify.sessionStore?.deleteOthers(keepSessionId) ?? 0; + if (endedSessions) logger?.info({ endedSessions }, 'password changed; other sessions signed out'); return true; }); @@ -209,5 +250,5 @@ function formatSeconds(seconds) { return `${minutes} minute${minutes === 1 ? '' : 's'}`; } -export { MAX_ATTEMPTS_PER_WINDOW, WINDOW_MS }; +export { MAX_ACCOUNT_LOCK_SECONDS, WINDOW_MS }; export default fp(authPlugin, { name: 'selfpod-auth', dependencies: ['selfpod-session'] }); diff --git a/src/plugins/session.js b/src/plugins/session.js index 31d7e79..4c338f8 100644 --- a/src/plugins/session.js +++ b/src/plugins/session.js @@ -19,6 +19,8 @@ class SqliteSessionStore { ON CONFLICT(sid) DO UPDATE SET data = excluded.data, expires_at = excluded.expires_at`, ); this.deleteStmt = db.prepare('DELETE FROM sessions WHERE sid = ?'); + this.deleteOthersStmt = db.prepare('DELETE FROM sessions WHERE sid <> ?'); + this.deleteAllStmt = db.prepare('DELETE FROM sessions'); this.cleanupStmt = db.prepare('DELETE FROM sessions WHERE expires_at < ?'); } @@ -50,6 +52,18 @@ class SqliteSessionStore { } } + /** + * Ends every session but one. The one to keep is the session of whoever just + * changed the password: they proved they hold it, and signing them out of the + * page they did it from would be a strange reward. + */ + deleteOthers(keepSid) { + const info = keepSid + ? this.deleteOthersStmt.run(keepSid) + : this.deleteAllStmt.run(); + return info.changes; + } + destroy(sid, callback) { try { this.deleteStmt.run(sid); diff --git a/src/routes/api/auth.js b/src/routes/api/auth.js index b82cdb6..5641768 100644 --- a/src/routes/api/auth.js +++ b/src/routes/api/auth.js @@ -1,4 +1,4 @@ -import { unauthorized } from '../../lib/errors.js'; +import { tooManyRequests, unauthorized } from '../../lib/errors.js'; /** * Sign-in and sign-out. Rate limiting is handled inside `verifyCredentials`, @@ -11,10 +11,16 @@ export default async function authRoutes(fastify, { settings }) { const result = await fastify.verifyCredentials(username, password, request); if (!result.ok) { - if (result.retryAfter) reply.header('retry-after', String(result.retryAfter)); - throw unauthorized(result.message, result.retryAfter ? 'rate_limited' : 'invalid_credentials'); + if (result.retryAfter) { + reply.header('retry-after', String(result.retryAfter)); + throw tooManyRequests(result.message, 'rate_limited'); + } + throw unauthorized(result.message, 'invalid_credentials'); } + // A fresh session id on every sign-in, so nothing issued before the password + // was proved can be carried across it. + await request.session.regenerate(); request.session.set('admin', { username: result.username, since: new Date().toISOString() }); await request.session.save(); diff --git a/src/routes/api/settings.js b/src/routes/api/settings.js index 24c622e..b8e4550 100644 --- a/src/routes/api/settings.js +++ b/src/routes/api/settings.js @@ -216,7 +216,7 @@ export default async function settingsRoutes(fastify, { config, settings, watche throw unprocessable('Some of those values need fixing.', 'validation_failed', fields); } - await fastify.setAdminPassword(password); + await fastify.setAdminPassword(password, { keepSessionId: request.session.sessionId }); return { ok: true }; }); } diff --git a/src/routes/api/setup.js b/src/routes/api/setup.js index ab451d8..0b9fd81 100644 --- a/src/routes/api/setup.js +++ b/src/routes/api/setup.js @@ -34,7 +34,7 @@ export default async function setupRoutes(fastify, { settings, events, shows }) fields.passwordConfirm = "Those two passwords don't match."; } if (!fields.password && !fields.passwordConfirm) { - await fastify.setAdminPassword(password); + await fastify.setAdminPassword(password, { keepSessionId: request.session.sessionId }); } } diff --git a/src/routes/api/status.js b/src/routes/api/status.js index b601c75..5455fec 100644 --- a/src/routes/api/status.js +++ b/src/routes/api/status.js @@ -18,8 +18,10 @@ export default async function statusRoutes(fastify, { settings, health, watcher, hasPublicBaseUrl: settings.hasPublicBaseUrl(), authenticated, // The banner has to be visible to whoever can reach the app, otherwise a - // permission problem is undiagnosable without SSH (spec §13.1). - issues: issues.map((issue) => ({ + // permission problem is undiagnosable without SSH (spec §13.1). Only the + // permission problems, though: the rest name shows and followed feeds, which + // an anonymous caller has no business reading. + issues: (authenticated ? issues : issues.filter((issue) => health.isPublicIssue(issue.key))).map((issue) => ({ key: issue.key, level: issue.level, message: issue.message, diff --git a/src/services/covers.js b/src/services/covers.js index 8243518..53c5d36 100644 --- a/src/services/covers.js +++ b/src/services/covers.js @@ -7,6 +7,7 @@ import { pipeline } from 'node:stream/promises'; import sharp from 'sharp'; import { + IMAGE_MAX_INPUT_PIXELS, ARTWORK_MAX_PX, ARTWORK_MIN_PX, CANONICAL_COVER_FILENAME, @@ -14,6 +15,11 @@ import { imageMimeType, } from '../constants.js'; import { badRequest } from '../lib/errors.js'; +import { describeImageError } from './episode-art.js'; + +/** Every decode refuses at the header past the pixel ceiling — see the constant. */ +const SHARP_LIMITS = Object.freeze({ limitInputPixels: IMAGE_MAX_INPUT_PIXELS }); +const isPixelLimitError = (err) => Boolean(describeImageError(err)); /** * Cover art detection, validation and normalisation (spec §10). @@ -53,7 +59,7 @@ export function createCovers({ config, logger }) { */ async inspect(filePath) { try { - const [meta, stats] = await Promise.all([sharp(filePath).metadata(), stat(filePath)]); + const [meta, stats] = await Promise.all([sharp(filePath, SHARP_LIMITS).metadata(), stat(filePath)]); const width = meta.width ?? null; const height = meta.height ?? null; return { @@ -110,12 +116,18 @@ export function createCovers({ config, logger }) { const target = join(showDir, CANONICAL_COVER_FILENAME); const tmp = join(showDir, `.cover-upload-${randomUUID()}.tmp`); try { - await sharp(sourcePath) + await sharp(sourcePath, SHARP_LIMITS) .rotate() // honour EXIF orientation before discarding metadata .jpeg({ quality: 90, mozjpeg: true }) .toFile(tmp); } catch (err) { await unlink(tmp).catch(() => {}); + if (isPixelLimitError(err)) { + throw badRequest( + `That image is too large to be used as cover art: it has more than ${Math.round(IMAGE_MAX_INPUT_PIXELS / 1_000_000)} million pixels. Podcast directories want a square between 1400 and 3000 pixels, so shrink it and try again.`, + 'image_too_large', + ); + } throw badRequest( "That file could not be read as an image. Cover art needs to be a JPEG, PNG or WebP.", 'invalid_image', @@ -144,7 +156,7 @@ export function createCovers({ config, logger }) { try { const background = await dominantEdgeColour(source); - await sharp(source) + await sharp(source, SHARP_LIMITS) .rotate() .resize(size, size, { fit: 'contain', background, withoutEnlargement: false }) .flatten({ background }) @@ -244,7 +256,7 @@ export function createCovers({ config, logger }) { */ async function dominantEdgeColour(filePath) { try { - const { dominant } = await sharp(filePath).stats(); + const { dominant } = await sharp(filePath, SHARP_LIMITS).stats(); if (dominant) return { r: dominant.r, g: dominant.g, b: dominant.b, alpha: 1 }; } catch { /* fall through to a neutral paper tone */ diff --git a/src/services/episode-art.js b/src/services/episode-art.js index f2f51e1..0075e43 100644 --- a/src/services/episode-art.js +++ b/src/services/episode-art.js @@ -5,7 +5,23 @@ import { join } from 'node:path'; import sharp from 'sharp'; -import { DIRECTORY_IMAGE_FORMATS } from '../constants.js'; +import { DIRECTORY_IMAGE_FORMATS, IMAGE_MAX_INPUT_PIXELS } from '../constants.js'; + +/** Every decode refuses at the header past the pixel ceiling — see the constant. */ +const SHARP_LIMITS = Object.freeze({ limitInputPixels: IMAGE_MAX_INPUT_PIXELS }); + +/** + * Whether sharp refused an image for its size rather than failing to parse it. + * + * Turned into a sentence the scan log can carry: "could not be read" would send the + * owner looking for corruption in a file that is perfectly valid, merely enormous. + */ +export function describeImageError(err) { + if (/pixel limit/i.test(err?.message ?? '')) { + return `The image is larger than ${Math.round(IMAGE_MAX_INPUT_PIXELS / 1_000_000)} million pixels, which SelfPod will not decode — a cover that size would take the server down with it. Shrink it to 3000×3000 or less.`; + } + return null; +} /** * Per-episode artwork storage (the cache behind the `art_*` columns on `episodes`). @@ -55,7 +71,20 @@ export function createEpisodeArt({ config, covers, logger }) { */ async store({ showId, episodeId, buffer, sourceFormat = null }) { const data = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer); - const probe = await sharp(data).metadata(); + let probe; + try { + probe = await sharp(data, SHARP_LIMITS).metadata(); + // `metadata()` reads the header without decoding, so the ceiling is enforced + // here by hand: the decode that would otherwise hit it comes later, after a + // JPEG or PNG has already been accepted as-is on the strength of this probe. + if ((probe.width ?? 0) * (probe.height ?? 0) > IMAGE_MAX_INPUT_PIXELS) { + throw new Error('Input image exceeds pixel limit'); + } + } catch (err) { + const why = describeImageError(err); + if (why) throw new Error(why, { cause: err }); + throw err; + } // What the bytes are, never what the tag claimed they were: an APIC frame // announcing `image/png` around JPEG data is a common tagger bug, and trusting @@ -74,12 +103,12 @@ export function createEpisodeArt({ config, covers, logger }) { let height = probe.height ?? null; if (!passthrough) { - bytes = await sharp(data) + bytes = await sharp(data, SHARP_LIMITS) .rotate() // honour EXIF orientation before the metadata is dropped .jpeg({ quality: 90, mozjpeg: true }) .toBuffer(); extension = '.jpg'; - const after = await sharp(bytes).metadata(); + const after = await sharp(bytes, SHARP_LIMITS).metadata(); width = after.width ?? width; height = after.height ?? height; } diff --git a/src/services/health.js b/src/services/health.js index a0a373c..496e182 100644 --- a/src/services/health.js +++ b/src/services/health.js @@ -14,6 +14,16 @@ import { describeFsError } from '../lib/errors.js'; * every failure in the hand-rolled version was invisible until a podcast app * broke. */ +/** Issue keys whose message carries nothing about the owner's shows. */ +const PUBLIC_ISSUE_KEYS = new Set([ + 'data_writable', + 'shows_readable', + 'temp_writable', + 'episode_art_writable', + 'entrypoint_selftest', + 'sqlite_journal', +]); + export function createHealth({ config, events, logger }) { /** key → { level, message, detail?, since } */ const issues = new Map(); @@ -59,6 +69,24 @@ export function createHealth({ config, events, logger }) { return [...issues.values()].filter((issue) => issue.level === 'error' || issue.level === 'warn'); }, + /** + * The banners that may be shown before anyone has signed in. + * + * The permission problems have to be visible on the sign-in page — a container + * that cannot write its own data directory is undiagnosable otherwise (spec + * §13.1). But every other issue names something private: a show's title, the + * host of a feed being followed, which episode's cut copy went missing. Feeds + * are private by their token; their names should not be readable by whoever + * finds the tunnel hostname. + */ + publicBanners() { + return api.banners().filter((issue) => PUBLIC_ISSUE_KEYS.has(issue.key)); + }, + + isPublicIssue(key) { + return PUBLIC_ISSUE_KEYS.has(key); + }, + hasErrors() { return [...issues.values()].some((issue) => issue.level === 'error'); }, diff --git a/src/web/routes/fragments.js b/src/web/routes/fragments.js index 496141d..87e2bcc 100644 --- a/src/web/routes/fragments.js +++ b/src/web/routes/fragments.js @@ -1607,7 +1607,7 @@ export default async function fragmentRoutes(fastify, services) { return reply.view('partials/modal-change-password.eta', { errors, helpers: fastify.viewHelpers }); } - await fastify.setAdminPassword(password); + await fastify.setAdminPassword(password, { keepSessionId: request.session.sessionId }); if (!isHtmx(request)) return redirectBack(request, reply, '/settings', 'Password changed.'); return reply.view('partials/modal-closed.eta', { toast: { message: 'Password changed.', level: 'ok' }, diff --git a/src/web/routes/pages.js b/src/web/routes/pages.js index 70247d0..13c5a23 100644 --- a/src/web/routes/pages.js +++ b/src/web/routes/pages.js @@ -86,7 +86,7 @@ export default async function pageRoutes(fastify, services) { next: sanitiseNext(request.query?.next), firstRun: settings.mustChangePassword(), error: request.query?.error === 'invalid' ? 'That username and password combination is not correct.' : null, - issues: health.banners(), + issues: health.publicBanners(), }, BARE_LAYOUT, ); @@ -97,7 +97,10 @@ export default async function pageRoutes(fastify, services) { const result = await fastify.verifyCredentials(username, password, request); if (!result.ok) { - reply.status(401); + // 429 with Retry-After when it is the throttle answering, so a script or a + // proxy can tell "wrong password" from "not now" without parsing the page. + if (result.retryAfter) reply.header('retry-after', String(result.retryAfter)); + reply.status(result.retryAfter ? 429 : 401); return reply.view( 'pages/login.eta', { @@ -106,12 +109,15 @@ export default async function pageRoutes(fastify, services) { username, firstRun: settings.mustChangePassword(), error: result.message, - issues: health.banners(), + issues: health.publicBanners(), }, BARE_LAYOUT, ); } + // A fresh session id on every sign-in, so nothing issued before the password + // was proved can be carried across it. + await request.session.regenerate(); request.session.set('admin', { username: result.username, since: new Date().toISOString() }); await request.session.save(); @@ -177,7 +183,7 @@ export default async function pageRoutes(fastify, services) { reply.status(422); return reply.view('pages/setup.eta', setupContext(1, { errors }), BARE_LAYOUT); } - await fastify.setAdminPassword(password); + await fastify.setAdminPassword(password, { keepSessionId: request.session.sessionId }); return reply.redirect('/setup/2', 303); }); diff --git a/test/integration/http.test.js b/test/integration/http.test.js index b7d2c07..d0f2655 100644 --- a/test/integration/http.test.js +++ b/test/integration/http.test.js @@ -105,7 +105,9 @@ describe('authentication (spec §12.1)', () => { payload: { username: 'admin', password: ADMIN_PASSWORD }, headers: { 'sec-fetch-site': 'same-origin', 'x-forwarded-for': '203.0.113.99' }, }); - assert.equal(spoofed.statusCode, 401); + // 429, not 401: the throttle answering is not "wrong password", and a script or + // proxy should be able to tell the two apart without parsing the message. + assert.equal(spoofed.statusCode, 429); assert.equal(spoofed.json().error.code, 'rate_limited'); assert.ok(spoofed.headers['retry-after']); }); diff --git a/test/security/auth-and-headers.test.js b/test/security/auth-and-headers.test.js index 53dac60..62da663 100644 --- a/test/security/auth-and-headers.test.js +++ b/test/security/auth-and-headers.test.js @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { after, before, describe, it } from 'node:test'; -import { createTestServer } from '../helpers/http.js'; +import { ADMIN_PASSWORD, createTestServer } from '../helpers/http.js'; /** * Adversarial tests for authentication, session handling and response hardening. @@ -136,6 +136,133 @@ describe('the admin surface cannot be reached without credentials', () => { } }); + it('signs every other session out when the password changes', async () => { + const fresh = await createTestServer(); + try { + await fresh.login(); + const phone = fresh.cookie; + await fresh.login(); + const laptop = fresh.cookie; + assert.notEqual(phone, laptop, 'two sign-ins should be two sessions'); + + const change = await fresh.app.inject({ + method: 'POST', + url: '/api/settings/password', + headers: { cookie: laptop, 'sec-fetch-site': 'same-origin' }, + payload: { + currentPassword: ADMIN_PASSWORD, + password: 'a-new-password-123', + passwordConfirm: 'a-new-password-123', + }, + }); + assert.equal(change.statusCode, 200, change.body); + + const stolen = await fresh.app.inject({ + method: 'GET', + url: '/api/settings', + headers: { cookie: phone, 'sec-fetch-site': 'same-origin' }, + }); + assert.equal(stolen.statusCode, 401, 'the other session survived a password change'); + const own = await fresh.app.inject({ + method: 'GET', + url: '/api/settings', + headers: { cookie: laptop, 'sec-fetch-site': 'same-origin' }, + }); + assert.equal(own.statusCode, 200, 'the session that changed the password was signed out too'); + } finally { + await fresh.cleanup(); + } + }); + + it('issues a new session id on sign-in rather than promoting the one it was handed', async () => { + const fresh = await createTestServer(); + try { + await fresh.login(); + const before = fresh.cookie; + const again = await fresh.app.inject({ + method: 'POST', + url: '/api/login', + payload: { username: 'admin', password: ADMIN_PASSWORD }, + headers: { cookie: before, 'sec-fetch-site': 'same-origin' }, + }); + assert.equal(again.statusCode, 200); + const issued = again.headers['set-cookie']; + assert.ok(issued, 'a sign-in with an existing cookie must still set a cookie'); + const sid = (value) => String(value).split(';')[0]; + assert.notEqual(sid(issued), sid(before), 'the session id did not change on sign-in'); + } finally { + await fresh.cleanup(); + } + }); + + it('never locks the account out for more than a minute, however hard a stranger tries', async () => { + const fresh = await createTestServer(); + try { + const justNow = new Date(Date.now() - 1000).toISOString(); + const insert = fresh.db.prepare( + 'INSERT INTO login_attempts (username, attempted_at, succeeded, source) VALUES (?, ?, 0, ?)', + ); + for (let i = 0; i < 40; i += 1) insert.run('admin', justNow, `203.0.113.${i}|`); + + // Forty failures from forty addresses a second ago: the account waits, but + // only a minute — one wrong password every five minutes used to keep the + // owner out for as long as the stranger cared to carry on. + const accountWait = fresh.app.loginBackoffSeconds('admin'); + assert.ok(accountWait > 0, 'the account should be backing off'); + assert.ok(accountWait <= 60, `the account lock was ${accountWait}s`); + + // Whereas the address that did the guessing waits the full five minutes. + for (let i = 0; i < 10; i += 1) insert.run('admin', justNow, '198.51.100.7|'); + const sourceWait = fresh.app.loginBackoffSeconds('admin', '198.51.100.7|'); + assert.ok(sourceWait > 60, `the guessing source only waits ${sourceWait}s`); + assert.equal(fresh.app.loginBackoffSeconds('admin', '192.0.2.1|'), accountWait, 'an innocent address waits only the account minute'); + + // And the throttle answers 429, not "wrong password". + const refused = await fresh.app.inject({ + method: 'POST', + url: '/login', + payload: 'username=admin&password=whatever', + headers: { 'content-type': 'application/x-www-form-urlencoded', 'sec-fetch-site': 'same-origin' }, + }); + assert.equal(refused.statusCode, 429); + assert.ok(refused.headers['retry-after']); + } finally { + await fresh.cleanup(); + } + }); + + it('shows a stranger only the permission banners, never a show or a feed by name', async () => { + const fresh = await createTestServer(); + try { + fresh.health.set('trimmed_missing_show1', { + level: 'warn', + message: 'SelfPod is serving “Secret Tape Club” with its adverts back in.', + }); + fresh.health.set('shows_readable', { + level: 'error', + message: 'SelfPod cannot read your shows folder `/data/shows`.', + }); + + const anonymousStatus = await fresh.app.inject({ url: '/api/status' }); + assert.equal(anonymousStatus.statusCode, 200); + assert.doesNotMatch(anonymousStatus.body, /Secret Tape Club/); + assert.match(anonymousStatus.body, /cannot read your shows folder/); + + const loginPage = await fresh.app.inject({ url: '/login' }); + assert.doesNotMatch(loginPage.body, /Secret Tape Club/); + assert.match(loginPage.body, /cannot read your shows folder/); + + await fresh.login(); + const ownStatus = await fresh.app.inject({ + url: '/api/status', + headers: { cookie: fresh.cookie }, + }); + assert.match(ownStatus.body, /Secret Tape Club/, 'the owner still sees everything'); + } finally { + await fresh.cleanup(); + } + }); + it('ends a session server-side on logout', async () => { await server.login(); const cookie = server.cookie; diff --git a/test/security/image-bomb.test.js b/test/security/image-bomb.test.js new file mode 100644 index 0000000..9c1de5b --- /dev/null +++ b/test/security/image-bomb.test.js @@ -0,0 +1,105 @@ +import assert from 'node:assert/strict'; +import { writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { after, before, describe, it } from 'node:test'; +import { deflateSync } from 'node:zlib'; + +import { createTestServer } from '../helpers/http.js'; +import { IMAGE_MAX_INPUT_PIXELS } from '../../src/constants.js'; + +/** + * A decompression bomb dropped on the share. + * + * `/data/shows` is a network share other people can write to, so a cover or an + * episode sidecar is a stranger's choice. sharp's default pixel ceiling is ~268 + * megapixels; an 8000×8000 PNG of one colour is 60 KB on disk and 192 MB decoded, + * and 16000×16000 is a gigabyte. The scanner decodes sidecars on its own, on every + * scan, so one such file used to be a crash loop with no banner to explain it. + */ +const SIDE = 8000; // 64 megapixels: past the 40 MP ceiling, cheap to build in a test + +function crc32(buffer) { + let crc = 0xffffffff; + for (let i = 0; i < buffer.length; i += 1) { + let c = (crc ^ buffer[i]) & 0xff; + for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + crc = (crc >>> 8) ^ c; + } + return (crc ^ 0xffffffff) >>> 0; +} + +function chunk(type, data) { + const length = Buffer.alloc(4); + length.writeUInt32BE(data.length); + const typed = Buffer.concat([Buffer.from(type, 'ascii'), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(typed)); + return Buffer.concat([length, typed, crc]); +} + +/** A valid 8-bit greyscale PNG of one colour: tiny on disk, enormous decoded. */ +function bombPng(side) { + const header = Buffer.alloc(13); + header.writeUInt32BE(side, 0); + header.writeUInt32BE(side, 4); + header[8] = 8; // bit depth + header[9] = 0; // greyscale + const rows = Buffer.alloc(side * (side + 1)); // one filter byte per row, then zeros + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', header), + chunk('IDAT', deflateSync(rows, { level: 9 })), + chunk('IEND', Buffer.alloc(0)), + ]); +} + +describe('an image too large to decode safely', () => { + let server; + let png; + + before(async () => { + server = await createTestServer(); + png = bombPng(SIDE); + assert.ok(SIDE * SIDE > IMAGE_MAX_INPUT_PIXELS, 'the test image must exceed the ceiling'); + assert.ok(png.length < 200_000, `the bomb should be small on disk, got ${png.length} bytes`); + }); + + after(async () => { + await server.cleanup(); + }); + + it('is refused as episode artwork with a sentence that says why', async () => { + await assert.rejects( + server.episodeArt.store({ showId: 'show', episodeId: 'episode', buffer: png }), + /million pixels/, + ); + }); + + it('is refused as an uploaded cover without being decoded', async () => { + const dir = await server.makeShowFolder('bomb-upload'); + const source = join(dir, 'upload.png'); + await writeFile(source, png); + await assert.rejects(server.covers.saveUpload(dir, source), (err) => { + assert.equal(err.code, 'image_too_large'); + assert.match(err.message, /million pixels/); + return true; + }); + }); + + it('does not stop a scan, and the scan log says what happened', async () => { + await server.addAudio('bomb-sidecar', 'sample.mp3', 'episode.mp3'); + await writeFile(join(server.config.showsDir, 'bomb-sidecar', 'episode.png'), png); + await server.scanner.scanAllNow('manual'); + + const show = server.shows.getBySlug('bomb-sidecar'); + assert.ok(show, 'the show was still discovered'); + const [episode] = server.episodes.listByShow(show.id); + assert.ok(episode, 'the episode beside the bomb was still added'); + assert.equal(episode.art_source ?? null, null, 'the bomb was not adopted as artwork'); + + const scan = server.activity.latestForShow(show.id); + const warning = scan.warnings.find((w) => /episode\.png/.test(w.file ?? '') || /episode\.png/.test(w.message)); + assert.ok(warning, `expected a warning naming episode.png, got ${JSON.stringify(scan.warnings)}`); + assert.match(warning.message, /million pixels/); + }); +}); From bc32840562458cb0affffa22040c9e9382f26dd8 Mon Sep 17 00:00:00 2001 From: antoine-debroye <144667691+antoine-debroye@users.noreply.github.com> Date: Fri, 9 Oct 2026 18:26:49 +0100 Subject: [PATCH 2/8] =?UTF-8?q?Answer=20every=20press,=20keep=20what=20is?= =?UTF-8?q?=20being=20typed,=20and=20fit=20a=20phone=20(audit=20tier=204,?= =?UTF-8?q?=20U1=E2=80=93U20)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Items U1–U12 and U14–U20 of doc/audit-2026-10-09.md §4. Broken or silent actions: Remove/Delete from the episode's own page re-targeted a table that page does not have, so nothing happened; the four Subscription status buttons posted into a redirect the XHR swallowed; the password-changed toast put hx-swap-oob on the toast itself and arrived as bare text. Each now answers with HX-Redirect and a flash, or a real toast, and Stop following asks first. Every decision, teach, check, rescan and settings control is held and shows a ring while its request is out (hx-indicator / hx-disabled-elt / hx-sync), htmx:sendError is reported, and a 401 with HX-Redirect no longer flashes an error on its way to sign-in. Check now and the three Teach routes start the pass and answer at once on the htmx path; the plain form still waits. Background refreshes: a swap the page asked for itself (sse:, load, script) is held while a field inside it is focused or dirty and taken once it is not; a
someone toggled keeps its state across swaps; the stream's re-render of a target with a user request in flight is dropped, which removes the double render after every decision. Phone: the topbar actions wrap under the breadcrumb below 640px; the access log and both statistics tables stack with data-label column names (thead kept for screen readers); 44px targets on coarse pointers, with the cut bar's tap area on a wrapper so the track keeps its 14px. Contrast: --accent-2 for button fills and text-sized accent, --ink-soft for muted text that carries information. Also: the SSE scan-progress strip is the same partial as the clicked one, with its polling backstop; keyboard focus is put back after swaps and modal closes; error toasts persist and are alerts, others scale with length, mouseleave resumes; Settings switches get accessible names, card titles are h2, refused fields carry aria-invalid/aria-describedby, the breadcrumb marks the current page, a refused sign-in focuses the password; new-show no longer pre-fills the page title and keeps what was typed; upload success is green; the dashboard is highlighted in the sidebar (and the sidebar's aria-current, rendered through the escaping tag, is now a real attribute); settings toggles and inline saves say they saved; the cut pill links to the episode page. A date at the start of a filename (YYYY-MM-DD, with -, _, . or nothing) is the episode's publish date at midnight in TZ on first sight, unless the mtime already falls on that day; undated files keep the mtime; a rescan never touches pub_date. Co-Authored-By: Claude Fable 5.1 --- .gitignore | 2 + CHANGELOG.md | 66 ++++ README.md | 11 +- doc/selfpod-spec.md | 7 +- src/services/adverts-view.js | 6 +- src/services/scanner.js | 45 ++- src/web/public/css/app.css | 163 ++++++++-- src/web/public/js/app.js | 300 +++++++++++++++++- src/web/routes/events.js | 57 +++- src/web/routes/fragments.js | 210 ++++++++---- src/web/routes/pages.js | 17 +- src/web/views/pages/activity.eta | 4 +- src/web/views/pages/dashboard.eta | 2 +- src/web/views/pages/episode-edit.eta | 6 +- src/web/views/pages/login.eta | 13 +- src/web/views/pages/settings.eta | 24 +- src/web/views/pages/setup.eta | 18 +- src/web/views/pages/show-detail.eta | 2 +- src/web/views/pages/show-new.eta | 16 +- src/web/views/pages/stats.eta | 36 ++- src/web/views/pages/subscription.eta | 24 +- src/web/views/partials/access-log-rows.eta | 20 +- src/web/views/partials/access-log.eta | 9 +- src/web/views/partials/ad-action.eta | 9 +- src/web/views/partials/ad-panel.eta | 19 +- src/web/views/partials/cut-bar.eta | 12 +- src/web/views/partials/episode-adverts.eta | 4 +- src/web/views/partials/episode-form.eta | 22 +- src/web/views/partials/episode-row.eta | 6 + src/web/views/partials/episode-table.eta | 2 +- src/web/views/partials/episode-transcript.eta | 5 +- src/web/views/partials/feed-readiness.eta | 2 +- .../views/partials/modal-change-password.eta | 18 +- src/web/views/partials/modal-closed.eta | 12 +- .../views/partials/modal-delete-episode.eta | 13 +- src/web/views/partials/modal-delete-show.eta | 7 +- src/web/views/partials/modal-new-show.eta | 11 +- src/web/views/partials/modal-rebuild-show.eta | 7 +- .../views/partials/modal-stop-following.eta | 27 ++ src/web/views/partials/settings-row.eta | 24 +- src/web/views/partials/show-meta-form.eta | 33 +- src/web/views/partials/show-reach.eta | 2 +- src/web/views/partials/sidebar.eta | 10 +- src/web/views/partials/stats-chart-apps.eta | 2 +- src/web/views/partials/stats-chart-daily.eta | 2 +- src/web/views/partials/subscription-form.eta | 20 +- src/web/views/partials/subscription-items.eta | 2 +- .../views/partials/subscription-preview.eta | 2 +- src/web/views/partials/teach-range.eta | 1 + src/web/views/partials/toast.eta | 6 +- src/web/views/partials/topbar.eta | 2 +- test/integration/ad-timeline-ui.test.js | 2 +- test/integration/subscriptions-ui.test.js | 66 ++++ test/integration/ui.test.js | 200 ++++++++++++ test/unit/scanner.test.js | 74 +++++ 55 files changed, 1401 insertions(+), 281 deletions(-) create mode 100644 src/web/views/partials/modal-stop-following.eta diff --git a/.gitignore b/.gitignore index 53c5b8c..cb53f20 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ node_modules/ .devdata/ +# A second dev instance beside the first (another port, another data folder). +.devdata-*/ .dockerdata/ *.log .DS_Store diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dacf85..e1d567c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -72,6 +72,72 @@ changes what your listeners see, it says so. (libheif and librsvg), music-metadata 11.16.1 (crafted MP4, EBML and DSF files could crash the scanner — and the scanner reads whatever is dropped on the share). `npm audit` is clean. +### Fixed — things you could do that gave no answer, or the wrong one + +- **Remove or delete from an episode's own page now works.** The response re-targeted the + episode table, which only the show page has; on the episode page htmx refused it and the + page went on showing an episode that was gone. Both actions now take you to the show, with + the confirmation, when they were started on the episode page. +- **Check now, Pause, Resume and Stop following on the Subscription page do something you + can see.** They used to post into a redirect the browser swallowed; the page re-reads + itself now and says what happened. Stop following asks first, like every other action + that cannot be undone. +- **A password change is confirmed with a real notice.** The toast arrived as bare text with + a × that threw. +- **A button that is working says so.** Every decision, teach, check, rescan and settings + button is held while its request is out and shows a ring; a second press while one is in + flight is dropped rather than queued. A request that gets no answer at all — offline, a + tunnel that dropped, an extension in the way — now says so instead of failing in silence, + and a session that has run out no longer flashes "Something went wrong" on its way to the + sign-in page. +- **Check now and Teach no longer hold the page for the whole pass.** The panel comes back at + once with a note, and the work strip follows the pass; the plain-form path still waits. +- **A background refresh no longer wipes what you are typing.** The Adverts panel and the + episode's cuts card re-read themselves after every pass, scheduled ones included, and used + to throw away a half-typed boundary and close the settings fold under you. A refresh now + waits while a field inside it is in use, and is taken once it is not; a fold you opened + stays open; and the second render after every decision — the stream announcing what the + response already carried — is gone. +- **The Show page topbar fits a phone**: the actions take a row of their own under the + breadcrumb instead of pushing it onto four lines and "Follow a feed" off the edge. +- **The access log and the statistics tables are readable on a phone**: each row is a block + with its column names, like the episode table already was, rather than a six-column table + scrolling sideways. The column headers stay for screen readers. +- **The scan-progress strip sent over the live stream could be left behind forever** when + the stream dropped mid-scan: the streamed copy omitted the poll the clicked one has. It is + the same strip now. +- "New show" no longer opens with "New show" already typed into the name, and a refused form + keeps what you typed. The upload queue's success line is no longer painted red. The + dashboard is highlighted in the sidebar when you are on it — and `aria-current` on the + sidebar's current item is now a real attribute rather than escaped text. Settings toggles + and inline saves confirm themselves. The cut pill in the episode table links to the + episode page, where the bar always is, rather than to an anchor the Adverts page may have + paged away. + +### Changed + +- **A date at the start of a filename is the episode's publish date.** `2026-09-01-…`, + `2026_09_01…` or `20260901…` is taken as that day at midnight in `TZ`, unless the file's + modification time already falls on that day, in which case the time of day is kept. Three + dated files copied onto the share together used to land on the one minute they were + copied. Undated files keep the modification time, and a date set on the episode page is + never changed by a rescan. README, *How it finds new episodes*. +- **Colour and size, for people and thumbs.** Primary buttons, accent-coloured text and + selected chips use the darker terracotta (`#B84A1E`, 7.4:1 on white) rather than the one + that fell short of AA for text; the signal colour stays on bars, dots and marks. Muted + grey text that carried information — the "· test" affordance, stat-card hints, timestamps, + label hints — is a shade darker. On a touch screen every control is at least 44px: the + stretch ▶, the toast ×, chips, sign-out, the menu button, the small decision buttons, and + the cut bar gets a taller area to tap without looking any different. +- **Keyboard focus survives a swap.** After saving a setting, sorting the log, restoring an + episode or closing a modal, focus goes back to the control it was on — or to the control + that opened the modal — rather than to the top of the page. Errors are announced as alerts + and stay until dismissed; other notices stay six seconds plus fifty milliseconds a + character, and pausing with the pointer resumes when it leaves. The two Settings switches + have accessible names, card titles are real headings, a refused field says so to assistive + technology, the current breadcrumb is marked, and a refused sign-in puts the cursor on the + password. + ## 1.9.1 — 2026-09-16 ### Fixed diff --git a/README.md b/README.md index 353c88b..4f9ad29 100644 --- a/README.md +++ b/README.md @@ -263,7 +263,7 @@ of it can be changed later in **Settings** without touching the container. |---|---|---| | `PUBLIC_BASE_URL` | — | The address your proxy serves SelfPod on, e.g. `https://podcast.example.com`. Every feed and media URL is built from it. No trailing slash. Can also be set in the setup wizard. | | `PUID` / `PGID` | `1000` | The user and group SelfPod runs as. Match the owner of your audio files. | -| `TZ` | `UTC` | Used for displayed dates and an episode's default publish date. | +| `TZ` | `UTC` | Used for displayed dates and an episode's default publish date — see [How it finds new episodes](#how-it-finds-new-episodes). | | `PORT` | `8080` | Port inside the container. | | `RESCAN_INTERVAL_SECONDS` | `300` | How often the whole library is re-checked as a fallback. 60–21600. | | `MISSING_GRACE_SECONDS` | `86400` | How long an episode whose file vanished stays in the feed, so a brief share outage doesn't drop episodes. | @@ -471,6 +471,15 @@ shows the current mode. It deliberately does not sit in a banner across every pa a banner that is always there is a banner nobody reads when something is actually wrong. +**The publish date** of a new episode comes from its filename when the name starts +with a date — `2026-09-01-episode-one.mp3`, `2026_09_01 …` or `20260901 …` — at +midnight in your `TZ`. Otherwise it is the file's modification time, which is right +for a file that was just recorded and wrong for three dated files copied onto the +share together, which would all land on the minute they were copied. A modification +time that already falls on the named day is kept, because it also carries the time +of day. Either way it is only a starting point: the date you set on the episode page +is never changed by a rescan. + ## Security SelfPod is built to be published to the internet, so the design assumes the address diff --git a/doc/selfpod-spec.md b/doc/selfpod-spec.md index fdba2c0..4d3e0a1 100644 --- a/doc/selfpod-spec.md +++ b/doc/selfpod-spec.md @@ -246,7 +246,12 @@ Required behavior: used only as a *suggested* title if the user hasn't set one, never silently overwrites a user-edited title on rescan. - Compute/assign a stable GUID (§7.2). - - Insert into the database with `pub_date` defaulting to file mtime. + - Insert into the database with `pub_date` defaulting to the date the filename + starts with (`YYYY-MM-DD`, with `-`, `_`, `.` or nothing between the parts, + at midnight in `TZ`) when there is one and the file mtime falls on another + day; otherwise to the file mtime. First insert only — a rescan never + rewrites `pub_date`, and a user-set date (`pub_date_is_custom`) is never + touched. 3. For each file previously known but no longer present on disk, mark the episode `missing` (soft state, not deleted) rather than removing it from the feed immediately — avoids apps re-downloading/duplicating diff --git a/src/services/adverts-view.js b/src/services/adverts-view.js index a55725f..107d919 100644 --- a/src/services/adverts-view.js +++ b/src/services/adverts-view.js @@ -621,7 +621,11 @@ export function createAdvertsView({ db, adDetect, transcriber, episodes, shows } if (data.off) return summaries; for (const episode of episodes.listByShow(show.id)) { const state = api.episodeState(episode, api.stretchesOf(episode, data), data); - if (state) summaries.set(episode.id, { ...state, url: `/shows/${encodeURIComponent(show.slug)}/adverts#ep-${episode.id}` }); + // The episode's own page, where the same bar is drawn under #episode-cuts. The + // Adverts page used to be the link, with `#ep-` as the anchor — but that + // page shows thirty episodes at a time, so for anything older the anchor was + // not there and the link landed at the top. + if (state) summaries.set(episode.id, { ...state, url: `/shows/${encodeURIComponent(show.slug)}/episodes/${encodeURIComponent(episode.id)}#episode-cuts` }); } return summaries; }, diff --git a/src/services/scanner.js b/src/services/scanner.js index 0caef85..43a09b7 100644 --- a/src/services/scanner.js +++ b/src/services/scanner.js @@ -11,7 +11,7 @@ import { imageMimeType, isSupportedAudioFile, } from '../constants.js'; -import { nowIso } from '../lib/dates.js'; +import { fromLocalInputValue, nowIso, toLocalInputValue } from '../lib/dates.js'; import { EVENTS } from '../lib/events.js'; import { initialPublishHold } from '../lib/publish-hold.js'; import { computeIdentityKey } from '../lib/identity.js'; @@ -385,7 +385,9 @@ export function createScanner({ mtimeIso = nowIso(); warnings.push({ file: filename, - message: `\`${filename}\` has a modification time SelfPod cannot read, so today's date is used as its publish date. You can set the publish date yourself on the episode page.`, + message: dateInFilename(filename) + ? `\`${filename}\` has a modification time SelfPod cannot read, so its publish date is the date its name starts with. You can set the publish date yourself on the episode page.` + : `\`${filename}\` has a modification time SelfPod cannot read, so today's date is used as its publish date. You can set the publish date yourself on the episode page.`, }); } else { errors.push(activity.formatFileError(filename, err)); @@ -566,7 +568,9 @@ export function createScanner({ description: meta.description ?? '', season: meta.season ?? null, episode_number: meta.episodeNumber ?? null, - pub_date: mtimeIso, + // First sight only. A rescan never touches pub_date, so a date set on the + // episode page stays, whatever the file or its name says afterwards. + pub_date: publishDateFor(filename, mtimeIso, config.timeZone), duration_seconds: meta.durationSeconds, bitrate_kbps: meta.bitrateKbps, file_size_bytes: stats.size, @@ -931,6 +935,41 @@ function returnedFromExpiry(filename) { return `\`${filename}\` is back after being gone longer than the grace period, so it has returned to the feed with its original episode identity — subscribers keep their played state.`; } +/** + * The date a filename starts with, as `YYYY-MM-DD` — the same prefix titleFromFilename + * strips, and the one the remote fetcher writes. Null when there is none, or when the + * digits are not a day that exists. + */ +export function dateInFilename(filename) { + const match = String(filename ?? '').match(/^(\d{4})[-_.]?(\d{2})[-_.]?(\d{2})/); + if (!match) return null; + const [, y, m, d] = match; + const probe = new Date(Date.UTC(+y, +m - 1, +d)); + if (probe.getUTCFullYear() !== +y || probe.getUTCMonth() !== +m - 1 || probe.getUTCDate() !== +d) return null; + return `${y}-${m}-${d}`; +} + +/** + * The publish date an episode gets when it is first seen. + * + * A file named `2026-09-01-…` says when it was published, and that beats the + * modification time: three dated files copied onto the share together all carry the + * moment they were copied, which put them in the feed as one episode on the same + * minute. The name wins unless the modification time already falls on that day — in + * the instance's zone or in UTC — in which case it is kept, because it also carries + * the time of day and the remote fetcher sets it to the exact moment of publication. + * Without a date in the name the modification time is the answer, as it always was. + */ +export function publishDateFor(filename, mtimeIso, timeZone) { + const dated = dateInFilename(filename); + if (!dated) return mtimeIso; + const sameDay = + toLocalInputValue(mtimeIso, { timeZone }).slice(0, 10) === dated || + String(mtimeIso ?? '').slice(0, 10) === dated; + if (sameDay) return mtimeIso; + return fromLocalInputValue(`${dated}T00:00`, { timeZone }) ?? mtimeIso; +} + /** "2026-08-07-episode-one.m4a" → "Episode One" (a suggestion, never a lock). */ function titleFromFilename(filename) { const withoutExt = filename.replace(/\.[^.]+$/, ''); diff --git a/src/web/public/css/app.css b/src/web/public/css/app.css index 5d04e30..6d56fe5 100644 --- a/src/web/public/css/app.css +++ b/src/web/public/css/app.css @@ -90,8 +90,10 @@ --text: #1B1D22; /* primary text on paper */ /* --- Accent: Signal Terracotta (the signature) --- */ - --accent: #D9602B; /* primary accent — warm broadcast amber-red */ - --accent-2: #B84A1E; /* hover / pressed */ + --accent: #D9602B; /* primary accent — bars, dots, marks, outlines: never text */ + --accent-2: #B84A1E; /* A11Y · text-sized accent and button fills: 7.4:1 on white, 6.6:1 on paper + (#D9602B is 3.7:1, short of AA for text and for white on it) */ + --accent-3: #9A3C16; /* hover / pressed for --accent-2 fills */ --accent-soft: #F3D9C8; /* tint background */ --accent-ink: #7A3215; /* text on tint */ @@ -194,7 +196,7 @@ body::before { } .section-tag { - font-family: var(--mono); font-size: 11px; color: var(--accent); + font-family: var(--mono); font-size: 11px; color: var(--accent-2); font-weight: 600; letter-spacing: .06em; text-transform: uppercase; margin-bottom: 8px; } @@ -261,6 +263,25 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } .htmx-request .htmx-indicator, .htmx-request.htmx-indicator { display: inline-flex; } +/* ADDED · a button that is waiting on its request says so. + htmx puts `htmx-request` on the element that made the request and on whatever + `hx-indicator` names — every action button in the app names itself — so the ring + appears in the button and goes when the answer comes, with no markup per button. + `hx-disabled-elt` holds it meanwhile, which is what the [disabled] rule draws. */ +.btn.htmx-request, +.icon-btn.htmx-request { pointer-events: none; } +.btn.htmx-request::after, +.icon-btn.htmx-request::after { + content: ""; width: 12px; height: 12px; flex: none; + border-radius: 50%; + border: 2px solid currentColor; border-right-color: transparent; + animation: sp-spin .6s linear infinite; +} +.icon-btn.htmx-request svg { display: none; } +.btn[disabled], +.icon-btn[disabled] { opacity: .55; cursor: not-allowed; } +.btn.htmx-request[disabled] { opacity: .8; cursor: progress; } + @keyframes sp-spin { to { transform: rotate(360deg); } } @@ -276,8 +297,9 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } padding: 9px 15px; cursor: pointer; transition: .15s; text-decoration: none; } .btn svg { width: 16px; height: 16px; } -.btn-primary { background: var(--accent); color: #fff; } -.btn-primary:hover { background: var(--accent-2); } +/* A11Y · was --accent: white on #D9602B is 3.7:1 */ +.btn-primary { background: var(--accent-2); color: #fff; } +.btn-primary:hover { background: var(--accent-3); } .btn-ghost { background: transparent; color: var(--ink); border-color: var(--line-2); } .btn-ghost:hover { background: var(--paper-2); } .btn-ink { background: var(--ink); color: #ECE7DA; } @@ -764,8 +786,9 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } } /* A11Y · was --ink-mute */ .dropzone p { color: var(--ink-soft); font-size: 14px; } -.dropzone p a { color: var(--accent); font-weight: 600; } -.dropzone .or { margin: 18px 0; font-size: 12px; color: var(--ink-mute); } +.dropzone p a { color: var(--accent-2); font-weight: 600; } +/* A11Y · was --ink-mute */ +.dropzone .or { margin: 18px 0; font-size: 12px; color: var(--ink-soft); } .queue { margin-top: 20px; } .queue-item { @@ -912,7 +935,7 @@ hr.soft { border: none; border-top: 1px solid var(--line); margin: 22px 0; } font-family: var(--mono); font-size: 12px; font-weight: 600; } .setup-progress .step.done .n { background: var(--ok); color: #fff; border-color: var(--ok); } -.setup-progress .step.active .n { background: var(--accent); color: #fff; border-color: var(--accent); } +.setup-progress .step.active .n { background: var(--accent-2); color: #fff; border-color: var(--accent-2); } .setup-progress .step.active { color: var(--ink); font-weight: 600; } .setup-progress .bar { flex: 1; height: 2px; background: var(--line); border-radius: 1px; } .setup-progress .bar.done { background: var(--ok); } @@ -984,6 +1007,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } } .toast--ok { border-left-color: var(--ok); } .toast--err { border-left-color: var(--err); } +.toast--warn { border-left-color: var(--warn); } +.toast--leaving { opacity: 0; transition: opacity .22s; } .toast__title { font-weight: 600; color: var(--ink); display: block; } .toast__body { flex: 1; min-width: 0; } .toast__close { @@ -1076,9 +1101,25 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .toast { max-width: none; } } -/* larger hit targets on touch devices */ +/* ADDED · the topbar on a phone. The action cluster used to sit beside the + breadcrumb at any width, which squeezed a three-level breadcrumb into four lines + and pushed "Follow a feed" off the right edge. Below 640px the actions take a row + of their own under the breadcrumb, and a bar with no actions keeps one row. */ +@media (max-width: 640px) { + .topbar { flex-wrap: wrap; row-gap: 10px; } + .topbar .crumbs { flex: 1 1 0; min-width: 0; overflow-wrap: anywhere; } + .topbar .right { flex: 1 0 100%; margin-left: 0; flex-wrap: wrap; gap: 8px; } + .topbar .right:not(:has(.btn)) { display: none; } +} + +/* larger hit targets on touch devices: 44px, the size a thumb can be sure of. + The rules for components defined later in this file live at the very end (§18), + where they are not outranked by the component's own size. */ @media (pointer: coarse) { - .icon-btn { width: 40px; height: 40px; } + .icon-btn { width: 44px; height: 44px; } + .btn-sm { min-height: 44px; padding-top: 10px; padding-bottom: 10px; } + .nav-toggle { width: 44px; height: 44px; } + .toast__close { width: 44px; height: 44px; margin: -12px -14px -12px auto; } } @@ -1131,7 +1172,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } } .topbar .public-url:hover { border-color: var(--line-2); } .topbar .public-url__host { max-width: 22ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.topbar .public-url__action { color: var(--ink-mute); margin-left: 4px; } +/* A11Y · was --ink-mute: "· test" is an affordance, not decoration */ +.topbar .public-url__action { color: var(--ink-soft); margin-left: 4px; } .topbar .public-url--unset { color: var(--warn); } .topbar .public-url .d--warn { background: var(--warn); box-shadow: 0 0 6px var(--warn); } .topbar .public-url .d--err { background: var(--err); box-shadow: 0 0 6px var(--err); } @@ -1149,7 +1191,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } /* ---- forms ---- */ .mono-input { font-family: var(--mono); font-size: 13px; } -.label-hint { color: var(--ink-mute); font-weight: 400; } +/* A11Y · was --ink-mute */ +.label-hint { color: var(--ink-soft); font-weight: 400; } .static-value { font-size: 13px; color: var(--ink-soft); background: var(--paper-2); border: 1px solid var(--line); border-radius: var(--r-sm); padding: 10px 12px; @@ -1158,7 +1201,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .form-card--narrow { max-width: 620px; } .form-saved { margin-right: auto; color: var(--ok); font-size: 13px; font-weight: 600; } .inline-form { display: inline-flex; align-items: center; gap: 8px; margin: 0; } -.link-button { color: var(--accent); font-weight: 600; cursor: pointer; } +.link-button { color: var(--accent-2); font-weight: 600; cursor: pointer; } .link-button:hover { text-decoration: underline; } .checkbox { display: flex; gap: 9px; align-items: flex-start; font-size: 13.5px; margin: 12px 0 4px; cursor: pointer; } .checkbox input { margin-top: 2px; flex: none; } @@ -1253,7 +1296,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .log-item__warnings summary { cursor: pointer; font-weight: 600; } .log-item__warnings ul { margin: 7px 0 0; padding-left: 18px; } .log-item__warnings li + li { margin-top: 4px; } -.log-item .time small { display: block; color: var(--ink-mute); font-size: 11px; } +/* A11Y · was --ink-mute: the date is information */ +.log-item .time small { display: block; color: var(--ink-soft); font-size: 11px; } .activity-more { margin: 16px auto; display: block; } /* ---- settings rows ---- */ @@ -1344,7 +1388,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .subscribe__app:hover { border-color: var(--line-2); color: var(--ink); } .chip.is-active, .subscribe__app.is-active { - background: var(--accent); border-color: var(--accent); color: #fff; + background: var(--accent-2); border-color: var(--accent-2); color: #fff; } .subscribe__body { min-height: 96px; } .subscribe__pane { display: flex; flex-direction: column; gap: 12px; align-items: flex-start; } @@ -1359,10 +1403,11 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .subscribe__hint p { margin: 0 0 6px; } .subscribe__open { display: inline-block; font-weight: 600; font-size: 12.5px; - color: var(--accent); text-decoration: none; + color: var(--accent-2); text-decoration: none; } .subscribe__open:hover { text-decoration: underline; } -.subscribe__aside { color: var(--ink-mute); font-size: 11.5px; } +/* A11Y · was --ink-mute */ +.subscribe__aside { color: var(--ink-soft); font-size: 11.5px; } @media (max-width: 820px) { .subscribe .qr { width: 220px; height: 220px; } @@ -1416,7 +1461,8 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } color: var(--ink-soft); margin-top: 6px; } -.stat-card__h { font-size: 11.5px; color: var(--ink-mute); margin-top: 6px; line-height: 1.45; } +/* A11Y · was --ink-mute: this line says what the number counts */ +.stat-card__h { font-size: 11.5px; color: var(--ink-soft); margin-top: 6px; line-height: 1.45; } .stat-card--bad { border-color: var(--err); background: var(--err-soft); } .stat-card--bad .stat-card__n { color: var(--err); } @@ -1445,7 +1491,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } "why hasn't my podcast app picked up the new episode?", so it is worth the space. */ .reach-stat__when { font-size: 11px; - color: var(--ink-mute); + color: var(--ink-soft); /* A11Y · was --ink-mute */ margin-top: 3px; white-space: nowrap; } @@ -1534,8 +1580,20 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } width: auto; } - /* The header labels the columns of a grid that no longer exists. */ - .ep-table--pinned thead { display: none; } + /* The header labels the columns of a grid that no longer exists — visually. It is + kept for a screen reader, which still has a table to read and needs the column + names for it; `display: none` took them away from it too. */ + .ep-table--pinned thead, + .ep-table--stack thead { + position: absolute; + width: 1px; height: 1px; + padding: 0; margin: -1px; + overflow: hidden; + clip: rect(0 0 0 0); + clip-path: inset(50%); + white-space: nowrap; + border: 0; + } .ep-table--pinned tr { position: relative; @@ -1608,6 +1666,49 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } } +/* ═══════════════════════════════════════════════════════════════════════════ + 14b ANY OTHER TABLE ON A PHONE + The access log and the two statistics tables: six columns that scrolled + sideways with one row filling the screen. The same treatment as §14, made + general: each row becomes a block, the first cell (the title) runs full width, + and every other cell writes its column name in front of its value, taken from + a `data-label` the template puts on it. The stays for screen readers. + ═══════════════════════════════════════════════════════════════════════════ */ + +@media (max-width: 640px) { + /* Beats the 620px floor §11 puts on every non-pinned table in a scroller. */ + .table-scroll .ep-table.ep-table--stack { min-width: 0; } + .ep-table--stack, + .ep-table--stack tbody, + .ep-table--stack tr, + .ep-table--stack td { display: block; width: auto; } + + .ep-table--stack tr { padding: 12px 0; border-bottom: 1px solid var(--line); } + .ep-table--stack tbody tr:last-child { border-bottom: none; } + .ep-table--stack tr:hover td { background: transparent; } + .ep-table--stack tr.is-missing { background: var(--warn-soft); padding-left: 10px; border-radius: var(--r-sm); } + + .ep-table--stack td { + display: flex; align-items: baseline; gap: 10px; + padding: 3px 0; border: none; + font-size: 13px; + } + .ep-table--stack td[data-label]::before { + content: attr(data-label); + flex: 0 0 82px; + font-family: var(--mono); font-size: 10px; font-weight: 600; + letter-spacing: .06em; text-transform: uppercase; + color: var(--ink-soft); + } + .ep-table--stack td.ep-table__lead { display: block; padding-bottom: 6px; } + .ep-table--stack .ep-title small { white-space: normal; word-break: break-word; } + .ep-table--stack .log-range, .ep-table--stack .log-error { margin-left: 92px; } + + .ep-table--stack tr.log-more-row { border-bottom: none; } + .ep-table--stack tr.log-more-row td { display: block; padding-top: 6px; } +} + + /* ═══════════════════════════════════════════════════════════════════════════ 15 CHARTS Every plot here is plain HTML elements carrying an inline `height:%` or @@ -1779,7 +1880,7 @@ dialog.modal[open]::backdrop { animation: sp-fade-in .16s ease-out both; } .stat-card__d--good { color: var(--ok); } .stat-card__d--bad { color: var(--err); } .stat-card__d--flat { color: var(--ink-soft); font-weight: 400; } -.stat-card__d--none { color: var(--ink-mute); font-weight: 400; } +.stat-card__d--none { color: var(--ink-soft); font-weight: 400; } /* A11Y · was --ink-mute */ @media (max-width: 640px) { .chart__plot, @@ -2233,7 +2334,7 @@ a.cut-pill:hover { text-decoration: underline; } border: 1px solid var(--line-2); color: var(--ink); background: var(--card); } .stretch__play:hover { background: var(--paper-2); } -.stretch__play.is-playing { background: var(--accent); border-color: var(--accent); color: #fff; } +.stretch__play.is-playing { background: var(--accent-2); border-color: var(--accent-2); color: #fff; } .cuts-timeline__more { margin-top: 12px; } .cuts-settings > summary { cursor: pointer; margin-bottom: 0; } .cuts-settings[open] > summary { margin-bottom: 14px; } @@ -2267,3 +2368,19 @@ a.cut-pill:hover { text-decoration: underline; } .ep-cuts__players { grid-template-columns: 1fr; } .rule-teach select, .tx__teach-row select, .teach-range__row select { flex: 1 1 100%; } } + + +/* ═══════════════════════════════════════════════════════════════════════════ + 18 TOUCH TARGETS FOR THE COMPONENTS ABOVE + Last on purpose: these override sizes set by the component rules earlier in + the file, and at equal specificity the later rule wins. 44px is the size a + thumb can be sure of; the look of each control is unchanged apart from room. + ═══════════════════════════════════════════════════════════════════════════ */ + +@media (pointer: coarse) { + .sidebar .me-signout { width: 44px; height: 44px; } + .chip, .subscribe__app { min-height: 44px; display: inline-flex; align-items: center; padding: 8px 14px; } + .stretch__play { width: 44px; height: 44px; font-size: 13px; } + /* The bar keeps its 14px; the wrapper around it is what the thumb lands on. */ + .cutbar__hit { padding: 15px 0; margin: -9px 0; } +} diff --git a/src/web/public/js/app.js b/src/web/public/js/app.js index 3d86b71..adcb208 100644 --- a/src/web/public/js/app.js +++ b/src/web/public/js/app.js @@ -26,6 +26,9 @@ document.addEventListener('htmx:responseError', function (event) { var xhr = event.detail.xhr; + // A session that has run out answers 401 with HX-Redirect to the sign-in page. + // htmx follows it; saying "something went wrong" first would be untrue. + if (xhr && xhr.getResponseHeader && xhr.getResponseHeader('HX-Redirect')) return; var message = 'Something went wrong.'; try { var parsed = JSON.parse(xhr.responseText); @@ -40,14 +43,209 @@ toast(message, 'err'); }); + /* + * No response at all: offline, a tunnel that dropped, a request an extension + * blocked. htmx raises this instead of responseError, and until it was handled + * these failed in silence — the button un-pressed itself and nothing said why. + */ + document.addEventListener('htmx:sendError', function () { + toast('SelfPod could not be reached. Check your connection, or that the container is still running, and try again.', 'err'); + }); + + /* ------------------------------------------- background refreshes & focus */ + + /** + * Whether a request was started by the page rather than by a person: a server-sent + * event, a `load` trigger, or script. Those are the refreshes that may not throw + * away what someone is in the middle of typing. + */ + function isBackgroundRequest(detail) { + var config = detail && detail.requestConfig; + var trigger = config && config.triggeringEvent; + if (!trigger || !trigger.type) return true; + return String(trigger.type).indexOf('sse:') === 0 || trigger.type === 'load'; + } + + /** A field someone has focused, or has changed and not yet submitted. */ + function fieldInUse(field) { + if (field === document.activeElement) return true; + if (field.type === 'checkbox' || field.type === 'radio') return field.checked !== field.defaultChecked; + if (field.tagName === 'SELECT') { + // A select with no `selected` attribute shows its first option, and that is + // its default too — comparing each option's selected flag with defaultSelected + // would call every such select dirty from the moment it was rendered. + var defaultIndex = -1; + for (var i = 0; i < field.options.length; i += 1) { + if (field.multiple && field.options[i].selected !== field.options[i].defaultSelected) return true; + if (defaultIndex === -1 && field.options[i].defaultSelected) defaultIndex = i; + } + if (field.multiple) return false; + if (defaultIndex === -1 && field.options.length) defaultIndex = 0; + return field.selectedIndex !== defaultIndex; + } + if (field.type === 'hidden' || field.type === 'submit' || field.type === 'button') return false; + return field.value !== field.defaultValue; + } + + function beingEdited(root) { + if (!root || !root.querySelectorAll) return false; + var fields = root.querySelectorAll('input, select, textarea'); + for (var i = 0; i < fields.length; i += 1) { + if (fieldInUse(fields[i])) return true; + } + return false; + } + + /* + * A refresh the page asked for itself is held back while a field inside the + * region it would replace is in use, and taken again once it is not. The Adverts + * panel and the episode's cuts card re-read themselves whenever a pass finishes — + * scheduled passes included — and used to wipe a half-typed boundary and close the + * settings fold under the person using them. + */ + document.addEventListener('htmx:beforeSwap', function (event) { + if (!isBackgroundRequest(event.detail)) return; + var target = event.detail.target; + if (!target || !beingEdited(target)) return; + event.detail.shouldSwap = false; + target.setAttribute('data-refresh-pending', '1'); + }); + + function takePendingRefreshes() { + var pending = document.querySelectorAll('[data-refresh-pending]'); + Array.prototype.forEach.call(pending, function (el) { + if (beingEdited(el) || !window.htmx) return; + el.removeAttribute('data-refresh-pending'); + var url = el.getAttribute('hx-get'); + if (!url) return; + window.htmx.ajax('GET', url, { source: el, target: el, swap: el.getAttribute('hx-swap') || 'innerHTML' }); + }); + } + + document.addEventListener('focusout', function () { + // After the browser has moved focus, so the next field in the same region counts. + setTimeout(takePendingRefreshes, 0); + }); + + /* + * A decision posts and swaps the panel; the server also announces the change over + * SSE, which made the panel fetch itself a second time for the same state. While a + * person's own request is in flight to a target, the stream's refresh of that + * target is dropped — the response on its way is at least as fresh. + */ + var userRequestsInFlight = {}; + + document.addEventListener('htmx:beforeRequest', function (event) { + var target = event.detail.target; + var key = target && target.id; + if (isBackgroundRequest(event.detail)) { + if (key && userRequestsInFlight[key]) event.preventDefault(); + return; + } + if (key) userRequestsInFlight[key] = (userRequestsInFlight[key] || 0) + 1; + }); + + document.addEventListener('htmx:afterRequest', function (event) { + if (isBackgroundRequest(event.detail)) return; + var target = event.detail.target; + var key = target && target.id; + if (key && userRequestsInFlight[key]) userRequestsInFlight[key] -= 1; + }); + + /* + * A
someone opened or closed stays that way across a swap of the region + * it sits in — the server renders it in its default state every time. + */ + var detailsState = {}; + + function detailsKey(details) { + return details.id || details.className || null; + } + + document.addEventListener('toggle', function (event) { + var details = event.target; + if (!details || details.tagName !== 'DETAILS') return; + var key = detailsKey(details); + if (key) detailsState[key] = details.open; + }, true); + + /** + * The element a swap left in the document. After an outerHTML swap htmx still + * reports the element it replaced, which is out of the document by then; the one + * that took its place carries the same id. + */ + function swappedTarget(detail) { + var target = detail && detail.target; + if (target && target.id && !document.body.contains(target)) return document.getElementById(target.id); + return target; + } + + document.addEventListener('htmx:afterSwap', function (event) { + var target = swappedTarget(event.detail); + if (!target || !target.querySelectorAll) return; + Array.prototype.forEach.call(target.querySelectorAll('details'), function (details) { + var key = detailsKey(details); + if (key && Object.prototype.hasOwnProperty.call(detailsState, key)) details.open = detailsState[key]; + }); + }); + + /* + * Keyboard focus survives a swap. htmx replaces the element that had it, and the + * browser then puts focus on : after saving a setting, sorting the log or + * closing a modal, a keyboard user was back at the top of the page. The control's + * id is remembered before the request and looked up again after the settle; when + * it is gone, the first control in what was swapped in takes its place. + */ + var focusBeforeRequest = null; + + document.addEventListener('htmx:beforeRequest', function (event) { + if (isBackgroundRequest(event.detail)) return; + var active = document.activeElement; + var target = event.detail.target; + if (!active || active === document.body) { + focusBeforeRequest = null; + return; + } + focusBeforeRequest = { + id: active.id || null, + inTarget: Boolean(target && target.contains && target.contains(active)), + }; + }); + + document.addEventListener('htmx:afterSettle', function (event) { + var remembered = focusBeforeRequest; + if (!remembered || isBackgroundRequest(event.detail)) return; + focusBeforeRequest = null; + var active = document.activeElement; + if (active && active !== document.body) return; // focus survived, or was placed on purpose + var again = remembered.id ? document.getElementById(remembered.id) : null; + if (again && document.body.contains(again)) { + again.focus({ preventScroll: true }); + return; + } + if (!remembered.inTarget) return; + var target = swappedTarget(event.detail); + if (!target || !document.body.contains(target) || !target.querySelector) return; + var first = target.querySelector('[autofocus], button:not([disabled]), input:not([type=hidden]):not([disabled]), select:not([disabled]), textarea:not([disabled]), a[href]'); + if (first) first.focus({ preventScroll: true }); + }); + /* ---------------------------------------------------------------- toasts */ + /** + * A notice stays long enough to be read: six seconds and fifty milliseconds a + * character, which gives the reachability verdicts their twenty. An error stays + * until it is dismissed, and is announced as an alert rather than a status. + */ + var TOAST_BASE_MS = 6000; + var TOAST_PER_CHAR_MS = 50; + function toast(message, level) { var root = document.getElementById('toast-root'); if (!root) return; var el = document.createElement('div'); el.className = 'toast toast--' + (level || 'ok'); - el.setAttribute('role', 'status'); + el.setAttribute('role', level === 'err' ? 'alert' : 'status'); var body = document.createElement('div'); body.className = 'toast__body'; body.textContent = message; @@ -55,6 +253,7 @@ close.type = 'button'; close.className = 'toast__close'; close.setAttribute('aria-label', 'Dismiss'); + close.setAttribute('data-toast-close', ''); close.textContent = '×'; el.appendChild(body); el.appendChild(close); @@ -62,21 +261,46 @@ scheduleToastDismissal(el); } + function dismissToast(el) { + if (!el || !el.parentNode) return; + el.classList.add('toast--leaving'); + setTimeout(function () { + el.remove(); + }, 240); + } + function scheduleToastDismissal(el) { - var timer = setTimeout(function () { - el.classList.add('toast--leaving'); - setTimeout(function () { - el.remove(); - }, 240); - }, 6000); - el.addEventListener('mouseenter', function () { + if (el.classList.contains('toast--err')) return; // stays until dismissed + var remaining = TOAST_BASE_MS + TOAST_PER_CHAR_MS * (el.textContent || '').length; + var timer = null; + var startedAt = 0; + + function start() { + if (timer !== null) return; + startedAt = Date.now(); + timer = setTimeout(function () { + timer = null; + dismissToast(el); + }, remaining); + } + function pause() { + if (timer === null) return; clearTimeout(timer); - }); + timer = null; + // Whatever is left, and at least a moment to finish reading after the pointer leaves. + remaining = Math.max(1500, remaining - (Date.now() - startedAt)); + } + + el.addEventListener('mouseenter', pause); + el.addEventListener('mouseleave', start); + el.addEventListener('focusin', pause); + el.addEventListener('focusout', start); + start(); } document.addEventListener('click', function (event) { var close = event.target.closest('[data-toast-close]'); - if (close) close.closest('.toast').remove(); + if (close) dismissToast(close.closest('.toast')); }); // Toasts raised out-of-band by an htmx response need the same auto-dismiss. @@ -100,11 +324,31 @@ } document.addEventListener('htmx:afterSwap', function (event) { - if (event.detail.target && event.detail.target.id === 'modal-root') { - openModalIn(event.detail.target); + var target = event.detail.target; + if (!target || target.id !== 'modal-root') return; + if (target.querySelector('dialog.modal')) { + openModalIn(target); + } else { + // A successful modal action answers with an empty root: the dialog is gone + // without closeModal() running, so focus is handed back here. + restoreFocusTo(modalOpener); + modalOpener = null; } }); + /* + * The control that opened the modal, so closing it can hand focus back. Only a + * request from outside the modal counts: the form inside posts to the same target. + */ + var modalOpener = null; + + document.addEventListener('htmx:beforeRequest', function (event) { + var target = event.detail.target; + if (!target || target.id !== 'modal-root') return; + var elt = event.detail.elt; + if (elt && !target.contains(elt)) modalOpener = elt; + }); + document.addEventListener('click', function (event) { if (event.target.closest('[data-modal-close]')) { closeModal(); @@ -117,12 +361,31 @@ document.body.addEventListener('selfpod:modal-close', closeModal); + // Escape closes a native dialog on its own; the root still has to be emptied and + // focus returned, the same as for Cancel. + document.addEventListener('close', function (event) { + var dialog = event.target; + if (dialog && dialog.tagName === 'DIALOG' && dialog.closest('#modal-root')) closeModal(); + }, true); + function closeModal() { var root = document.getElementById('modal-root'); if (!root) return; var dialog = root.querySelector('dialog.modal'); - if (dialog && typeof dialog.close === 'function') dialog.close(); + if (dialog && typeof dialog.close === 'function' && dialog.open) dialog.close(); root.innerHTML = ''; + restoreFocusTo(modalOpener); + modalOpener = null; + } + + function restoreFocusTo(opener) { + if (!opener) return; + var active = document.activeElement; + if (active && active !== document.body) return; + // The opener may have been swapped away with the table it sat in; the same + // control, re-rendered, carries the same id. + var again = document.body.contains(opener) ? opener : opener.id ? document.getElementById(opener.id) : null; + if (again && typeof again.focus === 'function') again.focus({ preventScroll: true }); } /* --------------------------------------------------- confirm gate helpers */ @@ -417,9 +680,12 @@ if (!form) return; var from = form.querySelector('[data-range-from]'); var to = form.querySelector('[data-range-to]'); - if (!from || !to || !track.clientWidth) return; - var rect = track.getBoundingClientRect(); - var share = Math.max(0, Math.min(1, (event.clientX - rect.left) / track.clientWidth)); + // The tap lands on a wrapper with room around the bar (a thumb needs it); the + // position is read off the drawn track inside it, so the geometry is the bar's. + var rail = track.querySelector('[data-cutbar-rail]') || track; + if (!from || !to || !rail.clientWidth) return; + var rect = rail.getBoundingClientRect(); + var share = Math.max(0, Math.min(1, (event.clientX - rect.left) / rail.clientWidth)); var ms = share * (Number(track.getAttribute('data-duration-ms')) || 0); // From, then To; a third tap starts a new range. var target = !from.value ? from : !to.value ? to : null; @@ -999,6 +1265,8 @@ row.querySelector('[data-pct]').textContent = 'done'; var message = row.querySelector('[data-message]'); message.hidden = false; + // `.msg` is styled as a problem; `.ok` is what makes this one read as good news. + message.classList.add('ok'); message.textContent = 'Uploaded — scanning now.'; } diff --git a/src/web/routes/events.js b/src/web/routes/events.js index 184526f..933840e 100644 --- a/src/web/routes/events.js +++ b/src/web/routes/events.js @@ -56,33 +56,48 @@ export default async function eventRoutes(fastify, { events, logger, shows, adPi reply.raw.write(`event: ${event}\ndata: ${payload}\n\n`); }; + /* + * The strip is the same partial the rescan button swaps in, rendered here rather + * than assembled by hand. The partial carries the slow poll of /ui/scan-status + * that clears the strip when the stream dies mid-scan; the hand-built copy used + * to leave that out, so the first SSE message replaced a strip that could clear + * itself with one that could not. Rendering is asynchronous, so each strip goes + * out through one queue and a later event can never overtake an earlier one. + */ + let queue = Promise.resolve(); + const sendStrip = (event, scope, label) => { + queue = queue + .then(() => renderStrip(fastify, scope, label)) + .then((html) => send(event, html)) + .catch((err) => logger?.debug({ err }, 'could not render the scan-progress strip for the live stream')); + }; + const sendAfterStrips = (event, data) => { + queue = queue.then(() => send(event, data)).catch(() => {}); + }; + const onScanStarted = (payload) => { const label = payload.scope === 'all' ? 'Scanning your whole library…' : `Scanning ${payload.slug ?? 'show'}…`; - send( - payload.scope === 'all' ? 'scan-progress-all' : `scan-progress-${payload.showId}`, - progressHtml(payload.scope === 'all' ? 'all' : payload.showId, label), - ); + const scope = payload.scope === 'all' ? 'all' : payload.showId; + sendStrip(`scan-progress-${scope}`, scope, label); }; const onScanProgress = (payload) => { if (payload.scope !== 'all') return; - send( - 'scan-progress-all', - progressHtml('all', `Scanning ${payload.title ?? payload.slug} (${payload.index} of ${payload.total})…`), - ); + sendStrip('scan-progress-all', 'all', `Scanning ${payload.title ?? payload.slug} (${payload.index} of ${payload.total})…`); }; const onScanFinished = (payload) => { const scope = payload.scope === 'all' ? 'all' : payload.showId; - // An empty swap clears the strip once the scan is done. - send(`scan-progress-${scope}`, ''); + // An empty swap clears the strip once the scan is done — queued behind any + // strip still rendering, or the clear would arrive before what it clears. + sendAfterStrips(`scan-progress-${scope}`, ''); // These are used as triggers (hx-trigger="sse:scan-finished-…"), where the // payload is irrelevant — only the event name matters. - if (payload.showId) send(`scan-finished-${payload.showId}`, 'done'); - if (payload.scope === 'all') send('scan-finished-all', 'done'); + if (payload.showId) sendAfterStrips(`scan-finished-${payload.showId}`, 'done'); + if (payload.scope === 'all') sendAfterStrips('scan-finished-all', 'done'); }; /* @@ -147,10 +162,24 @@ export default async function eventRoutes(fastify, { events, logger, shows, adPi }); } +/** + * The scan-progress strip for the stream: partials/scan-progress.eta, the one the + * rescan buttons use, so the two cannot drift apart. The hand-written copy below is + * the fallback if rendering fails, and carries the same polling backstop. + */ +export async function renderStrip(fastify, scope, label) { + try { + return await fastify.view('partials/scan-progress.eta', { scope, label }); + } catch { + return progressHtml(scope, label); + } +} + function progressHtml(scope, label) { - return `
${escapeHtml( + )}" hx-trigger="load delay:2500ms" hx-swap="outerHTML">${escapeHtml( label, )}
`; } diff --git a/src/web/routes/fragments.js b/src/web/routes/fragments.js index 87e2bcc..7de45e5 100644 --- a/src/web/routes/fragments.js +++ b/src/web/routes/fragments.js @@ -53,6 +53,46 @@ export default async function fragmentRoutes(fastify, services) { return reply.redirect(path, 303); } + /** + * The htmx answer to "go somewhere else, and say why": the flash is stored for the + * page that loads next, and `HX-Redirect` sends the browser there. Used wherever a + * fragment swap would leave the page describing something that is gone — a show + * that was removed, an episode deleted from the page about it — and wherever the + * only honest result is the whole page re-read. + */ + function redirectWithFlash(request, reply, path, message, level = 'ok') { + if (message) services.setFlash(request, message, level); + reply.header('HX-Redirect', path); + return reply.send(''); + } + + /** + * Sends a fragment with a toast riding along out of band. `viewAsync` rather than + * `view`, because `reply.view` renders *and sends*, and anything appended to its + * return value reaches nobody — which is how confirmations were lost here twice. + */ + async function sendWithToast(reply, html, toast) { + if (!toast) return reply.type('text/html; charset=utf-8').send(html); + const oob = await reply.viewAsync('partials/toast.eta', { + message: toast.message, + level: toast.level ?? 'ok', + helpers: fastify.viewHelpers, + }); + return reply.type('text/html; charset=utf-8').send(`${html}${oob}`); + } + + /** + * Starts a pass over a show without waiting for it. A pass reads every episode and + * may listen for minutes, which is far too long for a request from a phone to hang + * on; the work strip on the page follows it over SSE, and the panel re-reads itself + * when the pass says it changed something. The returned promise is only for tests. + */ + function startPass(showId) { + const run = services.adPipeline.processShow(showId); + run.catch((err) => services.logger?.warn({ err, showId }, 'a pass started from the page failed')); + return run; + } + /* ----------------------------------------------------------- ad segments */ function advertsPath(slug) { @@ -60,13 +100,14 @@ export default async function fragmentRoutes(fastify, services) { } /** The one place the Adverts panel is rendered, so htmx and a reload agree. */ - async function renderSegments(reply, show, extra = {}) { - return reply.view('partials/ad-panel.eta', { + async function renderSegments(reply, show, extra = {}, { toast = null } = {}) { + const html = await reply.viewAsync('partials/ad-panel.eta', { show: presentShow(show), ...(await services.advertsView.panel(show, { owed: services.adPipeline.workOwed(show.id) })), helpers: fastify.viewHelpers, ...extra, }); + return sendWithToast(reply, html, toast); } /** @@ -74,14 +115,15 @@ export default async function fragmentRoutes(fastify, services) { * waiting, and the words underneath it. One target, so a decision made there * re-renders the whole story rather than half of it. */ - async function renderEpisodeAdverts(reply, episode, show, extra = {}) { - return reply.view('partials/episode-adverts.eta', { + async function renderEpisodeAdverts(reply, episode, show, extra = {}, { toast = null } = {}) { + const html = await reply.viewAsync('partials/episode-adverts.eta', { show: presentShow(show), episode: presentEpisode(episode, show), adverts: await services.advertsView.episodeAdverts(episode, show), helpers: fastify.viewHelpers, ...extra, }); + return sendWithToast(reply, html, toast); } /** Just the words, for anything that wants them on their own. */ @@ -185,11 +227,17 @@ export default async function fragmentRoutes(fastify, services) { ? renderSegments(reply, show) : redirectBack(request, reply, advertsPath(show.slug), 'Advert detection is off for this show.', 'err'); } - await services.adPipeline.processShow(show.id); if (!isHtmx(request)) { + // A plain form post has nothing on the page to follow the work with, so it + // waits and says what happened; the browser shows its own loading state. + await services.adPipeline.processShow(show.id); return redirectBack(request, reply, advertsPath(show.slug), 'Checked.'); } - return renderSegments(reply, shows.get(show.id)); + // Started, not awaited: the work strip above the panel follows the pass. + startPass(show.id); + return renderSegments(reply, shows.get(show.id), {}, { + toast: { message: 'Checking this show now. What it finds appears here as it goes.' }, + }); }); scoped.post('/ui/shows/:slug/ad-segments/:segmentId', { preHandler: [fastify.rateLimit(DECIDE_LIMIT)] }, async (request, reply) => { @@ -328,13 +376,17 @@ export default async function fragmentRoutes(fastify, services) { * The reply every cut decision ends with: back where it was made. htmx gets the * panel or the episode card re-rendered; a plain form gets a redirect and a flash. */ - async function afterDecision(request, reply, show, note, { level = 'ok' } = {}) { + async function afterDecision(request, reply, show, note, { level = 'ok', toast = false } = {}) { const back = returnTarget(request, show); if (!isHtmx(request)) { return redirectBack(request, reply, back ? episodePath(show.slug, back.episode.id) : advertsPath(show.slug), note, level); } - if (back) return renderEpisodeAdverts(reply, episodes.get(back.episode.id), shows.get(show.id)); - return renderSegments(reply, shows.get(show.id)); + // `toast: true` says the note is worth saying out loud on the htmx path too — + // for work that was started rather than finished, where the re-rendered panel + // alone would not show what the press achieved. + const extra = toast ? { toast: { message: note, level } } : {}; + if (back) return renderEpisodeAdverts(reply, episodes.get(back.episode.id), shows.get(show.id), {}, extra); + return renderSegments(reply, shows.get(show.id), {}, extra); } function segmentOf(show, segmentId) { @@ -367,9 +419,15 @@ export default async function fragmentRoutes(fastify, services) { rawText: text, language: show.language ? String(show.language).slice(0, 2) : null, }); - // New words to listen for in every episode: a pass, not a cut. - await services.adPipeline.processShow(show.id); - return afterDecision(request, reply, show, `SelfPod now listens for “${text}” in every episode.`); + // New words to listen for in every episode: a pass, not a cut. The page gets the + // new rule at once and the strip follows the pass; a plain form waits for it. + const note = `SelfPod now listens for “${text}” in every episode.`; + if (!isHtmx(request)) { + await services.adPipeline.processShow(show.id); + return afterDecision(request, reply, show, note); + } + startPass(show.id); + return afterDecision(request, reply, show, note, { toast: true }); }); /** "Restore everywhere and stop": the rule behind a cut, undone for the whole show. */ @@ -441,10 +499,15 @@ export default async function fragmentRoutes(fastify, services) { if (error.status && error.status < 500) return fail(error.message); throw error; } - await services.adPipeline.processShow(show.id); - const note = kind === 'jingle' ? 'SelfPod now cuts whatever comes before that jingle, in every episode.' : 'Taught.'; - if (!isHtmx(request)) return redirectBack(request, reply, episodePath(show.slug, episode.id), note); - return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id)); + const jingleNote = 'SelfPod now cuts whatever comes before that jingle, in every episode.'; + if (!isHtmx(request)) { + await services.adPipeline.processShow(show.id); + return redirectBack(request, reply, episodePath(show.slug, episode.id), kind === 'jingle' ? jingleNote : 'Taught.'); + } + startPass(show.id); + return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id), {}, { + toast: { message: kind === 'jingle' ? jingleNote : 'Taught. The cut lands as soon as the pass reaches this episode.' }, + }); }); scoped.get('/ui/episodes/:id/adverts', async (request, reply) => { @@ -482,9 +545,14 @@ export default async function fragmentRoutes(fastify, services) { ...range, status: verdict === 'advert' ? STATUS.APPROVED : STATUS.REJECTED, }); + const span = `${fastify.viewHelpers.formatDuration(Math.round(range.startMs / 1000))}–${fastify.viewHelpers.formatDuration(Math.round(range.endMs / 1000))}`; + // Past tense once the pass has run (the plain form waits for it); the page, + // which only starts the pass, is told what is under way. note = verdict === 'advert' - ? `Removed ${fastify.viewHelpers.formatDuration(Math.round(range.startMs / 1000))}–${fastify.viewHelpers.formatDuration(Math.round(range.endMs / 1000))} from this episode. The same words will be cut from later episodes.` + ? isHtmx(request) + ? `Removing ${span} from this episode. The same words will be cut from later episodes.` + : `Removed ${span} from this episode. The same words will be cut from later episodes.` : 'Kept, and SelfPod will not offer those words again.'; } else if (verdict === 'programme_starts' || verdict === 'programme_ends' || verdict === 'tail_starts') { services.adDetect.addMarker({ @@ -503,9 +571,12 @@ export default async function fragmentRoutes(fastify, services) { } else { return fail('Say what those words are.'); } - await services.adPipeline.processShow(show.id); - if (!isHtmx(request)) return redirectBack(request, reply, episodePath(show.slug, episode.id), note); - return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id)); + if (!isHtmx(request)) { + await services.adPipeline.processShow(show.id); + return redirectBack(request, reply, episodePath(show.slug, episode.id), note); + } + startPass(show.id); + return renderEpisodeAdverts(reply, episodes.get(episode.id), shows.get(show.id), {}, { toast: { message: note } }); }); /* ---------------------------------------------------------- subscription */ @@ -635,7 +706,7 @@ export default async function fragmentRoutes(fastify, services) { message = error.message; level = 'err'; } - return redirectBack(request, reply, subscriptionPath(show.slug), message, level); + return afterSubscriptionAction(request, reply, show, message, level); }); scoped.post('/ui/subscriptions/:id/toggle', async (request, reply) => { @@ -644,26 +715,49 @@ export default async function fragmentRoutes(fastify, services) { const updated = services.subscriptions.update(subscription.id, { enabled: !subscription.enabled, }); - return redirectBack( + return afterSubscriptionAction( request, reply, - subscriptionPath(show.slug), + show, updated.enabled ? 'Following again.' : 'Paused. Nothing new will be downloaded until you resume.', ); }); + /** Asks before the feed is forgotten, like every other action that cannot be undone. */ + scoped.get('/ui/modals/stop-following/:id', async (request, reply) => { + const subscription = services.subscriptions.getOrThrow(request.params.id); + const show = shows.getOrThrow(subscription.show_id); + return reply.view('partials/modal-stop-following.eta', { + show: presentShow(show), + subscription: presentSubscription(subscription, services), + helpers: fastify.viewHelpers, + }); + }); + scoped.post('/ui/subscriptions/:id/delete', async (request, reply) => { const subscription = services.subscriptions.getOrThrow(request.params.id); const show = shows.getOrThrow(subscription.show_id); services.subscriptions.remove(subscription.id); - return redirectBack( + return afterSubscriptionAction( request, reply, - subscriptionPath(show.slug), + show, 'Stopped following that feed. The episodes it already downloaded are untouched.', ); }); + /** + * Every one of these changes the status card, the next-check time and the ledger + * at once, which is the whole page; so the page is re-read, and the message rides + * on the flash either way. The buttons used to swap nothing and follow the 303 + * inside the XHR, which left the page unchanged and the message waiting for a + * reload nobody knew to do. + */ + function afterSubscriptionAction(request, reply, show, message, level = 'ok') { + if (!isHtmx(request)) return redirectBack(request, reply, subscriptionPath(show.slug), message, level); + return redirectWithFlash(request, reply, subscriptionPath(show.slug), message, level); + } + scoped.get('/ui/subscriptions/:id/items', async (request, reply) => { const subscription = services.subscriptions.getOrThrow(request.params.id); const show = shows.getOrThrow(subscription.show_id); @@ -1100,6 +1194,17 @@ export default async function fragmentRoutes(fastify, services) { } }); + /** + * Where the delete-episode modal was opened from. On the show page the episode + * table is re-rendered in place; on the episode's own page there is no table, and + * the page is about something that is now gone, so the answer is the show page + * with the message on the flash. The modal carries this as a hidden field, since + * SelfPod sends `Referrer-Policy: no-referrer` and the referer cannot say. + */ + function cameFromEpisodePage(request, episode) { + return String(request.body?.returnTo ?? '') === `episode:${episode.id}`; + } + scoped.post('/ui/episodes/:id/remove', async (request, reply) => { const episode = episodes.get(request.params.id); if (!episode) throw notFound('That episode does not exist.', 'episode_not_found'); @@ -1107,9 +1212,9 @@ export default async function fragmentRoutes(fastify, services) { episodes.removeFromFeed(episode.id); const message = 'Removed from the feed. The audio file is untouched, and rescans will leave it out.'; - if (!isHtmx(request)) { - return redirectBack(request, reply, `/shows/${encodeURIComponent(show.slug)}`, message); - } + const showPage = `/shows/${encodeURIComponent(show.slug)}`; + if (!isHtmx(request)) return redirectBack(request, reply, showPage, message); + if (cameFromEpisodePage(request, episode)) return redirectWithFlash(request, reply, showPage, message); return renderEpisodeTableWithToast(reply, show, message); }); @@ -1142,9 +1247,9 @@ export default async function fragmentRoutes(fastify, services) { const result = await episodes.deleteWithFile(episode.id); const message = `Deleted ${result.filename} from disk.`; - if (!isHtmx(request)) { - return redirectBack(request, reply, `/shows/${encodeURIComponent(show.slug)}`, message, 'warn'); - } + const showPage = `/shows/${encodeURIComponent(show.slug)}`; + if (!isHtmx(request)) return redirectBack(request, reply, showPage, message, 'warn'); + if (cameFromEpisodePage(request, episode)) return redirectWithFlash(request, reply, showPage, message, 'warn'); return renderEpisodeTableWithToast(reply, show, message, 'warn'); }); @@ -1497,9 +1602,9 @@ export default async function fragmentRoutes(fastify, services) { }, }; - function renderSettingRow(reply, key, { editing = false, errors = null } = {}) { + async function renderSettingRow(reply, key, { editing = false, errors = null } = {}, { toast = null } = {}) { const row = SETTING_ROWS[key]; - return reply.view('partials/settings-row.eta', { + const html = await reply.viewAsync('partials/settings-row.eta', { key, title: row.title, description: row.description, @@ -1515,6 +1620,7 @@ export default async function fragmentRoutes(fastify, services) { errors, helpers: fastify.viewHelpers, }); + return sendWithToast(reply, html, toast); } scoped.get('/ui/settings/:key', async (request, reply) => { @@ -1544,7 +1650,10 @@ export default async function fragmentRoutes(fastify, services) { } if (!isHtmx(request)) return redirectBack(request, reply, '/settings', `${row.title} updated.`); - return renderSettingRow(reply, key, { editing: false }); + // The row re-renders as its display view; the toast is what says it was saved, + // because a row that quietly stops being a form looks much like one that was + // cancelled. + return renderSettingRow(reply, key, { editing: false }, { toast: { message: `${row.title} updated.` } }); }); scoped.post('/ui/settings/watcher', async (request, reply) => { @@ -1552,16 +1661,12 @@ export default async function fragmentRoutes(fastify, services) { settings.update({ [SETTING_KEYS.WATCHER_ENABLED]: enabled ? '1' : '0' }); await watcher?.restart(); - if (!isHtmx(request)) { - return redirectBack( - request, - reply, - '/settings', - enabled ? 'Live file detection switched on.' : 'Live file detection switched off.', - ); - } + const message = enabled ? 'Live file detection switched on.' : 'Live file detection switched off.'; + if (!isHtmx(request)) return redirectBack(request, reply, '/settings', message); // Re-render the whole settings page section by asking the browser to reload - // it: the watcher's mode label depends on state this fragment doesn't own. + // it: the watcher's mode label depends on state this fragment doesn't own. The + // flash survives the reload, so the switch is seen to have done something. + services.setFlash(request, message); reply.header('HX-Refresh', 'true'); return reply.send(''); }); @@ -1571,18 +1676,13 @@ export default async function fragmentRoutes(fastify, services) { request.body?.subscriptionsEnabled === '1' || request.body?.subscriptionsEnabled === 'on'; settings.update({ [SETTING_KEYS.SUBSCRIPTIONS_ENABLED]: enabled ? '1' : '0' }); - if (!isHtmx(request)) { - return redirectBack( - request, - reply, - '/settings', - enabled - ? 'SelfPod can now follow podcast feeds. Set the rules on a show\'s own page.' - : 'Feed following switched off. SelfPod will not fetch from the internet.', - ); - } + const message = enabled + ? 'SelfPod can now follow podcast feeds. Set the rules on a show\'s own page.' + : 'Feed following switched off. SelfPod will not fetch from the internet.'; + if (!isHtmx(request)) return redirectBack(request, reply, '/settings', message); // Whole-page refresh: every show page's subscription section reads this, and // the banner it controls is not part of this fragment. + services.setFlash(request, message); reply.header('HX-Refresh', 'true'); return reply.send(''); }); @@ -1611,6 +1711,7 @@ export default async function fragmentRoutes(fastify, services) { if (!isHtmx(request)) return redirectBack(request, reply, '/settings', 'Password changed.'); return reply.view('partials/modal-closed.eta', { toast: { message: 'Password changed.', level: 'ok' }, + helpers: fastify.viewHelpers, }); }); @@ -1647,6 +1748,9 @@ export default async function fragmentRoutes(fastify, services) { return reply.view('partials/modal-delete-episode.eta', { episode: presentEpisode(episode, show), show: presentShow(show), + // `?from=episode`: opened on the episode's own page, which the action then + // has to leave (see cameFromEpisodePage). + returnTo: request.query?.from === 'episode' ? `episode:${episode.id}` : null, helpers: fastify.viewHelpers, }); }); diff --git a/src/web/routes/pages.js b/src/web/routes/pages.js index 13c5a23..1f12060 100644 --- a/src/web/routes/pages.js +++ b/src/web/routes/pages.js @@ -238,6 +238,7 @@ export default async function pageRoutes(fastify, services) { 'pages/dashboard.eta', shell(request, { title: 'Dashboard', + active: 'dashboard', crumbs: [{ label: 'Dashboard' }], shows: all.filter((s) => s.status === SHOW_STATUS.ACTIVE), pausedShows: all.filter((s) => s.status === SHOW_STATUS.FOLDER_MISSING), @@ -272,8 +273,8 @@ export default async function pageRoutes(fastify, services) { shell(request, { title: 'New show', crumbs: [{ label: 'Dashboard', href: '/' }, { label: 'New show' }], - title_: request.body?.title, - slug: request.body?.slug, + // Echoed back as the field values, so a refusal never discards what was typed. + form: { title: request.body?.title, slug: request.body?.slug }, errors: err.fields ?? { title: err.message }, }), APP_LAYOUT, @@ -980,9 +981,17 @@ export default async function pageRoutes(fastify, services) { }); } +/* + * Topbar actions. A button that makes a request is held and shows it is working until + * the answer comes (`hx-disabled-elt`, and htmx's own `htmx-request` class, which the + * stylesheet draws as a spinner), and a second press while one is in flight is dropped + * rather than queued as a second scan. + */ +const BUSY = 'hx-disabled-elt="this" hx-sync="this:drop"'; + function dashboardActions() { return ` - @@ -78,7 +78,7 @@
-
This episode's reach
+

This episode's reach

<% if (reach.lastAt) { %> Last fetched <%= it.helpers.relativeTime(reach.lastAt) %>. diff --git a/src/web/views/pages/login.eta b/src/web/views/pages/login.eta index c454b1c..a8c57ec 100644 --- a/src/web/views/pages/login.eta +++ b/src/web/views/pages/login.eta @@ -22,7 +22,7 @@

<% if (it.error) { %> -