diff --git a/crates/api/src/web/enrollment_tests.rs b/crates/api/src/web/enrollment_tests.rs index afd1799b..ec9a194b 100644 --- a/crates/api/src/web/enrollment_tests.rs +++ b/crates/api/src/web/enrollment_tests.rs @@ -6837,16 +6837,13 @@ async fn owner_routes_reject_a_discord_administrator() { "/api/service-upgrade", "/api/preview", ]; - let registered: std::collections::BTreeSet<_> = - [include_str!("mod.rs"), include_str!("recovery.rs")] - .into_iter() - .flat_map(|source| source.split(".route(").skip(1)) - .filter_map(|route| route.split('"').nth(1)) - .filter(|path| { - owner_prefixes.iter().any(|prefix| path.starts_with(prefix)) - && *path != "/api/service-upgrade/recovery" - }) - .collect(); + let registered: std::collections::BTreeSet<_> = registered_routes(&f.app) + .into_iter() + .filter(|path| { + owner_prefixes.iter().any(|prefix| path.starts_with(prefix)) + && *path != "/api/service-upgrade/recovery" + }) + .collect(); let tested: std::collections::BTreeSet<_> = routes .into_iter() .map(|(_, route, _)| route) diff --git a/crates/api/src/web/mod.rs b/crates/api/src/web/mod.rs index 08874976..33274ddc 100644 --- a/crates/api/src/web/mod.rs +++ b/crates/api/src/web/mod.rs @@ -2061,49 +2061,80 @@ pub fn router(app: Arc) -> Router { router_with_store(app, store) } -fn router_with_store(app: Arc, session_store: MemoryStore) -> Router { - // Secure cookies when the public URL is HTTPS (deploy behind TLS). - let secure = app - .cfg - .web - .base_url - .to_ascii_lowercase() - .starts_with("https://"); - // Parse CORS origins first. SameSite=None must track *successfully parsed* - // origins — a typo'd list must not enable cross-site cookies without CORS. - use axum::http::HeaderValue; - let cors_origins: Vec = app - .cfg - .web - .cors_origins - .iter() - .filter_map(|o| { - let origin = o.trim(); - if origin == "*" { - tracing::warn!("ignoring wildcard web.cors_origins entry; credentialed CORS requires explicit origins"); - None - } else { - HeaderValue::from_str(origin).ok() - } - }) - .collect(); - if !app.cfg.web.cors_origins.is_empty() && cors_origins.is_empty() { - tracing::warn!( - "web.cors_origins is set but none parsed as valid Origin headers — \ - CORS disabled; session cookies stay SameSite=Lax" - ); +/// Thin `Router` wrapper that records every registered path under `#[cfg(test)]` +/// so route-inventory tests inspect the live builder instead of parsing source. +pub(crate) struct RouteBuilder { + router: Router, + #[cfg(test)] + paths: Vec<&'static str>, +} + +impl RouteBuilder { + pub(crate) fn new() -> Self { + Self { + router: Router::new(), + #[cfg(test)] + paths: Vec::new(), + } + } + + pub(crate) fn route( + mut self, + path: &'static str, + method_router: axum::routing::MethodRouter, + ) -> Self { + #[cfg(test)] + self.paths.push(path); + self.router = self.router.route(path, method_router); + self } - let cross_origin = !cors_origins.is_empty(); - let same_site = session_same_site(cross_origin, secure); - let session_layer = SessionManagerLayer::new(resources::CountedStore(session_store)) - .with_name(SESSION_COOKIE_NAME) - .with_secure(secure) - .with_same_site(same_site) - .with_expiry(Expiry::OnInactivity(CookieDuration::seconds( - SESSION_INACTIVITY_SECS, - ))); - let sessioned = Router::new(); + pub(crate) fn merge(mut self, other: Self) -> Self { + #[cfg(test)] + self.paths.extend(other.paths); + self.router = self.router.merge(other.router); + self + } + + pub(crate) fn with_state(self, state: S) -> RouteBuilder { + RouteBuilder { + router: self.router.with_state(state), + #[cfg(test)] + paths: self.paths, + } + } + + pub(crate) fn into_router(self) -> Router { + self.router + } + + #[cfg(test)] + pub(crate) fn into_paths(self) -> Vec<&'static str> { + self.paths + } +} + +#[cfg(test)] +fn registered_routes(app: &Arc) -> Vec<&'static str> { + let mut paths = outer_route_builder().into_paths(); + paths.extend(sessioned_route_builder(app).into_paths()); + paths +} + +fn outer_route_builder() -> RouteBuilder> { + RouteBuilder::new() + .route("/health", get(health)) + .route("/health/", get(health)) + .route("/ready", get(ready)) + .route("/ready/", get(ready)) + .route("/privacy", get(legal::privacy)) + .route("/terms", get(legal::terms)) + .route("/api/legal", get(legal::details)) + .route("/api/legal/style.css", get(legal::stylesheet)) +} + +fn sessioned_route_builder(app: &Arc) -> RouteBuilder> { + let sessioned = RouteBuilder::new(); #[cfg(feature = "embed-ui")] let sessioned = sessioned .route("/", get(index)) @@ -2113,7 +2144,7 @@ fn router_with_store(app: Arc, session_store: MemoryStore) -> Router { .route("/administration.js", get(administration_js)) .route("/webui-runtime.js", get(webui_runtime)) .route("/style.css", get(style_css)); - let sessioned = sessioned + sessioned .route("/login", get(login)) .route("/logout", axum::routing::post(logout)) .route("/oauth/callback", get(callback)) @@ -2433,16 +2464,65 @@ fn router_with_store(app: Arc, session_store: MemoryStore) -> Router { "/api/owner/deletions/{request_id}/retry", axum::routing::post(deletions::owner_retry), ) - .merge(recovery::routes(Arc::new(recovery::RecoveryState { - cfg: Arc::clone(&app.cfg), - oauth: Arc::clone(&app.oauth), - control: recovery_control(&app), - apply_enabled: std::env::var("JMODGUARD_UPDATE_APPLY_ENABLED").as_deref() == Ok("1"), - now: recovery::current_timestamp, - api: Some(Arc::clone(&app)), - writer: None, - launcher: recovery::launcher_link(&app.cfg), - }))) + .merge(recovery::routes_builder(Arc::new( + recovery::RecoveryState { + cfg: Arc::clone(&app.cfg), + oauth: Arc::clone(&app.oauth), + control: recovery_control(app), + apply_enabled: std::env::var("JMODGUARD_UPDATE_APPLY_ENABLED").as_deref() + == Ok("1"), + now: recovery::current_timestamp, + api: Some(Arc::clone(app)), + writer: None, + launcher: recovery::launcher_link(&app.cfg), + }, + ))) +} + +fn router_with_store(app: Arc, session_store: MemoryStore) -> Router { + // Secure cookies when the public URL is HTTPS (deploy behind TLS). + let secure = app + .cfg + .web + .base_url + .to_ascii_lowercase() + .starts_with("https://"); + // Parse CORS origins first. SameSite=None must track *successfully parsed* + // origins — a typo'd list must not enable cross-site cookies without CORS. + use axum::http::HeaderValue; + let cors_origins: Vec = app + .cfg + .web + .cors_origins + .iter() + .filter_map(|o| { + let origin = o.trim(); + if origin == "*" { + tracing::warn!("ignoring wildcard web.cors_origins entry; credentialed CORS requires explicit origins"); + None + } else { + HeaderValue::from_str(origin).ok() + } + }) + .collect(); + if !app.cfg.web.cors_origins.is_empty() && cors_origins.is_empty() { + tracing::warn!( + "web.cors_origins is set but none parsed as valid Origin headers — \ + CORS disabled; session cookies stay SameSite=Lax" + ); + } + let cross_origin = !cors_origins.is_empty(); + let same_site = session_same_site(cross_origin, secure); + let session_layer = SessionManagerLayer::new(resources::CountedStore(session_store)) + .with_name(SESSION_COOKIE_NAME) + .with_secure(secure) + .with_same_site(same_site) + .with_expiry(Expiry::OnInactivity(CookieDuration::seconds( + SESSION_INACTIVITY_SECS, + ))); + + let sessioned = sessioned_route_builder(&app) + .into_router() .layer(axum::middleware::from_fn(save::middleware)) .layer(session_layer) .layer(axum::middleware::from_fn_with_state( @@ -2480,20 +2560,9 @@ fn router_with_store(app: Arc, session_store: MemoryStore) -> Router { sessioned }; - uncacheable_response_headers( - Router::new() - .route("/health", get(health)) - .route("/health/", get(health)) - .route("/ready", get(ready)) - .route("/ready/", get(ready)) - .route("/privacy", get(legal::privacy)) - .route("/terms", get(legal::terms)) - .route("/api/legal", get(legal::details)) - .route("/api/legal/style.css", get(legal::stylesheet)) - .merge(sessioned), - ) - .layer(axum::middleware::from_fn(resources::count_request)) - .with_state(app.clone()) + uncacheable_response_headers(outer_route_builder().into_router().merge(sessioned)) + .layer(axum::middleware::from_fn(resources::count_request)) + .with_state(app.clone()) } /// Membership admission failures contain no database diagnostics or tenant data. diff --git a/crates/api/src/web/recovery.rs b/crates/api/src/web/recovery.rs index d7b22425..8a443282 100644 --- a/crates/api/src/web/recovery.rs +++ b/crates/api/src/web/recovery.rs @@ -151,8 +151,10 @@ async fn mutation( Ok(()) } -pub fn routes(state: Arc) -> Router { - Router::new() +pub(crate) fn routes_builder( + state: Arc, +) -> super::RouteBuilder { + super::RouteBuilder::new() .route( "/api/service-upgrade/recovery", get(|| async { Html(include_str!("recovery.html")) }), @@ -163,6 +165,10 @@ pub fn routes(state: Arc) -> Ro .with_state(state) } +pub fn routes(state: Arc) -> Router { + routes_builder(state).into_router() +} + async fn status(State(state): State>, session: Session) -> Reply { owner(&state, &session).await?; let control = &state.control; diff --git a/crates/bot/src/automod.rs b/crates/bot/src/automod.rs index 31da7a8b..2fb48716 100644 --- a/crates/bot/src/automod.rs +++ b/crates/bot/src/automod.rs @@ -2362,6 +2362,7 @@ async fn execute_live<'a>( target.id, rule, &discord_reason, + pending_ban.token(), ), ) .await, diff --git a/crates/bot/src/commands/behaviors.rs b/crates/bot/src/commands/behaviors.rs index 937d8075..b6141029 100644 --- a/crates/bot/src/commands/behaviors.rs +++ b/crates/bot/src/commands/behaviors.rs @@ -227,11 +227,6 @@ pub(super) async fn run_with_userinfo_identity( let target = resolve_target(env, target).await?; let reason = jmodguard::ban_reason::without_tag(&reason).to_owned(); let target_user = user_lookup(env, target).await?; - let member = env - .ctx - .cache - .guild(env.guild_id) - .and_then(|g| g.members.get(&target).cloned()); refuse_bot_target(env, target)?; // Refuse before taking the shared ban slot, so a refused command // never blocks an authorized ban of the same member meanwhile. @@ -387,31 +382,26 @@ pub(super) async fn run_with_userinfo_identity( target.get(), Some(&operation_id), ); - let raced = if let Some(m) = member { - crate::discord::race_discord_call( - &env.app.activation, - m.ban_with_reason(&env.ctx.http, *delete_days, &discord_reason), - ) - .await - } else { - crate::discord::race_discord_call( - &env.app.activation, - env.guild_id.ban_with_reason( - &env.ctx.http, - target, - *delete_days, - &discord_reason, - ), - ) - .await - }; + let raced = crate::discord::race_discord_call( + &env.app.activation, + crate::discord::ban_with_reason( + &env.ctx.http, + env.guild_id, + target, + *delete_days, + &discord_reason, + pending_ban.token(), + ), + ) + .await; let crate::discord::DiscordCall::Finished(discord) = raced else { pending_ban .finish(env.app, crate::db::guild_data::CaseOutcome::Uncertain) .await; return Err(anyhow!("ban outcome is uncertain; verify it in Discord")); }; - let outcome = crate::cases::classify_discord(discord.as_ref().err()); + let outcome = + crate::cases::classify_discord(discord.as_ref().err().map(Box::as_ref)); if matches!(outcome, crate::db::guild_data::CaseOutcome::Failed) { env.app.release_gateway_case_suppression(suppression); } diff --git a/crates/bot/src/commands/plans.rs b/crates/bot/src/commands/plans.rs index 6676f84e..0c830a8b 100644 --- a/crates/bot/src/commands/plans.rs +++ b/crates/bot/src/commands/plans.rs @@ -555,11 +555,13 @@ async fn run_step( ); let result = match crate::discord::race_discord_call( &env.app.activation, - env.guild_id.ban_with_reason( + crate::discord::ban_with_reason( &env.ctx.http, + env.guild_id, target, *delete_days, &discord_reason, + pending_ban.token(), ), ) .await @@ -572,29 +574,18 @@ async fn run_step( } crate::discord::DiscordCall::Finished(result) => result, }; - if matches!( - crate::cases::classify_discord(result.as_ref().err()), - crate::db::guild_data::CaseOutcome::Failed - ) { + let outcome = + crate::cases::classify_discord(result.as_ref().err().map(Box::as_ref)); + if matches!(outcome, crate::db::guild_data::CaseOutcome::Failed) { env.app.release_gateway_case_suppression(suppression); } if !env.app.activation.may_record() { anyhow::bail!("writer lease is not held"); } if let Some(attempt) = attempted { - attempt - .finish( - env.app, - crate::cases::classify_discord(result.as_ref().err()), - ) - .await; + attempt.finish(env.app, outcome.clone()).await; } - pending_ban - .finish( - env.app, - crate::cases::classify_discord(result.as_ref().err()), - ) - .await; + pending_ban.finish(env.app, outcome).await; if !env.app.activation.may_record() { anyhow::bail!("writer lease is not held"); } diff --git a/crates/bot/src/discord.rs b/crates/bot/src/discord.rs index a5b05160..e1b8d371 100644 --- a/crates/bot/src/discord.rs +++ b/crates/bot/src/discord.rs @@ -23,6 +23,7 @@ pub(crate) async fn automod_ban( user_id: serenity::model::id::UserId, action: &crate::types::ActionDef, reason: &str, + _attempt: crate::member_directory::BanAttemptToken, ) -> Result<(), Box> { let mut headers = reqwest::header::HeaderMap::new(); headers.insert("X-Audit-Log-Reason", audit_reason_header(reason)); @@ -41,6 +42,21 @@ pub(crate) async fn automod_ban( http.request(request).await.map(|_| ()).map_err(Box::new) } +/// Ban Member with a day deletion window after [`crate::member_directory::begin_ban_attempt`]. +pub(crate) async fn ban_with_reason( + http: &serenity::http::Http, + guild_id: serenity::model::id::GuildId, + user_id: serenity::model::id::UserId, + dmd: u8, + reason: &str, + _attempt: crate::member_directory::BanAttemptToken, +) -> Result<(), Box> { + guild_id + .ban_with_reason(http, user_id, dmd, reason) + .await + .map_err(Box::new) +} + fn audit_reason_header(reason: &str) -> reqwest::header::HeaderValue { // Match Serenity's audit reason encoding (percent-encoded UTF-8). let mut encoded = String::new(); diff --git a/crates/bot/src/member_directory.rs b/crates/bot/src/member_directory.rs index eaa1c5b2..b9a42656 100644 --- a/crates/bot/src/member_directory.rs +++ b/crates/bot/src/member_directory.rs @@ -279,10 +279,19 @@ pub async fn begin_ban_attempt(app: &BotState, guild_id: u64, user_id: u64) -> P } } +/// Compile-time witness proving [`begin_ban_attempt`] reserved (or attempted to +/// reserve) the durable ban-in-progress marker before a Discord ban call. +#[derive(Clone, Copy, Debug)] +pub(crate) struct BanAttemptToken(()); + impl PendingBan { pub(crate) fn operation_id(&self) -> &str { &self.operation_id } + + pub(crate) fn token(&self) -> BanAttemptToken { + BanAttemptToken(()) + } } #[derive(Clone, Debug, PartialEq, Eq)] @@ -1341,28 +1350,24 @@ mod tests { assert_eq!(timed_out, MarkerSave::MaybeLate); } - #[test] - fn each_ban_path_uses_the_shared_marker_helper() { - let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); - for rel in [ - "src/automod.rs", - "src/spam_actions.rs", - "src/commands/behaviors.rs", - "src/commands/plans.rs", - ] { - let source = std::fs::read_to_string(root.join(rel)).unwrap(); - assert!( - source.contains("member_directory::begin_ban_attempt"), - "{rel} must ban through the shared marker helper" - ); - assert!( - !source.contains("deferred until retention marker"), - "{rel} must not skip the Discord ban when the marker save fails" - ); - } - let helper = include_str!("member_directory.rs"); - assert!(helper.contains("reserve_ban_marker(save)")); - assert!(helper.contains("BAN_MARKER_SAVE_DEADLINE")); + #[tokio::test(start_paused = true)] + async fn ban_marker_reservation_times_out_at_deadline_and_never_blocks_ban() { + let mut save = Box::pin(reserve_ban_marker( + std::future::pending::>(), + )); + let poll_before = tokio::time::timeout( + BAN_MARKER_SAVE_DEADLINE.saturating_sub(Duration::from_millis(1)), + &mut save, + ) + .await; + assert!( + poll_before.is_err(), + "reservation must keep waiting until BAN_MARKER_SAVE_DEADLINE" + ); + let outcome = tokio::time::timeout(Duration::from_millis(5), &mut save) + .await + .expect("reservation must finish once BAN_MARKER_SAVE_DEADLINE elapses"); + assert_eq!(outcome, MarkerSave::MaybeLate); } #[tokio::test] diff --git a/crates/bot/src/member_rejoin/tests.rs b/crates/bot/src/member_rejoin/tests.rs index d364807e..ee3bfcf7 100644 --- a/crates/bot/src/member_rejoin/tests.rs +++ b/crates/bot/src/member_rejoin/tests.rs @@ -604,83 +604,444 @@ async fn ignored_user_skips_member_rejoin_note() { assert!(sink.messages.lock().unwrap().is_empty()); } -#[test] -fn maybe_emit_defers_rejoin_enrichment_to_log_admission() { - let src = include_str!("../member_rejoin.rs"); - let start = src - .find("pub(crate) async fn maybe_emit_member_rejoin") - .expect("maybe_emit_member_rejoin"); - let body = &src[start..start + 700]; +#[tokio::test] +async fn maybe_emit_defers_rejoin_enrichment_to_log_admission() { + use std::sync::atomic::AtomicBool; + + const GUILD: i64 = 10; + const SUBJECT: u64 = 42; + let probe = Arc::new(db::StartupProbe::default()); + let _probe = db::enter_startup_probe(Some(probe.clone())); + let f = Fixture::new(); assert!( - !body.contains("enrich_member_rejoin_vars("), - "rejoin enrichment must run only after log delivery admission" + db::claim_active_bot( + &f.app.db, + f.app.activation.instance(), + jmodguard::control::now_ms(), + Arc::new(AtomicBool::new(false)), + ) + .await + .unwrap() ); - assert!(body.contains("emit_member_event")); -} + f.app.activation.mark_lock_held(true); + let enrollment = db::enroll_guild(&f.app.db, GUILD, 100) + .await + .unwrap() + .unwrap(); + f.app.tenant.activate(enrollment.clone()).await.unwrap(); + let _ = ready_directory(&f.app, &enrollment).await; + record_application( + &f.app, + Some(enrollment), + CaseAction::Kick, + CaseOutcome::Succeeded, + SUBJECT, + Some(1), + Some("prior case".into()), + CaseEvidence::Unavailable, + ) + .await + .unwrap(); + let http = Arc::new( + serenity::http::HttpBuilder::new("fixture") + .proxy("http://127.0.0.1:1") + .ratelimiter_disabled(true) + .build(), + ); + let ctx = crate::commands::mod_reason_dm::fixture_context_for_dm_order_test( + http, + Arc::new(serenity::cache::Cache::new()), + ) + .await; + let enrollment_statements = || { + probe + .primary_labels() + .iter() + .filter(|label| label.starts_with("db/enrollments:")) + .map(|label| probe.primary_statements(label)) + .sum::() + }; -#[test] -fn rejected_departure_keeps_rejoin_delivery_guard() { - let src = include_str!("../handlers.rs"); - let start = src - .find("let departed = crate::member_directory::observe_departure") - .expect("departure observation"); - let body = &src[start..start + 900]; - let verify = body - .find("NeedsVerification") - .expect("stale removal must be rejected"); - let clear = body - .find("rejoin_note_deliveries") - .expect("applied departures clear delivery state"); + // Unconfigured log channel must exit before running rejoin enrichment. + let before_unconfigured = enrollment_statements(); + assert_eq!( + maybe_emit_member_rejoin(&f.app, &ctx, GuildId::new(GUILD as u64), &user(SUBJECT)).await, + MemberRejoinEmitOutcome::Retry + ); + assert_eq!( + enrollment_statements() - before_unconfigured, + 0, + "unconfigured channel must not run rejoin enrichment" + ); + + // A configured channel that excludes the user via log filters must also exit before enrichment. + db::upsert_log_channel(&f.app.db, GUILD, "member_rejoin", 200) + .await + .unwrap(); + f.app + .db + .with_conn(|conn| { + conn.execute_bounded( + "INSERT INTO log_filters(guild_id,event_type,data) VALUES(10,'member_rejoin',?1)", + db::params![r#"{"users":["42"],"channels":[]}"#], + 65_536, + )?; + Ok(()) + }) + .await + .unwrap(); + f.app.invalidate_configs(); + let before_filtered = enrollment_statements(); + assert_eq!( + maybe_emit_member_rejoin(&f.app, &ctx, GuildId::new(GUILD as u64), &user(SUBJECT)).await, + MemberRejoinEmitOutcome::Retry + ); + assert_eq!( + enrollment_statements() - before_filtered, + 0, + "filtered user must not run rejoin enrichment" + ); + + // Once admitted, enrichment runs and delivers the prior-case note. + f.app + .db + .with_conn(|conn| { + conn.execute_bounded( + "DELETE FROM log_filters WHERE guild_id = 10 AND event_type = 'member_rejoin'", + (), + 65_536, + )?; + Ok(()) + }) + .await + .unwrap(); + f.app.invalidate_configs(); + let sink = Sink::default(); + let before_admitted = enrollment_statements(); + let (delivery, _) = crate::logging::emit_member_event_to( + &f.app, + &sink, + GuildId::new(GUILD as u64), + "member_rejoin", + &user(SUBJECT), + BTreeMap::new(), + None, + ) + .await; + assert_eq!(delivery, Delivery::Sent); assert!( - verify < clear, - "rejected departures must not release in-flight rejoin delivery" + enrollment_statements() > before_admitted, + "admitted rejoin delivery must enrich from the enrolled guild store" ); - assert!(body.contains("MemberDepartureDecision::Applied(_))")); + assert_eq!(sink.messages.lock().unwrap().len(), 1); + assert!(sink.messages.lock().unwrap()[0].1.contains("prior case")); } -#[test] -fn guild_member_addition_retries_rejoin_without_double_posting() { - let source = include_str!("../handlers.rs"); - let (_, additions) = source - .split_once("async fn guild_member_addition") - .expect("guild_member_addition"); - let (body, _) = additions - .split_once("async fn guild_member_removal") - .expect("guild_member_removal"); - let reserve = body - .find("begin_in_flight") - .expect("join handler must reserve rejoin delivery"); - let emit = body - .find("maybe_emit_member_rejoin") - .expect("join handler must emit the rejoin note"); +#[tokio::test] +async fn rejected_departure_keeps_rejoin_delivery_guard() { + use serenity::client::EventHandler; + use std::sync::atomic::AtomicBool; + + const GUILD: i64 = 10; + const USER: i64 = 42; + let f = Fixture::new(); assert!( - reserve < emit, - "reservation must occur before the awaited rejoin emission" + db::claim_active_bot( + &f.app.db, + f.app.activation.instance(), + jmodguard::control::now_ms(), + Arc::new(AtomicBool::new(false)), + ) + .await + .unwrap() ); + f.app.activation.mark_lock_held(true); + f.app.activation.note_discord_connected(); + let enrollment = db::enroll_guild(&f.app.db, GUILD, 100) + .await + .unwrap() + .unwrap(); + f.app.tenant.activate(enrollment.clone()).await.unwrap(); + let (store, scope) = ready_directory(&f.app, &enrollment).await; + store + .observe_member( + scope.clone(), + MemberObservation { + user_id: USER, + username: Some(Some("member".into())), + global_name: None, + nickname: None, + joined_at_ms: Some(3_000), + observed_at_ms: 3_000, + is_join: true, + }, + ) + .await + .unwrap(); + let (stay, _) = + crate::member_directory::current_rejoin_note(&f.app, GUILD as u64, USER as u64).await; + let stay_id = stay.expect("saved stay"); + let in_flight = f + .app + .rejoin_note_deliveries + .begin_in_flight(GUILD as u64, USER as u64, &stay_id) + .expect("reserve in-flight rejoin delivery"); + + let handler = crate::handlers::Handler { + app: Arc::clone(&f.app), + }; + let http = Arc::new( + serenity::http::HttpBuilder::new("fixture") + .proxy("http://127.0.0.1:1") + .ratelimiter_disabled(true) + .build(), + ); + let ctx = crate::commands::mod_reason_dm::fixture_context_for_dm_order_test( + http, + Arc::new(serenity::cache::Cache::new()), + ) + .await; + let member_with_joined = |joined_at: &str| -> serenity::model::guild::Member { + serde_json::from_value(serde_json::json!({ + "guild_id": GUILD.to_string(), + "user": user(USER as u64), + "roles": [], + "joined_at": joined_at, + "deaf": false, + "mute": false, + "flags": 0 + })) + .unwrap() + }; + + // A stale removal whose joined_at disagrees with the saved stay triggers NeedsVerification + // and must NOT release the in-flight rejoin delivery guard. + handler + .guild_member_removal( + ctx.clone(), + GuildId::new(GUILD as u64), + user(USER as u64), + Some(member_with_joined("1970-01-01T00:00:01Z")), + ) + .await; assert!( - body.contains("in_flight.complete"), - "join handler must record successful rejoin delivery" + !f.app + .rejoin_note_deliveries + .begin_attempt(GUILD as u64, USER as u64, &stay_id), + "rejected stale departure must not release in-flight rejoin delivery" ); - assert_eq!( - body.matches("maybe_emit_member_rejoin").count(), - 1, - "join handler must not double-post the prior-case note" + let queued = store + .next_member_target_check(scope, i64::MAX) + .await + .unwrap() + .expect("stale removal queues targeted verification"); + assert_eq!(queued.user_id, USER); + assert_eq!(queued.reason, "mismatched_departure"); + + // Once the rejoin delivery settles, a matching applied departure clears delivery state. + in_flight.complete(true); + assert!( + !f.app + .rejoin_note_deliveries + .begin_attempt(GUILD as u64, USER as u64, &stay_id), + "settled delivery blocks duplicate attempt before departure" ); + handler + .guild_member_removal( + ctx, + GuildId::new(GUILD as u64), + user(USER as u64), + Some(member_with_joined("1970-01-01T00:00:03Z")), + ) + .await; assert!( - body.contains("pending_redelivery"), - "stale join events must still retry an undelivered rejoin note" + f.app + .rejoin_note_deliveries + .begin_attempt(GUILD as u64, USER as u64, &stay_id), + "applied departure must clear rejoin delivery state" ); +} + +#[tokio::test] +async fn concurrent_guild_member_addition_does_not_double_post_rejoin_note() { + use hyper::service::{make_service_fn, service_fn}; + use hyper::{Body, Request, Response, Server}; + use serenity::client::EventHandler; + use std::convert::Infallible; + use std::sync::atomic::AtomicBool; + use tokio::sync::Notify; + + const GUILD: i64 = 10; + const USER: i64 = 42; + // Allow two concurrent log admissions so the second join handler reaches the + // rejoin in-flight guard while the first rejoin HTTP request is still active. + let f = Fixture::with_log_limits(2, 5); assert!( - body.contains("membership_refresh || retry_undelivered || durable_pending"), - "fresh stays, durable receipts, or failed-delivery retries may emit rejoin notes" + db::claim_active_bot( + &f.app.db, + f.app.activation.instance(), + jmodguard::control::now_ms(), + Arc::new(AtomicBool::new(false)), + ) + .await + .unwrap() + ); + f.app.activation.mark_lock_held(true); + f.app.activation.note_discord_connected(); + let enrollment = db::enroll_guild(&f.app.db, GUILD, 100) + .await + .unwrap() + .unwrap(); + f.app.tenant.activate(enrollment.clone()).await.unwrap(); + let (store, scope) = ready_directory(&f.app, &enrollment).await; + record_application( + &f.app, + Some(enrollment), + CaseAction::Kick, + CaseOutcome::Succeeded, + USER as u64, + Some(1), + Some("prior case for concurrent rejoin".into()), + CaseEvidence::Unavailable, + ) + .await + .unwrap(); + store + .observe_member( + scope.clone(), + MemberObservation { + user_id: USER, + username: Some(Some("member".into())), + global_name: None, + nickname: None, + joined_at_ms: Some(1_000), + observed_at_ms: 1_000, + is_join: true, + }, + ) + .await + .unwrap(); + store + .depart_member(scope.clone(), USER, 2_000) + .await + .unwrap(); + db::upsert_log_channel(&f.app.db, GUILD, "member_rejoin", 999) + .await + .unwrap(); + f.app.invalidate_configs(); + let member: serenity::model::guild::Member = serde_json::from_value(serde_json::json!({ + "guild_id": GUILD.to_string(), + "user": user(USER as u64), + "roles": [], + "joined_at": "1970-01-01T00:00:03Z", + "deaf": false, + "mute": false, + "flags": 0 + })) + .unwrap(); + let handler = Arc::new(crate::handlers::Handler { + app: Arc::clone(&f.app), + }); + let requests = Arc::new(Mutex::new(Vec::new())); + let captured = Arc::clone(&requests); + let first_started = Arc::new(Notify::new()); + let release_first = Arc::new(Notify::new()); + let server = Server::bind(&([127, 0, 0, 1], 0).into()); + let http = Arc::new( + serenity::http::HttpBuilder::new("fixture") + .proxy(format!("http://{}", server.local_addr())) + .ratelimiter_disabled(true) + .build(), ); + let ctx = crate::commands::mod_reason_dm::fixture_context_for_dm_order_test( + http, + Arc::new(serenity::cache::Cache::new()), + ) + .await; + let started_tx = Arc::clone(&first_started); + let release_rx = Arc::clone(&release_first); + let server = tokio::spawn(server.serve(make_service_fn(move |_| { + let captured = Arc::clone(&captured); + let started_tx = Arc::clone(&started_tx); + let release_rx = Arc::clone(&release_rx); + async move { + Ok::<_, Infallible>(service_fn(move |request: Request| { + let captured = Arc::clone(&captured); + let started_tx = Arc::clone(&started_tx); + let release_rx = Arc::clone(&release_rx); + async move { + let (parts, body) = request.into_parts(); + let body = hyper::body::to_bytes(body).await.unwrap(); + let payload: serde_json::Value = serde_json::from_slice(&body).unwrap(); + let call_index = { + let mut calls = captured.lock().unwrap(); + calls.push((parts.method, parts.uri.path().to_owned(), payload)); + calls.len() + }; + if call_index == 1 { + started_tx.notify_one(); + release_rx.notified().await; + } + Ok::<_, Infallible>( + Response::builder() + .status(200) + .header("content-type", "application/json") + .body(Body::from( + r#"{"id":"1000","channel_id":"999","author":{"id":"1","username":"fixture","discriminator":"0","avatar":null},"content":"fixture","timestamp":"2026-01-01T00:00:00Z","tts":false,"mention_everyone":false,"mentions":[],"mention_roles":[],"attachments":[],"embeds":[],"pinned":false,"type":0}"#, + )) + .unwrap(), + ) + } + })) + } + }))); + + let mut first_task = { + let handler = Arc::clone(&handler); + let ctx = ctx.clone(); + let member = member.clone(); + tokio::spawn(async move { handler.guild_member_addition(ctx, member).await }) + }; + let wait_for_post = tokio::time::timeout(std::time::Duration::from_secs(5), async { + tokio::select! { + _ = first_started.notified() => Ok(()), + res = &mut first_task => Err(res), + } + }) + .await; + match wait_for_post { + Ok(Ok(())) => {} + Ok(Err(res)) => { + server.abort(); + panic!("first guild_member_addition exited before posting rejoin note: {res:?}"); + } + Err(_) => { + first_task.abort(); + server.abort(); + panic!("timed out waiting for first guild_member_addition to post rejoin note"); + } + } + // While the first rejoin post is in flight, a second addition for the same stay must not post again. + handler.guild_member_addition(ctx, member).await; + release_first.notify_one(); + first_task.await.unwrap(); + + let pending_after = store.has_pending_rejoin_note(scope, USER).await.unwrap(); + server.abort(); + assert!(server.await.unwrap_err().is_cancelled()); assert!( - body.contains("clear_pending_rejoin_note"), - "settled rejoin delivery must clear the durable receipt" + !pending_after, + "settled rejoin delivery must clear durable receipt" + ); + let requests = requests.lock().unwrap(); + assert_eq!( + requests.len(), + 1, + "concurrent join events for the same stay must post only once" ); assert!( - body.contains("retain_current_stay") && body.matches("current_rejoin_note").count() == 1, - "in-memory retries must key to the current stay" + crate::logging::tests::log_text(&requests[0].2) + .contains("prior case for concurrent rejoin") ); } @@ -1014,11 +1375,15 @@ struct Fixture { impl Fixture { fn new() -> Self { + Self::with_log_limits(1, 1) + } + + fn with_log_limits(discord_concurrency: usize, discord_timeout_secs: u64) -> Self { let path = std::env::temp_dir().join(format!("member_rejoin_{:032x}.db", rand::random::())); let mut cfg = BotProcessConfig::default(); - cfg.log.discord_concurrency = 1; - cfg.log.discord_timeout_secs = 1; + cfg.log.discord_concurrency = discord_concurrency; + cfg.log.discord_timeout_secs = discord_timeout_secs; Self { app: BotState::new(cfg, Db::open(&path, 2).unwrap()).unwrap(), path, diff --git a/crates/bot/src/spam_actions.rs b/crates/bot/src/spam_actions.rs index f7d1f76d..bd80081f 100644 --- a/crates/bot/src/spam_actions.rs +++ b/crates/bot/src/spam_actions.rs @@ -927,6 +927,7 @@ async fn punish_proven_match( chrono::Utc::now().timestamp_millis(), ); } + let ban_token = pending_ban.token(); if let Some(outcome) = dispatch_spam_ban( app, enrollment.clone(), @@ -942,6 +943,7 @@ async fn punish_proven_match( UserId::new(found.author), ban_action, &discord_reason, + ban_token, ), ) .await diff --git a/crates/runtime/src/cgroup.rs b/crates/runtime/src/cgroup.rs index 7686b69d..fac5dfd7 100644 --- a/crates/runtime/src/cgroup.rs +++ b/crates/runtime/src/cgroup.rs @@ -2045,22 +2045,145 @@ mod tests { } #[test] - fn reader_source_reads_host_memory_only_for_the_v1_limit() { - let source = include_str!("cgroup.rs"); - let production = source.split("#[cfg(test)]").next().unwrap(); - let meminfo = ["/proc/", "meminfo"].concat(); - let host_stat = ["/proc/", "stat"].concat(); - assert!( - !source.contains(&meminfo), - "host memory is read only through host_memory_total" - ); - assert!( - !source.contains(&host_stat), - "host processor file must not be read" - ); - // One read of `MemTotal`, whose only consumer is the v1 limit check. - assert_eq!(production.matches("\"meminfo\"").count(), 1); - assert_eq!(production.matches("host_memory_total(").count(), 2); + fn host_memory_is_consulted_only_for_numeric_v1_limits_and_host_proc_is_never_reported() { + // Host /proc/meminfo and /proc/stat must never fabricate container memory or CPU readings. + let empty_cgroup = temp_tree(); + let proc = temp_tree(); + write_files( + &proc.path, + &[ + ("meminfo", "MemTotal: 33554432 kB\nMemFree: 1024 kB\n"), + ("stat", "cpu 100 200 300 400\n"), + ("self/cgroup", "0::/\n"), + ( + "self/mountinfo", + &format!("{}\n", v2_mount_line("/", &empty_cgroup.path)), + ), + ], + ); + assert_eq!( + read_proc_cgroup(&proc.path, &empty_cgroup.path), + CgroupReading::default(), + "host /proc/meminfo and /proc/stat must not synthesize cgroup counters" + ); + assert_eq!( + read_proc_cpu_limit(&proc.path, &empty_cgroup.path), + None, + "host /proc/stat must not synthesize a cgroup CPU quota" + ); + + // cgroup v2 never consults host_total, even when memory.max exceeds host memory. + for (max, expected) in [ + ("max\n", MemoryLimit::Unlimited), + ("536870912\n", MemoryLimit::Bytes(512 << 20)), + ("68719476736\n", MemoryLimit::Bytes(64 * GIB)), + ] { + let v2 = temp_tree(); + write_files( + &v2.path, + &[ + ("memory.current", "1000\n"), + ("memory.stat", "inactive_file 100\n"), + ("memory.max", max), + ], + ); + let calls = AtomicU64::new(0); + let dirs = [CgroupDir { + path: v2.path.clone(), + mount: v2.path.clone(), + }]; + let reading = read_resolved_cgroup( + &dirs, + &[], + || { + calls.fetch_add(1, Ordering::SeqCst); + Some(32 * GIB) + }, + None, + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "v2 limit {max:?} must not consult host memory" + ); + let memory = reading.counters.memory.unwrap(); + assert_eq!(memory.program_bytes, 900); + assert_eq!(memory.limit, expected); + } + + // cgroup v1 sentinel / max / absent limits do not consult host_total. + for limit in [None, Some("max\n"), Some(V1_SENTINEL)] { + let v1 = temp_tree(); + let mut files = vec![ + ("memory.usage_in_bytes", "1000\n"), + ("memory.stat", "inactive_file 100\n"), + ]; + if let Some(limit) = limit { + files.push(("memory.limit_in_bytes", limit)); + } + write_files(&v1.path, &files); + let calls = AtomicU64::new(0); + let dirs = [CgroupDir { + path: v1.path.clone(), + mount: v1.path.clone(), + }]; + let reading = read_resolved_cgroup( + &dirs, + &[], + || { + calls.fetch_add(1, Ordering::SeqCst); + Some(32 * GIB) + }, + None, + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 0, + "v1 non-numeric/sentinel limit {limit:?} must not consult host memory" + ); + assert_eq!( + reading.counters.memory.unwrap().limit, + MemoryLimit::Unlimited + ); + } + + // A numeric v1 limit below the sentinel consults host_total once only to classify Unlimited vs Bytes. + for (limit, expected) in [ + ("536870912\n", MemoryLimit::Bytes(512 << 20)), + ("34359738368\n", MemoryLimit::Unlimited), + ] { + let v1 = temp_tree(); + write_files( + &v1.path, + &[ + ("memory.usage_in_bytes", "1000\n"), + ("memory.stat", "inactive_file 100\n"), + ("memory.limit_in_bytes", limit), + ], + ); + let calls = AtomicU64::new(0); + let dirs = [CgroupDir { + path: v1.path.clone(), + mount: v1.path.clone(), + }]; + let reading = read_resolved_cgroup( + &dirs, + &[], + || { + calls.fetch_add(1, Ordering::SeqCst); + Some(32 * GIB) + }, + None, + ); + assert_eq!( + calls.load(Ordering::SeqCst), + 1, + "v1 numeric limit {limit:?} consults host memory once" + ); + let memory = reading.counters.memory.unwrap(); + assert_eq!(memory.program_bytes, 900); + assert_eq!(memory.limit, expected); + } } #[test] diff --git a/frontend/app.js b/frontend/app.js index a516b562..2e41aa40 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -1814,25 +1814,18 @@ function TabPlatformAnalytics() { function PlatformAnalytics() { const [days, setDays] = useState(30); - const [legacy, setLegacy] = useState(false); - const historyPath = `/api/platform/analytics?days=${days}`; - const result = useApiRead(legacy ? historyPath : `${historyPath}&include_members=false`, { retainData: true }); - const directory = useApiRead(legacy ? null : "/api/platform/analytics/members", { retainData: true }); - const splitMissing = !legacy && directory.error?.status === 404; - useEffect(() => { - if (splitMissing) setLegacy(true); - }, [splitMissing]); + const result = useApiRead(`/api/platform/analytics?days=${days}&include_members=false`, { retainData: true }); + const directory = useApiRead("/api/platform/analytics/members", { retainData: true }); const snapshot = result.data; - const checkingLegacy = splitMissing || (!legacy && directory.loading && result.error?.status === 400); - const historyError = checkingLegacy ? null : result.error; + const historyError = result.error; const loading = !snapshot && !historyError; const failed = !snapshot && Boolean(historyError); const rangeLabel = `${days} days`; const series = snapshot?.series; const points = React.useMemo(() => toTrendPoints(series), [series]); const previous = snapshot?.previous ?? null; - const members = legacy ? snapshot?.members : directory.error?.status === 403 ? null : directory.data; - const membersLoading = !members && (legacy ? loading : splitMissing || (directory.loading && !directory.error)); + const members = directory.error?.status === 403 ? null : directory.data; + const membersLoading = !members && directory.loading && !directory.error; const snapshotGuildIds = Array.isArray(members?.snapshot_guild_ids) ? new Set(members.snapshot_guild_ids) : null; const rows = platformRows(snapshot, members, membersLoading, snapshotGuildIds); const activeRows = rows.filter(row => row.active); @@ -1862,7 +1855,7 @@ function PlatformAnalytics() { snapshot ? render() : h("p", { className: "an-empty muted", "aria-busy": loading ? "true" : "false" }, failed ? "Unavailable" : "Loading…"); const rank = (title, id, props) => analyticsPanel(title, id, body(() => h(RankList, props)), "an-span-4"); const memberStatus = !membersLoading && members?.status !== "complete" ? platformMemberStatus(members) : ""; - const memberWarning = directory.error && !splitMissing + const memberWarning = directory.error ? members ? `Member totals refresh failed. ${directory.error.message}. Showing the last successful response (stale). ${memberStatus}`.trim() : `Member totals unavailable. ${directory.error.message}` @@ -1877,7 +1870,7 @@ function PlatformAnalytics() { h(RangeSelector, { value: days, onChange: setDays }), h(ActionButton, { id: "refresh-platform-analytics", size: "sm", onClick: () => { result.refresh(); - if (!legacy) directory.refresh(); + directory.refresh(); } }, "Refresh"), helpTooltip("About these figures", PLATFORM_HELP), ), @@ -5353,7 +5346,7 @@ function tabDashboard() { ), h( Paper, - { withBorder: true, className: "stats w-full dashboard-stats" }, + { withBorder: true, className: "stats w-full dashboard-stats", "data-testid": "dashboard-stats" }, // One row each for protection, moderation activity and server configuration. stat("Rules enabled", `${rulesOn} / ${rules.length}`, "rules-enabled"), stat("Rules in dry-run", rulesDry, "rules-dry-run"), @@ -5387,9 +5380,9 @@ function stat(label, value, icon) { const tile = icon && DASHBOARD_ICONS[icon]; return h( "div", - { className: "stat" }, - h("div", { className: "stat-title" }, tile && h(Icon, { name: tile.icon, intent: tile.intent }), ...[label].flat()), - h("div", { className: "stat-value" }, value), + { className: "stat", "data-testid": "dashboard-stat" }, + h("div", { className: "stat-title", "data-testid": "dashboard-stat-label" }, tile && h(Icon, { name: tile.icon, intent: tile.intent }), ...[label].flat()), + h("div", { className: "stat-value", "data-testid": "dashboard-stat-value" }, value), ); } diff --git a/scripts/frontend-contrast-test.mjs b/scripts/frontend-contrast-test.mjs index beaf0267..ce264e69 100644 --- a/scripts/frontend-contrast-test.mjs +++ b/scripts/frontend-contrast-test.mjs @@ -570,6 +570,29 @@ function mediaBlock(query, source = css) { } throw new Error(`unterminated @media ${query}`); } +function mediaBlocks(query, source = css) { + const prefix = `@media ${query} {`; + const blocks = []; + let offset = 0; + while (true) { + const start = source.indexOf(prefix, offset); + if (start < 0) break; + let depth = 0; + let end = -1; + for (let index = source.indexOf("{", start); index < source.length; index++) { + if (source[index] === "{") depth++; + if (source[index] === "}" && --depth === 0) { + end = index; + break; + } + } + assert.ok(end >= 0, `unterminated @media ${query}`); + blocks.push(source.slice(source.indexOf("{", start) + 1, end)); + offset = end + 1; + } + assert.ok(blocks.length > 0, `missing @media ${query}`); + return blocks.join("\n"); +} test("public policies use readable dashboard colors in both system themes", () => { const legalCss = readFileSync(new URL("../crates/api/src/web/legal/style.css", import.meta.url), "utf8"); const light = tokens(".legal-site", legalCss); @@ -601,6 +624,9 @@ test("shared desktop scale keeps controls compact and readable in both themes", assert.ok(value("--card-p") > 16 && value("--card-p") <= 18); assert.ok(value("--ui-gap") > 12 && value("--ui-gap") <= 14); assert.ok(value("--stat-value-size") > 20 && value("--stat-value-size") <= 23); + assert.equal(declaration(rule("#content"), "gap"), "var(--ui-gap)"); + const heading = declaration(rule("#content h2"), "font-size"); + assert.ok(px(heading) <= 20, `page heading ${heading}`); assert.match(declaration(shared, "--dialog-gutter"), /^[\d.]+rem$/); const narrow = mediaBlock("(max-width: 720px), (pointer: coarse)", controls); assert.match(declaration(narrow, "--dialog-gutter"), /^(?:min\([\d.]+rem,\s*\d+px\)|[\d.]+rem)$/); @@ -626,17 +652,6 @@ test("global UI scale uses percentage root sizing and rem typography without har assert.equal(declaration(rule("#content"), "max-width"), "1440px"); }); -test("the page uses the scale tokens instead of the old touch-sized values", () => { - assert.match(mantineBaseline, /body,\s*:host\s*\{[^}]*font-size:\s*var\(--mantine-font-size-md\)/); - assert.equal(emittedMantineVariables()["--mantine-font-size-md"], "var(--ui-font-size)"); - assert.match(rule(".stat-value"), /font-size:\s*var\(--stat-value-size\)/); - assert.match(css, /#content\s*\{[^}]*gap:\s*var\(--ui-gap\)/); - const heading = declaration(rule("#content h2"), "font-size"); - assert.ok(px(heading) <= 20, `page heading ${heading}`); - // Old scale: 2rem page headings, 36px/40px content padding, 1.875rem stat numerals. - assert.doesNotMatch(css, /clamp\(1\.5rem, 2\.2vw, 2rem\)|padding: 36px 40px|clamp\(1\.25rem, 2vw, 1\.875rem\)/); -}); - test("compact controls keep a visible focus ring with 3:1 contrast on every surface", () => { const focus = css.match(/^:is\(([^)]*)\):focus-visible\s*\{([^}]*)\}/m); assert.ok(focus, "missing the shared :focus-visible rule"); @@ -648,7 +663,7 @@ test("compact controls keep a visible focus ring with 3:1 contrast on every surf assert.match(switchFocus, /outline:\s*2px solid var\(--accent\)/); assert.match(switchFocus, /outline-offset:\s*2px/); // No first-party rule removes the outline from a focused control. - for (const [, selectors, body] of css.matchAll(/([^{}]*:focus(?:-visible|-within)?[^{}]*)\{([^}]*)\}/g)) + for (const [, selectors, body] of (css + controls).matchAll(/([^{}]*:focus(?:-visible|-within)?[^{}]*)\{([^}]*)\}/g)) assert.doesNotMatch(body, /outline(?:-style)?:\s*(?:none|0)\b/, selectors.trim()); for (const [theme, selector] of [["light", ":root"], ["dark", ':root[data-theme="dark"]']]) { const colors = tokens(selector); @@ -891,29 +906,8 @@ test("dashboard icons use the shared icon size, not a page-specific scale", () = assert.match(iconCssRule(':is(.mantine-Button-root, .mantine-ActionIcon-root):is(:disabled, [aria-disabled="true"]) svg.icon'), /color:\s*inherit/); }); -// Analytics dashboard (#587): one delimited stylesheet section, series colors -// readable in both themes, no wrapping numbers and a one-column narrow layout. -const ANALYTICS_START = "Analytics dashboard (#587). Self-contained"; -const ANALYTICS_END = "/* ==== end Analytics dashboard (#587) ==== */"; -function analyticsCss() { - const start = css.indexOf(ANALYTICS_START); - const end = css.indexOf(ANALYTICS_END); - assert.ok(start > 0 && end > start, "analytics styles live in one delimited section"); - return css.slice(css.lastIndexOf("/*", start), end + ANALYTICS_END.length); -} - -test("analytics styles stay inside their delimited section", () => { - const section = analyticsCss(); - const outside = css.replace(section, ""); - assert.doesNotMatch(outside, /\.an-[\w-]+|\.analytics-page/, "no analytics selector outside the section"); - for (const [, selectors] of section.replace(/\/\*[\s\S]*?\*\//g, "").matchAll(/([^{}]+)\{[^{}]*\}/g)) { - const trimmed = selectors.trim(); - if (trimmed.startsWith("@media")) continue; - for (const selector of trimmed.split(",").map((part) => part.trim())) - assert.match(selector, /(?:^|\s|\[data-theme="dark"\] )(?:\.analytics-page|\.an-|#content \.an-)/, `scoped selector: ${selector}`); - } -}); - +// Analytics dashboard (#587): series colors readable in both themes, +// no wrapping numbers and a one-column narrow layout. for (const [theme, rootSelector, analyticsSelector] of [ ["light", ":root", ".analytics-page"], ["dark", ':root[data-theme="dark"]', '[data-theme="dark"] .analytics-page'], @@ -929,9 +923,8 @@ for (const [theme, rootSelector, analyticsSelector] of [ assert.ok(ratio >= 3, `${theme} ${name} on panel: ${ratio.toFixed(2)}:1`); } assert.equal(new Set(names.map((name) => series[name].toLowerCase())).size, names.length, `${theme} series colors are distinct`); - const section = analyticsCss(); for (const selector of [".an-kpi-label", ".an-delta"]) - assert.match(rule(selector, section), /color:\s*var\(--muted\)/, selector); + assert.match(rule(selector, css), /color:\s*var\(--muted\)/, selector); assert.ok(contrast(shell["--muted"], shell["--panel"]) >= 4.5, `${theme} muted labels`); assert.ok(contrast(shell["--warn"], shell["--panel"]) >= 4.5, `${theme} coverage badge`); assert.ok(contrast(shell["--accent-text"], shell["--accent"]) >= 4.5, `${theme} selected range`); @@ -939,60 +932,41 @@ for (const [theme, rootSelector, analyticsSelector] of [ } test("analytics numbers never wrap and the grid collapses on narrow screens", () => { - const section = analyticsCss(); for (const selector of [".an-kpi-value", ".an-delta", ".an-rank-count", ".an-badge"]) - assert.match(rule(selector, section), /white-space:\s*nowrap/, selector); - assert.match(rule(".an-kpi-body", section), /white-space:\s*nowrap/); - assert.match(rule(".an-kpi-value", section), /font-variant-numeric:\s*tabular-nums/); + assert.match(rule(selector, css), /white-space:\s*nowrap/, selector); + assert.match(rule(".an-kpi-body", css), /white-space:\s*nowrap/); + assert.match(rule(".an-kpi-value", css), /font-variant-numeric:\s*tabular-nums/); // Headline numerals stay below the shared stat scale (no oversized numbers). - assert.ok(px(declaration(rule(".an-kpi-value", section), "font-size")) <= 20); - assert.match(rule(".an-kpis", section), /grid-template-columns:\s*repeat\(auto-fit,\s*minmax\(/); - const narrow = section.slice(section.indexOf("@media (max-width: 720px) {")); + assert.ok(px(declaration(rule(".an-kpi-value", css), "font-size")) <= 20); + assert.match(rule(".an-kpis", css), /grid-template-columns:\s*repeat\(auto-fit,\s*minmax\(/); + const narrow = mediaBlocks("(max-width: 720px)", css); assert.match(narrow, /\.an-grid\s*\{\s*grid-template-columns:\s*minmax\(0,\s*1fr\);/); assert.match(narrow, /\.an-span-4, \.an-span-5, \.an-span-7, \.an-span-12\s*\{\s*grid-column:\s*auto;/); - const medium = section.slice(section.indexOf("@media (max-width: 1100px) {")); + const medium = mediaBlocks("(max-width: 1100px)", css); assert.match(medium, /\.an-span-5, \.an-span-7\s*\{\s*grid-column:\s*span 12;/); }); -// Database usage (#613): one delimited stylesheet section; gauge fills and -// threshold marks keep 3:1 against their track, text stays readable. -const USAGE_START = "Database usage (#613). Self-contained"; -const USAGE_END = "/* ==== end Database usage (#613) ==== */"; -function usageCss() { - const start = css.indexOf(USAGE_START); - const end = css.indexOf(USAGE_END); - assert.ok(start > 0 && end > start, "database usage styles live in one delimited section"); - return css.slice(css.lastIndexOf("/*", start), end + USAGE_END.length); -} - -test("database usage styles stay inside their delimited section", () => { - const section = usageCss(); - assert.doesNotMatch(css.replace(section, ""), /\.du-[\w-]+|\.database-usage-page/, "no database usage selector outside the section"); - for (const [, selectors] of section.replace(/\/\*[\s\S]*?\*\//g, "").matchAll(/([^{}]+)\{[^{}]*\}/g)) - for (const selector of selectors.trim().split(",").map((part) => part.trim())) - assert.match(selector, /^(?:#content )?\.(?:du-|database-usage-page)/, `scoped selector: ${selector}`); -}); - +// Database usage (#613): gauge fills and threshold marks keep 3:1 against their track, +// and captions stay readable. for (const [theme, selector] of [["light", ":root"], ["dark", ':root[data-theme="dark"]']]) { test(`${theme} database usage fills, marks and captions stay readable`, () => { const colors = tokens(selector); - const section = usageCss(); - const tones = Object.fromEntries([...section.matchAll(/\.du-tone-(\w+)\s*\{\s*--du-tone:\s*var\((--[\w-]+)\)/g)].map(([, tone, token]) => [tone, token])); + const tones = Object.fromEntries([...css.matchAll(/\.du-tone-(\w+)\s*\{\s*--du-tone:\s*var\((--[\w-]+)\)/g)].map(([, tone, token]) => [tone, token])); assert.deepEqual(Object.keys(tones).sort(), ["accent", "bad", "muted", "ok", "warn"]); for (const [tone, token] of Object.entries(tones)) { // WCAG 1.4.11: a fill must stand out from the track it is drawn on. const ratio = contrast(colors[token], colors["--panel2"]); assert.ok(ratio >= 3, `${theme} ${tone} fill on track: ${ratio.toFixed(2)}:1`); } - assert.match(rule(".du-gauge-mark", section), /background:\s*var\(--text\)/); + assert.match(rule(".du-gauge-mark", css), /background:\s*var\(--text\)/); assert.ok(contrast(colors["--text"], colors["--panel2"]) >= 3, `${theme} threshold marks`); // The empty track keeps a visible boundary on the card. - assert.match(rule(".du-gauge-track, .du-share", section), /border:\s*1px solid var\(--input-border\)/); + assert.match(rule(".du-gauge-track, .du-share", css), /border:\s*1px solid var\(--input-border\)/); assert.ok(contrast(colors["--input-border"], colors["--panel"]) >= 3, `${theme} track boundary`); for (const caption of [".du-chip", ".du-metric-caption", ".du-facts dt", ".du-unknown"]) - assert.match(rule(caption, section), /color:\s*var\(--muted\)/, caption); + assert.match(rule(caption, css), /color:\s*var\(--muted\)/, caption); assert.ok(contrast(colors["--muted"], colors["--panel"]) >= 4.5, `${theme} muted captions`); - assert.match(rule(".du-stale", section), /color:\s*var\(--warn\)/); + assert.match(rule(".du-stale", css), /color:\s*var\(--warn\)/); assert.ok(contrast(colors["--warn"], colors["--panel"]) >= 4.5, `${theme} stale warning`); }); } diff --git a/scripts/frontend-state-test.mjs b/scripts/frontend-state-test.mjs index cdd1a9f8..d710ccb8 100644 --- a/scripts/frontend-state-test.mjs +++ b/scripts/frontend-state-test.mjs @@ -1115,22 +1115,20 @@ test('dashboard shows the configured and measured stats in one compact grid', as app.state.config = configuredDashboard(); const dashboard = app.tabDashboard(); await settle(); - const grids = Array.from(dashboard.querySelectorAll('.stats')); + const grids = Array.from(dashboard.querySelectorAll('[data-testid="dashboard-stats"]')); assert.equal(grids.length, 1, 'one stat grid'); - assert.ok(grids[0].classList.contains('dashboard-stats')); - const value = (label) => Array.from(grids[0].children) - .find((n) => n.className === 'stat' && n.querySelector('.stat-title').textContent.startsWith(label)) - ?.querySelector('.stat-value').textContent; + const tiles = Array.from(grids[0].querySelectorAll('[data-testid="dashboard-stat"]')); + const value = (label) => tiles + .find((n) => n.querySelector('[data-testid="dashboard-stat-label"]').textContent.startsWith(label)) + ?.querySelector('[data-testid="dashboard-stat-value"]').textContent; const expected = [ ['Rules enabled', '1 / 2'], ['Rules in dry-run', '1'], ['Commands enabled', '1 / 2'], ['Log channels', '1'], ['Moderation records', '7'], ['Warns', '2'], ['Bans', '1'], ['Cases', '4'], ['Prefix', '!'], ['Bot nickname', 'Guard'], ['Badword patterns', '3'], ]; assert.equal(value('Routine chat collection'), undefined); - assert.equal(grids[0].children.length, expected.length, 'no stat dropped or duplicated'); + assert.equal(tiles.length, expected.length, 'no stat dropped or duplicated'); for (const [label, shown] of expected) assert.equal(value(label), shown, label); - // The hero, its eyebrow and the separate explainer band are gone. - assert.equal(dashboard.querySelector('.sf-empty-panel, .hero, .dashboard-hero, .eyebrow, .dashboard-note')?.className ?? null, null); const header = dashboard.querySelector('.page-header'); assert.ok(Boolean(header), 'expected a page header'); assert.equal(header.querySelectorAll('h2').length, 1); @@ -1139,7 +1137,6 @@ test('dashboard shows the configured and measured stats in one compact grid', as assert.match(header.querySelector('.page-header-detail').textContent, /First/); assert.deepEqual(Array.from(header.querySelectorAll('button')).map((b) => b.textContent), ['Review protection', 'View audit log']); for (const button of header.querySelectorAll('button')) { - assert.ok(button.classList.contains('mantine-Button-root')); assert.equal(button.getAttribute('data-size'), 'sm'); } }); @@ -1153,10 +1150,10 @@ test('dashboard distinguishes an unset bot nickname from unavailable settings', app.state.config = { ...configuredDashboard(), settings }; const dashboard = app.tabDashboard(); await settle(); - const tile = [...dashboard.querySelectorAll('.dashboard-stats > .stat')] - .find((stat) => stat.querySelector('.stat-title').textContent === 'Bot nickname'); + const tile = [...dashboard.querySelectorAll('[data-testid="dashboard-stat"]')] + .find((stat) => stat.querySelector('[data-testid="dashboard-stat-label"]').textContent === 'Bot nickname'); assert.ok(tile, 'dashboard includes the bot nickname tile'); - assert.equal(tile.querySelector('.stat-value').textContent, expected); + assert.equal(tile.querySelector('[data-testid="dashboard-stat-value"]').textContent, expected); } }); @@ -1165,14 +1162,14 @@ test('dashboard count explainer is an accessible, keyboard-reachable tooltip', a app.state.config = configuredDashboard(); const dashboard = app.tabDashboard(); await settle(); - const trigger = dashboard.querySelector('.tooltip-trigger'); + const trigger = dashboard.querySelector('button[aria-label="About these counts"]'); assert.ok(Boolean(trigger), 'expected an info tooltip trigger'); assert.equal(trigger.tagName, 'BUTTON'); assert.equal(trigger.getAttribute('type'), 'button'); assert.notEqual(trigger.tabIndex, -1, 'keyboard focusable'); assert.equal(trigger.getAttribute('aria-label'), 'About these counts'); // The trigger sits with the stat it explains. - assert.match(trigger.closest('.stat').querySelector('.stat-title').textContent, /^Moderation records/); + assert.match(trigger.closest('[data-testid="dashboard-stat"]').querySelector('[data-testid="dashboard-stat-label"]').textContent, /^Moderation records/); assert.equal(trigger.getAttribute('aria-describedby'), null, 'closed until hover or focus'); assert.equal(document.querySelector('[role="tooltip"]'), null, 'hidden until hover or focus'); const tip = await openTooltip(trigger); @@ -1195,8 +1192,8 @@ test('count tooltip stays open while the pointer moves from the trigger onto its app.state.config = configuredDashboard(); const dashboard = app.tabDashboard(); await settle(); - const trigger = dashboard.querySelector('.tooltip-trigger'); - const outside = trigger.closest('.stat').querySelector('.stat-value'); + const trigger = dashboard.querySelector('button[aria-label="About these counts"]'); + const outside = trigger.closest('[data-testid="dashboard-stat"]').querySelector('[data-testid="dashboard-stat-value"]'); trigger.getBoundingClientRect = () => ({ left: 100, top: 200, right: 124, bottom: 224, width: 24, height: 24, x: 100, y: 200 }); await fire(trigger, 'mouseenter', { relatedTarget: outside, clientX: 112, clientY: 212 }); const tip = document.getElementById(trigger.getAttribute('aria-describedby')); @@ -1348,19 +1345,19 @@ test('analytics opens with a one-line header, range selector and info tip, then app.state.config = ANALYTICS_CONFIG; const panel = app.tabAnalytics(); await settle(); - assert.equal(panel.querySelector('.sf-empty-panel, .hero, .dashboard-hero, .eyebrow')?.className ?? null, null); const header = panel.querySelector('.page-header'); assert.equal(header.querySelector('h2').textContent, 'Analytics'); + assert.equal(Boolean(header.querySelector('p')), false, 'the header carries no paragraph copy'); assert.match(header.querySelector('.page-header-detail').textContent, /First · last 30 days \(UTC\)/); // The explanation lives in the collapsible info tip, not a paragraph on the page. - const tip = header.querySelector('.tooltip-trigger'); - assert.equal(tip.getAttribute('aria-label'), 'About these trends'); + const tip = header.querySelector('button[aria-label="About these trends"]'); + assert.ok(Boolean(tip), 'expected an About these trends tooltip trigger'); const tipBody = await openTooltip(tip); assert.match(tipBody.textContent, /never added up/); // Unverified Members may be recovering on its own, so the tip defers to the Members page instead of demanding Reconcile. assert.match(tipBody.textContent, /Open Members to see recovery progress, retry timing, and available controls/); await fire(tip, 'keydown', { key: 'Escape' }); - assert.equal([...panel.querySelectorAll('.dashboard-note strong')].some((n) => n.textContent === 'About these trends'), false); + assert.doesNotMatch(textOf(panel), /About these trends/, 'explanation stays inside the tooltip'); // Range selector: labelled group of pressed-state buttons. const range = panel.querySelector('[aria-label="Analytics date range"]'); assert.equal(range.getAttribute('role'), 'group'); @@ -2160,9 +2157,9 @@ test('Members uses saved identity, keeps large IDs exact and labels partial impo assert.match(textOf(panel), /Test Member 1/); assert.match(textOf(panel), /9007199254740993/); assert.match(textOf(panel), /Member list: partial/); - assert.equal(memberCoverage(panel).querySelector('.badge').textContent, 'partial'); - // The explanation is reachable from the keyboard, not only by hovering the badge. - const trigger = memberCoverage(panel).querySelector('.tooltip-trigger'); + assert.match(textOf(memberCoverage(panel)), /^Member list: partial\b/); + // The explanation is reachable from the keyboard, not only by hovering the label. + const trigger = memberCoverage(panel).querySelector('button[aria-label="About partial results"]'); assert.ok(trigger, 'expected an info button beside the partial badge'); assert.equal(trigger.tagName, 'BUTTON'); assert.notEqual(trigger.tabIndex, -1, 'keyboard focusable'); @@ -2844,15 +2841,13 @@ test('Members lays out a finished import as one summary line with its history be const panel = h.app.tabMembers(); await settle(); const card = memberImport(panel); - assert.ok(!card.closest('.sf-card'), 'a finished one-time import does not lead the page as a card'); assert.equal(textOf(memberCoverage(panel)), 'Member list: up to date'); assert.ok(memberCoverage(panel).compareDocumentPosition(card) & h.window.Node.DOCUMENT_POSITION_FOLLOWING); // One line: counts, completion date and duration. const summary = memberImportStatus(panel); assert.match(textOf(summary), /^Imported 10,539 members and 192 bans on .+ \(49 min\)$/); assert.equal(summary.querySelector('time').getAttribute('datetime'), new Date(finishedAt).toISOString()); - // No Complete badge, full progress bar or "100% complete" triple. - assert.ok(!card.querySelector('.badge'), 'no Complete badge'); + // No Complete status pill, full progress bar or "100% complete" triple. assert.ok(!panel.querySelector('progress'), 'no full progress bar'); assert.doesNotMatch(textOf(panel), /100%|Complete\b/); // Phase rows, totals and secondary times sit in a native disclosure that starts collapsed. @@ -2888,7 +2883,7 @@ test('Members lays out a finished import as one summary line with its history be fire(findNode(panel, n => n.localName === 'button' && n.getAttribute('aria-label') === 'View history'), 'click'); await settle(); const history = findNode(panel, n => n.getAttribute?.('aria-label') === 'Member history'); - assert.deepEqual([...history.children].map(n => n.className), ['sf-card-body']); + assert.ok(history && textOf(history).length > 0, 'Member history renders content'); }); test('Members keeps a running import compact but visible outside Details', async () => { @@ -2938,7 +2933,8 @@ for (const [status, reason, label, control] of [ assert.equal(textOf(memberImportStatus(panel)), `${label}Initial member import · Stage: Current bans${reason}`); assert.equal(details.contains(memberImportStatus(panel)), false); assert.match(visible, new RegExp(reason)); - assert.ok(card.querySelector('.badge') && !card.querySelector('.badge').closest('details'), 'state badge stays visible'); + const stateLabel = findNode(memberImportStatus(panel), n => textOf(n) === label && n.children.length === 0); + assert.ok(stateLabel && !details.contains(stateLabel), 'state label stays visible outside Details'); assert.ok(card.querySelector('progress') && !details.contains(card.querySelector('progress'))); assert.ok([...card.querySelectorAll('button')].some(n => textOf(n) === control && !details.contains(n))); }); @@ -2951,8 +2947,7 @@ test('Members describes a server that was never imported in one line with no emp const panel = memberView(h); await settle(); const card = memberImport(panel); - assert.ok(!card.closest('.sf-card'), 'no import card'); - assert.ok(!card.querySelector('details, table, dl, progress, .sf-card'), 'nothing to expand before a first run exists'); + assert.ok(!card.querySelector('details, table, dl, progress'), 'nothing to expand before a first run exists'); assert.equal(textOf(memberImportStatus(panel)), 'The bot will create the first import job when it is online. Import controls become available after that job exists.'); assert.match(textOf(memberCoverage(panel)), /^Member list: partial/); @@ -5955,19 +5950,19 @@ test('wrapped navigation leaves content and picker options reachable at enlarged const densityProbe = `(async () => { const wait = () => new Promise(resolve => setTimeout(resolve, 50)); const frame = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); - for (let i = 0; i < 200 && !document.querySelector('.dashboard-stats'); i++) await wait(); - for (let i = 0; i < 200 && /Loading/.test(document.querySelector('.dashboard-stats').textContent); i++) await wait(); + for (let i = 0; i < 200 && !document.querySelector('[data-testid="dashboard-stats"]'); i++) await wait(); + for (let i = 0; i < 200 && /Loading/.test(document.querySelector('[data-testid="dashboard-stats"]').textContent); i++) await wait(); await frame(); const rect = element => { const { left, top, bottom, width, height } = element.getBoundingClientRect(); return { left, top, bottom, width, height }; }; - const statBoxes = [...document.querySelectorAll('.dashboard-stats .stat')].map(rect); + const statBoxes = [...document.querySelectorAll('[data-testid="dashboard-stats"] [data-testid="dashboard-stat"]')].map(rect); const lastStatTop = Math.max(...statBoxes.map(stat => stat.top)); const result = { theme: document.documentElement.dataset.theme, viewport: innerHeight, scrollY, rootFont: parseFloat(getComputedStyle(document.documentElement).fontSize), bodyFont: parseFloat(getComputedStyle(document.body).fontSize), - statFont: parseFloat(getComputedStyle(document.querySelector('.stat-value')).fontSize), + statFont: parseFloat(getComputedStyle(document.querySelector('[data-testid="dashboard-stat-value"]')).fontSize), pageOverflow: document.documentElement.scrollWidth - innerWidth, workspace: rect(document.querySelector('.workspace')), content: rect(document.querySelector('#content')), - stats: rect(document.querySelector('.dashboard-stats')), header: rect(document.querySelector('.page-header')), + stats: rect(document.querySelector('[data-testid="dashboard-stats"]')), header: rect(document.querySelector('.page-header')), statRows: new Set(statBoxes.map(stat => Math.round(stat.top))).size, lastStatWidths: statBoxes.filter(stat => stat.top === lastStatTop).map(stat => stat.width), gettingStarted: Boolean(document.querySelector('.getting-started')), @@ -10910,9 +10905,10 @@ test('Badwords shows what is handled automatically, an entry counter, the action const content = h.nodes.get('#content'); const auto = content.querySelector('[aria-label="Words and phrases handle automatically"]'); assert.match(auto.textContent, /^Words and phrases handle automatically:/); - assert.deepEqual([...auto.querySelectorAll('.badge')].map((chip) => chip.textContent), + const autoItems = [...auto.querySelectorAll('li')].slice(1); + assert.deepEqual(autoItems.map((chip) => chip.textContent), ['Upper and lower case', 'Accents', 'Hidden characters', 'Spacing', 'Leetspeak', 'Whole words']); - for (const chip of auto.querySelectorAll('.badge')) assert.ok(chip.title, `${chip.textContent} explains itself on hover`); + for (const chip of autoItems) assert.ok(chip.title, `${chip.textContent} explains itself on hover`); assert.equal(textOf(content.querySelector('.list-status .rule-summary')), 'When a message matches your Badwords list: Strike 1: Warn · Strike 3: Timeout 10 min · Strike 5: Ban (delete last hour).'); assert.match(content.textContent, /No words yet\. Add some above, for example: scam, free nitro/); @@ -11024,10 +11020,10 @@ test('list pages show status, add form, list, then tester or preview, with searc const sections = [...page.querySelectorAll('.list-card')].map((card) => order.find((name) => card.classList.contains(name))); assert.deepEqual(sections, order, tab); assert.equal(textOf(page.querySelector('.list-status .rule-summary')), summary, tab); - const editButton = page.querySelector('.list-status .mantine-Button-root'); + const editButton = page.querySelector('.list-status button'); assert.equal(editButton.textContent, 'Edit actions & exemptions', tab); assert.equal(editButton.getAttribute('data-size'), 'md', `${tab}: normal-size edit button`); - assert.ok(page.querySelector('.list-add .list-form-submit .mantine-Button-root[data-variant="filled"]'), `${tab}: Add is the primary button under the entry`); + assert.ok(page.querySelector('.list-add .list-form-submit button[data-variant="filled"]'), `${tab}: Add is the primary button under the entry`); assert.ok(page.querySelector('.list-table input[data-search]'), `${tab}: search once the list has items`); const tester = page.querySelector('details.list-extra'); if (tester) assert.equal(tester.open, false, `${tab}: the tester or preview starts collapsed`); @@ -11275,7 +11271,7 @@ test('known spam acknowledged Global add keeps Global selected when the refresh assert.match(content().textContent, /Configuration unavailable/); await fire([...content().querySelectorAll('button')].find(b => b.textContent === 'Retry'), 'click'); assert.equal(scopeSelect().value, 'global', 'the acknowledged scope stays selected after the refresh recovers'); - assert.equal(content().querySelector('.sf-card [role="alert"]'), null, 'an acknowledged add is not reported as unconfirmed'); + assert.equal(content().querySelector('.list-add [role="alert"]'), null, 'an acknowledged add is not reported as unconfirmed'); assert.deepEqual(Object.keys(h.app.currentDrafts()), []); assert.equal(h.app.isDirty(), false); }); @@ -11299,7 +11295,7 @@ test('known spam add failure stays with its draft without claiming an outcome th const sample = content().querySelector('textarea'); sample.value = 'Join our stocks community'; await fire(sample, 'input'); const add = label => fire([...content().querySelectorAll('button')].find(b => b.textContent === label), 'click'); - const alert = () => content().querySelector('.sf-card [role="alert"]')?.textContent || ''; + const alert = () => content().querySelector('.list-add [role="alert"]')?.textContent || ''; await add('Add sample'); assert.equal(alert(), 'Sample not confirmed as added: known spam entry already exists'); assert.equal(h.app.currentDrafts()['known-spam:sample'].value, 'Join our stocks community'); @@ -13744,8 +13740,9 @@ test('the Web UI draws SVG icons, never emoji or glyph icons', () => { }); // #653: display reads render this tab's cached copy at once, then revalidate. -const statValue = (h, label) => [...h.nodes.get('#content').querySelectorAll('.dashboard-stats > .stat')] - .find((tile) => tile.querySelector('.stat-title').textContent.startsWith(label)).querySelector('.stat-value').textContent; +const statValue = (h, label) => [...h.nodes.get('#content').querySelectorAll('[data-testid="dashboard-stat"]')] + .find((tile) => tile.querySelector('[data-testid="dashboard-stat-label"]').textContent.startsWith(label)) + .querySelector('[data-testid="dashboard-stat-value"]').textContent; const lastUpdated = (h) => h.nodes.get('#content').querySelector('.last-updated')?.textContent ?? null; const dashboardCacheConfig = () => ({ ...configuredDashboard(), enrollment_id: 'membership' }); const readCacheKeys = (session) => [...session.keys()].filter((key) => key.startsWith('jmodguard.read:')); @@ -14605,11 +14602,11 @@ function assertDecorativeIcon(icon, name, intent, where) { } // Returns the setup links shown; asserts every tile and link icon on a rendered dashboard. function assertDashboardIcons(dashboard, name) { - const tiles = [...dashboard.querySelectorAll('.dashboard-stats > .stat')]; + const tiles = [...dashboard.querySelectorAll('[data-testid="dashboard-stat"]')]; assert.equal(tiles.length, DASHBOARD_TILES.length, `${name}: every tile renders`); for (const [index, tile] of tiles.entries()) { const [label, , icon, intent] = DASHBOARD_TILES[index]; - const title = tile.querySelector('.stat-title'); + const title = tile.querySelector('[data-testid="dashboard-stat-label"]'); assert.ok(title.textContent.startsWith(label), `${name}: tile ${index + 1} keeps its label ${label}`); const svgs = tile.querySelectorAll('svg'); assert.equal(svgs.length, 1, `${name}: ${label} has one icon`); @@ -15075,7 +15072,7 @@ test('Platform analytics shows every metric together with changes, names, icons assert.equal(page.querySelector('[aria-label="Last 30 days"]').getAttribute('aria-pressed'), 'true'); // No single-metric toggle, no old stat cards, no explanatory paragraph. assert.equal(page.querySelector('[role="group"][aria-label="Trend metric"]'), null); - assert.equal(page.querySelector('.stat'), null); + assert.equal(page.querySelector('[data-testid="dashboard-stat"]'), null); assert.doesNotMatch(textOf(page), /Fleet-wide moderation and membership trends|Per-server rows show guild IDs/); const platformTip = await openTooltip(page.querySelector('.page-header .tooltip-trigger')); assert.match(platformTip.textContent, /previous period of the same length/); @@ -15266,34 +15263,6 @@ test('Platform analytics shows history while directory totals are delayed and re assert.equal(page.querySelector('#platform-members-status'), null); }); -test('Platform analytics uses the combined response on a legacy API', async () => { - const calls = []; - const rejected = (status, message) => ({ - ok: false, status, headers: { get: () => null }, text: async () => message, - }); - const h = ownerHarness(async (url) => { - calls.push(url); - if (url === platformMembersPath) return rejected(404, ''); - const query = new URL(url, 'https://ui.example.test').searchParams; - if (query.has('include_members')) return rejected(400, 'unknown field include_members'); - return response(platformSnapshot(Number(query.get('days')))); - }); - h.app.navigate('platform-analytics'); - await settle(); - await settle(); - const page = platformPage(h); - assert.equal(kpiValue(page, 'Warnings'), '5'); - assert.equal(kpiValue(page, 'Members'), '40'); - assert.equal(page.querySelector('#platform-analytics-status'), null); - await fire(page.querySelector('[aria-label="Last 7 days"]'), 'click'); - await fire(page.querySelector('#refresh-platform-analytics'), 'click'); - assert.deepEqual(calls, [ - platformHistoryPath(30), platformMembersPath, - '/api/platform/analytics?days=30', '/api/platform/analytics?days=7', '/api/platform/analytics?days=7', - ]); - assert.equal(kpiValue(page, 'Members'), '40'); -}); - test('Platform analytics distinguishes a server outside the saved directory snapshot from a failed read', async () => { let memberReads = 0; let historyFails = false;