You are a constitutional council ranking individual git commits for ownership allocation. Compare these two commits. Decide which contributed more lasting value to the project. Judge substance, not spectacle: - Prefer correct, lasting design and real bugfixes over churn, formatting, renames, or generated noise. - Prefer clarity and necessity over sheer line count. A small precise change can beat a large diffuse one. - Do not favor a side merely because its patch is longer or noisier. - Weight what the change does for the project, not the contributor's name. Return ONLY a JSON object: {"winner": "A" or "B", "ratio": "N:M", "explanation": "..."} The explanation must cite concrete differences in the patches (1-3 sentences). Side A — contributor: tommy-mor Side A — commit message: [52f5c51c] Add Reddit OAuth linking and make UUID the only account identity. OAuth providers only attach to a session UUID (first link creates the principal); linked providers stay private on the account page. Co-authored-by: Cursor Side A — unified diff (full patch): diff --git a/AGENTS.md b/AGENTS.md index 6e0fd8ebb65d665c9c1438e3275971d62b98fd95..e9cc3173dbeb21ad0fc090ca7b407b027c7820a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,8 +35,11 @@ Environment variables (defaults in `server/src/state.rs`): - `SORTER2_DATA_DIR` — default `./data` (created on startup) - `SORTER2_EVENT_LOG` — default `{data_dir}/events.jsonl` - `SORTER2_BASE_URL` — public origin (also drives Secure cookies when `https://`) -- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth (optional; login disabled if unset) -- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` (tests only) +- `GITHUB_CLIENT_ID` / `GITHUB_CLIENT_SECRET` — GitHub OAuth linking (optional) +- `REDDIT_CLIENT_ID` / `REDDIT_CLIENT_SECRET` (or `REDDIT_APP_*`) — Reddit API import + OAuth linking (optional) +- `SORTER2_ALLOW_MOCK_OAUTH=1` — allow `mock_user` on `/auth/github` and `/auth/reddit` (tests only) + +Identity: UUID is canonical. OAuth providers only *link* to a UUID (first link creates the principal). Linked providers are private to the account owner. Health check: `GET /healthz` → `ok`. diff --git a/server/src/auth/mod.rs b/server/src/auth/mod.rs index 5906f93b13853421e96a3c37bc9d8202a47842bf..c706ae8045a811e5941f5f6c72da88f42a403a82 100644 --- a/server/src/auth/mod.rs +++ b/server/src/auth/mod.rs @@ -1,4 +1,8 @@ -//! GitHub OAuth login, session cookies, and vote actor resolution. +//! OAuth linking, session cookies, and vote actor resolution. +//! +//! Canonical identity is a UUID. OAuth providers only *link* to that UUID +//! (first link creates the principal; later links attach while logged in). +//! Which providers are linked is private to the account owner. pub mod config; pub mod identity; @@ -22,7 +26,9 @@ use crate::{ form_template::template_json_compact, html::layout, state::AppState, - storage_schema::{oauth_link_owner, pseudonym_owner, Store, StoreFields}, + storage_schema::{ + linked_providers_for_uuid, oauth_link_owner, pseudonym_owner, Store, StoreFields, + }, ui_action::UI_RPC_FIELD, }; @@ -53,10 +59,12 @@ fn new_actor_uuid() -> String { pub struct LoginQuery { #[serde(default)] pub return_to: Option, + #[serde(default)] + pub error: Option, } #[derive(Debug, Deserialize)] -pub struct GitHubStartQuery { +pub struct OAuthStartQuery { #[serde(default)] pub return_to: Option, #[serde(default)] @@ -72,15 +80,22 @@ fn return_from_query_or_jar(jar: &CookieJar, query: Option<&str>) -> String { .unwrap_or_else(|| "/".to_string()) } -fn oauth_providers(base_url: &str, return_to: &str) -> Vec<(&'static str, String)> { +/// Available OAuth link targets: `(provider_key, label, start_href)`. +fn oauth_providers(base_url: &str, return_to: &str) -> Vec<(&'static str, &'static str, String)> { let mut out = Vec::new(); + let enc = urlencoding::encode(return_to); if oauth::GitHubConfig::from_env(base_url).is_some() { out.push(( - "GitHub", - format!( - "/auth/github?return_to={}", - urlencoding::encode(return_to) - ), + "github", + oauth::provider_label("github"), + format!("/auth/github?return_to={enc}"), + )); + } + if oauth::RedditConfig::from_env(base_url).is_some() { + out.push(( + "reddit", + oauth::provider_label("reddit"), + format!("/auth/reddit?return_to={enc}"), )); } out @@ -125,23 +140,41 @@ fn alias_claim_forms(return_to: &str, submit_label: &str) -> Result Markup { +fn login_error_message(code: Option<&str>) -> Option<&'static str> { + match code { + Some("oauth_taken") => { + Some("that OAuth account is already linked to a different sorter2 account") + } + Some("oauth_failed") => Some("OAuth failed — try again"), + _ => None, + } +} + +fn signed_out_body( + providers: &[(&str, &str, String)], + error: Option<&str>, +) -> Markup { html! { main class="panel login-page" { section class="login-section" { h1 { "sign in" } - p class="muted" { "link an account to vote under a lasting alias" } + p class="muted" { + "link an OAuth account to create your identity, then claim an alias to vote" + } + @if let Some(msg) = login_error_message(error) { + p class="alias-bad" data-testid="login-error" { (msg) } + } @if providers.is_empty() { p class="muted" { - "OAuth is not configured. Set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET." + "OAuth is not configured. Set GitHub and/or Reddit client credentials." } } @else { ul class="oauth-provider-list" { - @for (name, href) in providers { + @for (key, label, href) in providers { li { a href=(href) class="btn-primary oauth-provider" - data-testid=(format!("oauth-{}", name.to_lowercase())) { - (format!("Continue with {name}")) + data-testid=(format!("oauth-{key}")) { + (format!("Link {label}")) } } } @@ -156,7 +189,10 @@ fn signed_out_body(providers: &[(&str, String)]) -> Markup { fn account_body( actor: &session::SessionActor, aliases: &[String], - providers: &[(&str, String)], + // Provider keys already linked to this UUID (private). + linked: &[String], + // Providers available to link: not yet attached. + unlinkable: &[(&str, &str, String)], claim_forms: Markup, ) -> Markup { let current = actor.pseudonym.trim(); @@ -212,16 +248,29 @@ fn account_body( (claim_forms) } - @if !providers.is_empty() { - section class="login-section" { - h2 { "linked sign-in" } - p class="muted small" { "sign in again with the same provider to return to this account" } + section class="login-section" { + h2 { "linked sign-in" } + p class="muted small" { + "private to you — linking more providers raises trust weight without publishing which accounts you use" + } + @if linked.is_empty() { + p class="muted" data-testid="linked-providers-empty" { "none yet" } + } @else { + ul class="linked-provider-list" data-testid="linked-providers" { + @for key in linked { + li data-testid=(format!("linked-{key}")) { + (oauth::provider_label(key)) + } + } + } + } + @if !unlinkable.is_empty() { ul class="oauth-provider-list" { - @for (name, href) in providers { + @for (key, label, href) in unlinkable { li { a href=(href) class="btn-secondary oauth-provider" - data-testid=(format!("oauth-relink-{}", name.to_lowercase())) { - (format!("Re-link {name}")) + data-testid=(format!("oauth-link-{key}")) { + (format!("Link {label}")) } } } @@ -243,12 +292,21 @@ fn account_body( fn login_body( session: Option<&session::SessionActor>, aliases: &[String], - providers: &[(&str, String)], + linked: &[String], + providers: &[(&str, &str, String)], claim_forms: Option, + error: Option<&str>, ) -> Markup { match (session, claim_forms) { - (Some(actor), Some(forms)) => account_body(actor, aliases, providers, forms), - _ => signed_out_body(providers), + (Some(actor), Some(forms)) => { + let unlinkable: Vec<_> = providers + .iter() + .filter(|(key, _, _)| !linked.iter().any(|p| p == key)) + .cloned() + .collect(); + account_body(actor, aliases, linked, &unlinkable, forms) + } + _ => signed_out_body(providers, error), } } @@ -268,6 +326,10 @@ pub async fn login_page( .as_ref() .map(|s| alias_list(db, &s.uuid)) .unwrap_or_default(); + let linked = session + .as_ref() + .map(|s| linked_providers_for_uuid(db, &s.uuid).unwrap_or_default()) + .unwrap_or_default(); let providers = oauth_providers(&base_url_from_env(state.cfg.port), &return_to); let claim_forms = if session.is_some() { @@ -282,7 +344,14 @@ pub async fn login_page( } else { "login · sorter2" }, - login_body(session.as_ref(), &aliases, &providers, claim_forms), + login_body( + session.as_ref(), + &aliases, + &linked, + &providers, + claim_forms, + query.error.as_deref(), + ), state.views.get_views("/login"), session .as_ref() @@ -302,7 +371,6 @@ pub async fn alias_page( let db = state.projection_store.db(); let session = session::load_valid_session(db, &session_id).ok_or(StatusCode::UNAUTHORIZED)?; if session::session_has_pseudonym(&session) { - // Already onboarded — manage aliases on the account page. return Ok(Redirect::to("/login").into_response()); } @@ -331,7 +399,7 @@ pub async fn alias_page( pub async fn github_start( State(state): State, jar: CookieJar, - Query(query): Query, + Query(query): Query, ) -> Result { let cfg = oauth::GitHubConfig::from_env(&base_url_from_env(state.cfg.port)) .ok_or(StatusCode::SERVICE_UNAVAILABLE)?; @@ -342,7 +410,28 @@ pub async fn github_start( } else { None }; - let url = oauth::authorize_url(&cfg, &state_token, mock_user); + let url = oauth::github_authorize_url(&cfg, &state_token, mock_user); + let jar = jar + .add(session::oauth_state_cookie_value(&state_token)) + .add(session::auth_return_cookie_value(&return_to)); + Ok((jar, Redirect::temporary(&url)).into_response()) +} + +pub async fn reddit_start( + State(state): State, + jar: CookieJar, + Query(query): Query, +) -> Result { + let cfg = oauth::RedditConfig::from_env(&base_url_from_env(state.cfg.port)) + .ok_or(StatusCode::SERVICE_UNAVAILABLE)?; + let return_to = return_from_query_or_jar(&jar, query.return_to.as_deref()); + let state_token = session::new_oauth_state(); + let mock_user = if config::mock_oauth_allowed() { + query.mock_user.as_deref() + } else { + None + }; + let url = oauth::reddit_authorize_url(&cfg, &state_token, mock_user); let jar = jar .add(session::oauth_state_cookie_value(&state_token)) .add(session::auth_return_cookie_value(&return_to)); @@ -355,6 +444,13 @@ pub struct OAuthCallbackQuery { pub state: String, } +/// Link `provider:provider_id` to a UUID. +/// +/// - Logged in + new provider → attach to session UUID +/// - Logged in + already ours → no-op +/// - Logged in + owned by someone else → conflict +/// - Logged out + known link → resume that UUID +/// - Logged out + unknown → create principal + first link async fn finish_oauth_login( state: &AppState, jar: CookieJar, @@ -364,11 +460,41 @@ async fn finish_oauth_login( let db = state.projection_store.db(); let return_to = return_from_query_or_jar(&jar, None); - let uuid = match oauth_link_owner(db, provider, &provider_id) - .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? - { - Some(existing) => existing, - None => { + let existing_owner = oauth_link_owner(db, provider, &provider_id) + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let session_uuid = session::session_id_from_jar(&jar) + .as_deref() + .and_then(|id| session::load_valid_session(db, id)) + .map(|s| s.uuid); + let linking_while_logged_in = session_uuid.is_some(); + + let uuid = match (session_uuid, existing_owner) { + (Some(session_uuid), Some(owner)) if owner == session_uuid => session_uuid, + (Some(_), Some(_)) => { + return Ok(( + jar.add(session::clear_oauth_state_cookie()), + "/login?error=oauth_taken".into(), + )); + } + (Some(session_uuid), None) => { + let ts = now_ms(); + state + .append_identity_events(vec![Event::OauthLinked { + uuid: session_uuid.clone(), + provider: provider.to_string(), + provider_id, + ts, + }]) + .await + .map_err(|e| { + tracing::warn!(err = %e, "oauth link append failed"); + StatusCode::INTERNAL_SERVER_ERROR + })?; + session_uuid + } + (None, Some(owner)) => owner, + (None, None) => { let uuid = new_actor_uuid(); let ts = now_ms(); state @@ -409,6 +535,9 @@ async fn finish_oauth_login( "/login/alias?return_to={}", urlencoding::encode(&return_to) ) + } else if linking_while_logged_in { + // Additional link while already in an account → stay on account page. + "/login".to_string() } else { return_to }; @@ -434,22 +563,57 @@ pub async fn github_callback( .build() .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - let token = oauth::exchange_code(&client, &cfg, &query.code) + let token = oauth::github_exchange_code(&client, &cfg, &query.code) .await .map_err(|e| { tracing::warn!(err = %e, "github oauth token exchange failed"); StatusCode::BAD_GATEWAY })?; - let user = oauth::fetch_user(&client, &cfg.api_base, &token) + let user = oauth::github_fetch_user(&client, &cfg.api_base, &token) .await .map_err(|e| { tracing::warn!(err = %e, "github user fetch failed"); StatusCode::BAD_GATEWAY })?; - let provider = "github"; - let provider_id = oauth::provider_id(&user); - let (jar, dest) = finish_oauth_login(&state, jar, provider, provider_id).await?; + let (jar, dest) = + finish_oauth_login(&state, jar, "github", oauth::github_provider_id(&user)).await?; + Ok((jar, Redirect::to(&dest)).into_response()) +} + +pub async fn reddit_callback( + State(state): State, + jar: CookieJar, + Query(query): Query, +) -> Result { + let cfg = oauth::RedditConfig::from_env(&base_url_from_env(state.cfg.port)) + .ok_or(StatusCode::SERVICE_UNAVAILABLE)?; + + let expected_state = session::oauth_state_from_jar(&jar).ok_or(StatusCode::BAD_REQUEST)?; + if expected_state != query.state { + return Err(StatusCode::BAD_REQUEST); + } + + let client = Client::builder() + .timeout(std::time::Duration::from_secs(15)) + .build() + .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + + let token = oauth::reddit_exchange_code(&client, &cfg, &query.code) + .await + .map_err(|e| { + tracing::warn!(err = %e, "reddit oauth token exchange failed"); + StatusCode::BAD_GATEWAY + })?; + let user = oauth::reddit_fetch_user(&client, &cfg, &token) + .await + .map_err(|e| { + tracing::warn!(err = %e, "reddit user fetch failed"); + StatusCode::BAD_GATEWAY + })?; + + let (jar, dest) = + finish_oauth_login(&state, jar, "reddit", oauth::reddit_provider_id(&user)).await?; Ok((jar, Redirect::to(&dest)).into_response()) } diff --git a/server/src/auth/oauth.rs b/server/src/auth/oauth.rs index b80078fee0c5acd905b9125d29454e46c4e0d066..369b1527d9032cf312a07819279e0f988ef4a36e 100644 --- a/server/src/auth/oauth.rs +++ b/server/src/auth/oauth.rs @@ -1,8 +1,15 @@ -//! GitHub OAuth (raw reqwest, same style as reddit.rs). +//! OAuth providers (GitHub + Reddit). Provider accounts only *link* to a UUID; +//! the UUID is the canonical identity. Which providers are linked is private. use reqwest::Client; use serde::Deserialize; +use crate::reddit::{ + default_user_agent, reddit_oauth_api_base, reddit_oauth_token_base, +}; + +// ── GitHub ────────────────────────────────────────────────────────────────── + #[derive(Debug, Clone)] pub struct GitHubConfig { pub client_id: String, @@ -40,7 +47,7 @@ impl GitHubConfig { } #[derive(Debug, Deserialize)] -struct TokenResponse { +struct GitHubTokenResponse { access_token: String, } @@ -50,7 +57,7 @@ pub struct GitHubUser { pub login: String, } -pub fn authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) -> String { +pub fn github_authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) -> String { let mut url = format!( "{}/login/oauth/authorize?client_id={}&redirect_uri={}&scope=read:user&state={}", cfg.oauth_base.trim_end_matches('/'), @@ -65,7 +72,7 @@ pub fn authorize_url(cfg: &GitHubConfig, state: &str, mock_user: Option<&str>) - url } -pub async fn exchange_code( +pub async fn github_exchange_code( client: &Client, cfg: &GitHubConfig, code: &str, @@ -90,14 +97,14 @@ pub async fn exchange_code( return Err(format!("github token HTTP {}", resp.status())); } - let body: TokenResponse = resp + let body: GitHubTokenResponse = resp .json() .await .map_err(|e| format!("github token parse failed: {e}"))?; Ok(body.access_token) } -pub async fn fetch_user( +pub async fn github_fetch_user( client: &Client, api_base: &str, access_token: &str, @@ -120,10 +127,149 @@ pub async fn fetch_user( .map_err(|e| format!("github user parse failed: {e}")) } -pub fn provider_id(user: &GitHubUser) -> String { +pub fn github_provider_id(user: &GitHubUser) -> String { user.id.to_string() } +// ── Reddit ────────────────────────────────────────────────────────────────── + +#[derive(Debug, Clone)] +pub struct RedditConfig { + pub client_id: String, + pub client_secret: String, + pub redirect_uri: String, + /// Host for `/api/v1/authorize` (www.reddit.com in production). + pub authorize_base: String, + /// Host for `POST /api/v1/access_token`. + pub token_base: String, + /// Host for bearer `GET /api/v1/me` (oauth.reddit.com). + pub api_base: String, + pub user_agent: String, +} + +/// Authorize page base; defaults to the same host as token POSTs. +pub fn reddit_authorize_base() -> String { + std::env::var("REDDIT_OAUTH_AUTHORIZE_BASE") + .or_else(|_| std::env::var("REDDIT_OAUTH_BASE")) + .unwrap_or_else(|_| "https://www.reddit.com".into()) +} + +impl RedditConfig { + pub fn from_env(base_url: &str) -> Option { + let client_id = std::env::var("REDDIT_CLIENT_ID") + .or_else(|_| std::env::var("REDDIT_APP_ID")) + .ok()?; + let client_secret = std::env::var("REDDIT_CLIENT_SECRET") + .or_else(|_| std::env::var("REDDIT_APP_SECRET")) + .ok()?; + if client_id.is_empty() || client_secret.is_empty() { + return None; + } + let base = base_url.trim_end_matches('/'); + Some(Self { + client_id, + client_secret, + redirect_uri: format!("{base}/auth/reddit/callback"), + authorize_base: reddit_authorize_base(), + token_base: reddit_oauth_token_base(), + api_base: reddit_oauth_api_base(), + user_agent: default_user_agent(), + }) + } +} + +#[derive(Debug, Deserialize)] +struct RedditTokenResponse { + access_token: String, +} + +#[derive(Debug, Deserialize)] +pub struct RedditUser { + /// Stable id (`t2_…`); never use `name` as identity. + pub id: String, + pub name: String, +} + +pub fn reddit_authorize_url(cfg: &RedditConfig, state: &str, mock_user: Option<&str>) -> String { + let mut url = format!( + "{}/api/v1/authorize?client_id={}&response_type=code&state={}&redirect_uri={}&duration=temporary&scope=identity", + cfg.authorize_base.trim_end_matches('/'), + urlencoding::encode(&cfg.client_id), + urlencoding::encode(state), + urlencoding::encode(&cfg.redirect_uri), + ); + if let Some(user) = mock_user { + url.push_str("&mock_user="); + url.push_str(&urlencoding::encode(user)); + } + url +} + +pub async fn reddit_exchange_code( + client: &Client, + cfg: &RedditConfig, + code: &str, +) -> Result { + let resp = client + .post(format!( + "{}/api/v1/access_token", + cfg.token_base.trim_end_matches('/') + )) + .header("User-Agent", &cfg.user_agent) + .basic_auth(&cfg.client_id, Some(&cfg.client_secret)) + .form(&[ + ("grant_type", "authorization_code"), + ("code", code), + ("redirect_uri", cfg.redirect_uri.as_str()), + ]) + .send() + .await + .map_err(|e| format!("reddit token request failed: {e}"))?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + return Err(format!("reddit token HTTP {status}: {body}")); + } + + let body: RedditTokenResponse = resp + .json() + .await + .map_err(|e| format!("reddit token parse failed: {e}"))?; + Ok(body.access_token) +} + +pub async fn reddit_fetch_user( + client: &Client, + cfg: &RedditConfig, + access_token: &str, +) -> Result { + let resp = client + .get(format!( + "{}/api/v1/me", + cfg.api_base.trim_end_matches('/') + )) + .header("User-Agent", &cfg.user_agent) + .bearer_auth(access_token) + .send() + .await + .map_err(|e| format!("reddit user request failed: {e}"))?; + + if !resp.status().is_success() { + return Err(format!("reddit user HTTP {}", resp.status())); + } + + resp.json() + .await + .map_err(|e| format!("reddit user parse failed: {e}")) +} + +pub fn reddit_provider_id(user: &RedditUser) -> String { + user.id.clone() +} + +// ── Shared helpers ────────────────────────────────────────────────────────── + pub fn validate_pseudonym(raw: &str) -> Result { let trimmed = raw.trim(); if trimmed.is_empty() { @@ -144,3 +290,12 @@ pub fn validate_pseudonym(raw: &str) -> Result { pub fn sanitize_pseudonym(login: &str) -> String { validate_pseudonym(login).unwrap_or_else(|_| "user".to_string()) } + +/// Display name for a provider key (`github` → `GitHub`). Never show provider ids. +pub fn provider_label(provider: &str) -> &'static str { + match provider { + "github" => "GitHub", + "reddit" => "Reddit", + _ => "OAuth", + } +} diff --git a/server/src/lib.rs b/server/src/lib.rs index 84f2565b105fb302241b949af64bd5e49916eab2..0d948af1457504fdbd34d0b14261f65ac58da0ec 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -47,6 +47,8 @@ pub fn create_app(state: AppState) -> Router { .route("/login/alias", get(crate::auth::alias_page)) .route("/auth/github", get(crate::auth::github_start)) .route("/auth/github/callback", get(crate::auth::github_callback)) + .route("/auth/reddit", get(crate::auth::reddit_start)) + .route("/auth/reddit/callback", get(crate::auth::reddit_callback)) .route("/auth/logout", post(crate::auth::logout)) .route("/auth/switch", post(crate::auth::switch_pseudonym)) .route("/ui", post(crate::api::ui_html::post_ui_html)) diff --git a/server/src/projection_apply.rs b/server/src/projection_apply.rs index 4fb4b48ee0a53b7f673fae0c9731eed5acc33332..f50458c2ff3c447a3cfd28adb298e6883a2da4e9 100644 --- a/server/src/projection_apply.rs +++ b/server/src/projection_apply.rs @@ -4,6 +4,8 @@ //! child links, recent-vote appends) plus a cursor advance, all committed in //! one atomic `DisableWal` batch. +use std::collections::HashMap; + use crate::{ event_log::EventLogError, events::{Event, EventRecord}, @@ -44,6 +46,8 @@ pub fn apply_records( let db = projection_store.db(); let mut batch = db.batch(); let mut last_seq = 0u64; + // Weight reads must see earlier writes in this same batch. + let mut pending_weights: HashMap = HashMap::new(); for record in records { match &record.event { @@ -85,6 +89,7 @@ pub fn apply_records( ensure_path_writes(&mut batch, &parsed); } Event::PrincipalCreated { uuid, .. } => { + pending_weights.insert(uuid.clone(), BASE_TRUST_WEIGHT); batch.write( Store::root() .user_weights() @@ -112,17 +117,25 @@ pub fn apply_records( } } else { batch.write(Store::root().oauth_links().key(&link_key).set(uuid)); - let current = Store::root() - .user_weights() - .key(&uuid.clone()) - .get(db) - .map_err(|e| EventLogError::Apply(e.to_string()))? + let current = pending_weights + .get(uuid) + .copied() + .or_else(|| { + Store::root() + .user_weights() + .key(&uuid.clone()) + .get(db) + .ok() + .flatten() + }) .unwrap_or(BASE_TRUST_WEIGHT); + let next = trust_weight_after_link(current); + pending_weights.insert(uuid.clone(), next); batch.write( Store::root() .user_weights() .key(&uuid.clone()) - .set(&trust_weight_after_link(current)), + .set(&next), ); } } @@ -205,6 +218,15 @@ mod tests { ), record( 3, + Event::OauthLinked { + uuid: uuid.into(), + provider: "reddit".into(), + provider_id: "t2_abc".into(), + ts, + }, + ), + record( + 4, Event::PseudonymClaimed { uuid: uuid.into(), pseudonym: "octocat".into(), @@ -219,8 +241,12 @@ mod tests { oauth_link_owner(store.db(), "github", "42").unwrap(), Some(uuid.to_string()) ); + assert_eq!( + crate::storage_schema::linked_providers_for_uuid(store.db(), uuid).unwrap(), + vec!["github".to_string(), "reddit".to_string()] + ); assert_eq!(resolve_actor_uuid(store.db(), "octocat").unwrap(), uuid); - assert_eq!(user_trust_weight(store.db(), uuid).unwrap(), 1.5); + assert_eq!(user_trust_weight(store.db(), uuid).unwrap(), 2.0); let aliases = Store::root() .user_pseudonyms() .key(&uuid.to_string()) diff --git a/server/src/storage_schema.rs b/server/src/storage_schema.rs index b942810afd96d3bf01b7765718303a39be4ef8d2..dac6f8e6080e3f5683c24dbb8861f5a981d456c4 100644 --- a/server/src/storage_schema.rs +++ b/server/src/storage_schema.rs @@ -103,6 +103,25 @@ pub fn oauth_link_owner(db: &Db, provider: &str, provider_id: &str) -> durable:: .get(db) } +/// Provider names linked to a UUID (`github`, `reddit`, …). Private — for the +/// account owner's page only; never expose which providers are linked publicly. +pub fn linked_providers_for_uuid(db: &Db, uuid: &str) -> durable::Result> { + let mut providers = Vec::new(); + for (key, owner) in Store::root().oauth_links().iter(db)? { + if owner != uuid { + continue; + } + let Some((provider, _)) = key.split_once(':') else { + continue; + }; + if !providers.iter().any(|p| p == provider) { + providers.push(provider.to_string()); + } + } + providers.sort(); + Ok(providers) +} + pub const RECENT_VOTES_CAP: u64 = 200; fn id_key(id: &ItemId) -> String { diff --git a/test/support/harness.clj b/test/support/harness.clj index 4505ece5aa193e826ca61c52f1467d252080d66b..741024aab1d14269e225791189633287980ae2e4 100644 --- a/test/support/harness.clj +++ b/test/support/harness.clj @@ -48,12 +48,15 @@ "GITHUB_CLIENT_SECRET" "test-secret" "GITHUB_OAUTH_BASE" (str "http://127.0.0.1:" oauth-port) "GITHUB_API_BASE" (str "http://127.0.0.1:" oauth-port) + ;; Reddit import fixtures + Reddit OAuth on reddit-port. "REDDIT_API_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_CLIENT_ID" "test-reddit" + "REDDIT_CLIENT_SECRET" "test-reddit-secret" "REDDIT_OAUTH_BASE" (str "http://127.0.0.1:" reddit-port) - "REDDIT_CLIENT_ID" "" - "REDDIT_CLIENT_SECRET" "" - "REDDIT_APP_ID" "" - "REDDIT_APP_SECRET" ""})) + "REDDIT_OAUTH_AUTHORIZE_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_OAUTH_TOKEN_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_OAUTH_API_BASE" (str "http://127.0.0.1:" reddit-port) + "REDDIT_USER_AGENT" "web:sorter2-test:v0 (by /u/test)"})) (defn with-auth-servers "Start mock Reddit + mock OAuth + release sorter2-server. diff --git a/test/support/mock_oauth.clj b/test/support/mock_oauth.clj index 909d7a7be8b159ea54a122d69c46af3db3318118..5ba7e9be3cf6d2226648e9609a09ed45f306930f 100644 --- a/test/support/mock_oauth.clj +++ b/test/support/mock_oauth.clj @@ -1,5 +1,5 @@ (ns test.support.mock-oauth - "In-process HTTP stub for GitHub OAuth (authorize, token, /user)." + "In-process HTTP stub for GitHub + Reddit OAuth (authorize, token, user)." (:require [clojure.string :as str]) (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange] [java.net InetSocketAddress URLDecoder])) @@ -12,11 +12,14 @@ (URLDecoder/decode (or v "") "UTF-8")))) (str/split query #"&")))) -(defn- parse-mock-user [raw] +(defn- parse-mock-user + "GitHub-style `id:login` (numeric id). Reddit-style `t2_xxx:name`." + [raw] (let [s (or raw "1002:newbie") [id login] (str/split s #":" 2)] - {:id (Long/parseLong id) - :login (or login "newbie")})) + {:id id + :login (or login "newbie") + :numeric? (re-matches #"\d+" id)})) (defn- send-json [^HttpExchange ex status body] (let [bytes (.getBytes body "UTF-8")] @@ -31,9 +34,10 @@ (.sendResponseHeaders ex 302 -1) (.close (.getResponseBody ex))) -(defn- read-form-code [^HttpExchange ex] +(defn- read-form [^HttpExchange ex] (let [body (slurp (.getInputStream ex))] - (query-param body "code"))) + {:code (query-param body "code") + :grant (query-param body "grant_type")})) (defn- bearer-token [^HttpExchange ex] (some-> (.getRequestHeaders ex) @@ -44,8 +48,18 @@ (when (str/starts-with? token "mock:") (parse-mock-user (subs token 5)))) +(defn- authorize-redirect [exchange query] + (let [redirect-uri (query-param query "redirect_uri") + state (query-param query "state") + mock-user (query-param query "mock_user") + user (parse-mock-user mock-user) + code (str "mock:" (:id user) ":" (:login user)) + loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") + "&state=" (java.net.URLEncoder/encode state "UTF-8"))] + (send-redirect exchange loc))) + (defn start-mock-oauth - "Start mock GitHub OAuth on `port`. Returns a zero-arg `stop` function." + "Start mock GitHub + Reddit OAuth on `port`. Returns a zero-arg `stop` function." [port] (let [server (HttpServer/create (InetSocketAddress. "127.0.0.1" port) 0) handler @@ -53,28 +67,45 @@ (handle [^HttpExchange exchange] (let [uri (.getRequestURI exchange) path (.getPath uri) - query (.getQuery uri)] + query (.getQuery uri) + method (.getRequestMethod exchange)] (cond + ;; GitHub authorize (str/ends-with? path "/login/oauth/authorize") - (let [redirect-uri (query-param query "redirect_uri") - state (query-param query "state") - mock-user (query-param query "mock_user") - user (parse-mock-user mock-user) - code (str "mock:" (:id user) ":" (:login user)) - loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") - "&state=" (java.net.URLEncoder/encode state "UTF-8"))] - (send-redirect exchange loc)) + (authorize-redirect exchange query) + + ;; Reddit authorize + (str/ends-with? path "/api/v1/authorize") + (authorize-redirect exchange query) - (str/ends-with? path "/login/oauth/access_token") - (let [code (or (read-form-code exchange) "mock:1002:newbie")] + ;; GitHub token + (and (= method "POST") (str/ends-with? path "/login/oauth/access_token")) + (let [code (or (:code (read-form exchange)) "mock:1002:newbie")] (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\"}"))) + ;; Reddit token (client_credentials for import + authorization_code for login) + (and (= method "POST") (str/ends-with? path "/api/v1/access_token")) + (let [form (read-form exchange) + grant (or (:grant form) "") + code (or (:code form) "mock:t2_test:redditor")] + (if (= grant "client_credentials") + (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}") + (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}")))) + + ;; GitHub user (= path "/user") (let [token (bearer-token exchange) - user (or (parse-token-user token) {:id 1002 :login "newbie"})] + user (or (parse-token-user token) {:id "1002" :login "newbie" :numeric? true})] (send-json exchange 200 (str "{\"id\":" (:id user) ",\"login\":\"" (:login user) "\"}"))) + ;; Reddit /api/v1/me + (str/ends-with? path "/api/v1/me") + (let [token (bearer-token exchange) + user (or (parse-token-user token) {:id "t2_test" :login "redditor"})] + (send-json exchange 200 + (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}"))) + :else (send-json exchange 404 "{\"error\":\"not found\"}")))))] (.createContext server "/" handler) diff --git a/test/support/mock_reddit.clj b/test/support/mock_reddit.clj index 5efa92db3e1f79b8f423a2f1adcbda959123c1ad..a630cf0938722193e9af88382d60e777ff371be4 100644 --- a/test/support/mock_reddit.clj +++ b/test/support/mock_reddit.clj @@ -1,14 +1,56 @@ (ns test.support.mock-reddit - "In-process HTTP stub for Reddit API fixtures (`test/fixtures/reddit/`)." + "In-process HTTP stub for Reddit API fixtures + OAuth login endpoints." (:require [clojure.java.io :as io] [clojure.string :as str]) (:import [com.sun.net.httpserver HttpServer HttpHandler HttpExchange] - [java.net InetSocketAddress])) + [java.net InetSocketAddress URLDecoder])) (defn fixtures-dir ([] (fixtures-dir (System/getProperty "user.dir"))) ([root] (str root "/test/fixtures/reddit"))) +(defn- query-param [query key] + (when query + (some (fn [pair] + (let [[k v] (str/split pair "=" 2)] + (when (= k key) + (URLDecoder/decode (or v "") "UTF-8")))) + (str/split query #"&")))) + +(defn- parse-mock-user [raw] + (let [s (or raw "t2_test:redditor") + [id login] (str/split s #":" 2)] + {:id id :login (or login "redditor")})) + +(defn- send-bytes [^HttpExchange ex status ^bytes body content-type] + (.set (.getResponseHeaders ex) "Content-Type" content-type) + (.sendResponseHeaders ex status (alength body)) + (doto (.getResponseBody ex) + (.write body) + (.close))) + +(defn- send-json [^HttpExchange ex status body] + (send-bytes ex status (.getBytes body "UTF-8") "application/json")) + +(defn- send-redirect [^HttpExchange ex location] + (.set (.getResponseHeaders ex) "Location" location) + (.sendResponseHeaders ex 302 -1) + (.close (.getResponseBody ex))) + +(defn- read-form [^HttpExchange ex] + (let [body (slurp (.getInputStream ex))] + {:code (query-param body "code") + :grant (query-param body "grant_type")})) + +(defn- bearer-token [^HttpExchange ex] + (some-> (.getRequestHeaders ex) + (.getFirst "Authorization") + (str/replace #"^[Bb]earer " ""))) + +(defn- parse-token-user [token] + (when (str/starts-with? token "mock:") + (parse-mock-user (subs token 5)))) + (defn start-mock-reddit "Start a mock Reddit API on `port`. Returns a zero-arg `stop` function." ([port] (start-mock-reddit port (fixtures-dir))) @@ -19,15 +61,38 @@ handler (proxy [HttpHandler] [] (handle [^HttpExchange exchange] - ;; `/r//about.json` → subreddit entity; `/r/.json` → listing. - (let [path (.getPath (.getRequestURI exchange)) - body (if (str/includes? path "/about") - about - listing)] - (.sendResponseHeaders exchange 200 (alength body)) - (let [out (.getResponseBody exchange)] - (.write out body) - (.close out)))))] + (let [uri (.getRequestURI exchange) + path (.getPath uri) + query (.getQuery uri) + method (.getRequestMethod exchange)] + (cond + (str/ends-with? path "/api/v1/authorize") + (let [redirect-uri (query-param query "redirect_uri") + state (query-param query "state") + user (parse-mock-user (query-param query "mock_user")) + code (str "mock:" (:id user) ":" (:login user)) + loc (str redirect-uri "?code=" (java.net.URLEncoder/encode code "UTF-8") + "&state=" (java.net.URLEncoder/encode state "UTF-8"))] + (send-redirect exchange loc)) + + (and (= method "POST") (str/ends-with? path "/api/v1/access_token")) + (let [form (read-form exchange) + grant (or (:grant form) "") + code (or (:code form) "mock:t2_test:redditor")] + (if (= grant "client_credentials") + (send-json exchange 200 "{\"access_token\":\"app-token\",\"token_type\":\"bearer\",\"expires_in\":3600}") + (send-json exchange 200 (str "{\"access_token\":\"" code "\",\"token_type\":\"bearer\",\"expires_in\":3600}")))) + + (str/ends-with? path "/api/v1/me") + (let [user (or (parse-token-user (bearer-token exchange)) + {:id "t2_test" :login "redditor"})] + (send-json exchange 200 + (str "{\"id\":\"" (:id user) "\",\"name\":\"" (:login user) "\"}"))) + + ;; `/r//about.json` → subreddit entity; `/r/.json` → listing. + :else + (let [body (if (str/includes? path "/about") about listing)] + (send-bytes exchange 200 body "application/json"))))))] (.createContext server "/" handler) (.setExecutor server nil) (.start server) Side B — contributor: tommy-mor Side B — commit message: [5350388a] Add pool-scoped voting: /vote?pool= picks pairs from children. - /vote now accepts an optional `pool` param (parent item path). When provided without left/right, it picks the first unvoted pair from the pool's children. When provided alongside left/right, it constrains "next pair" navigation to siblings within the pool. - "vote on children" button appears on item pages with ≥2 children, linking to /vote?pool=. - Pool is threaded through VoteComparePost → success JS so in-page morph after voting keeps the pool context for next-pair navigation. Co-Authored-By: Claude Sonnet 4.6 Side B — unified diff (full patch): diff --git a/server/src/api/ui_html.rs b/server/src/api/ui_html.rs index 5faa642451d69555cb391974beb0ad22c9355c8c..b79efdb4d52bd445a67f38cbfd61d3507d2b3014 100644 --- a/server/src/api/ui_html.rs +++ b/server/src/api/ui_html.rs @@ -193,6 +193,7 @@ async fn dispatch_ui_action( ratio_right, explanation, next, + pool, form_action, } => { if form_action != "/ui" { @@ -239,6 +240,9 @@ async fn dispatch_ui_action( .into_response(); } }; + let pool_id = pool.as_deref().and_then(|p| { + crate::path_types::ItemId::parse(p.trim()).map(|i| i.normalized_storage()) + }); let mut rl = ratio_left.trim().parse::().unwrap_or(0).max(0); let mut rr = ratio_right.trim().parse::().unwrap_or(0).max(0); if rl == 0 && rr == 0 { @@ -294,6 +298,7 @@ async fn dispatch_ui_action( &thread_tag, &left_id, &right_id, + pool_id.as_ref(), pid.as_str(), post_index, ) diff --git a/server/src/html/garden/pin.rs b/server/src/html/garden/pin.rs index 5865cfdbc06aeb6555c97380e25591fae6b3d125..1820d7fe7ee167ecbf5ad5124f23b2ab92ffb01f 100644 --- a/server/src/html/garden/pin.rs +++ b/server/src/html/garden/pin.rs @@ -79,7 +79,7 @@ pub(super) fn ont_pin_vote_controls( } } } @else { - a class="ont-vote-compare-btn" href=(vote_compare_href(nav, pi, ¤t, None)) title="Compare and vote" { + a class="ont-vote-compare-btn" href=(vote_compare_href(nav, pi, ¤t, None, None)) title="Compare and vote" { span class="ont-vote-glyph" aria-hidden="true" { "⚖" } span { "vote" } } @@ -121,7 +121,7 @@ pub(super) fn child_row_pin_or_vote( if nv == 1 { "" } else { "s" }, ); @let aria = format!("Vote; {} pairwise {}", nv, if nv == 1 { "vote" } else { "votes" }); - a class="ont-garden-vote-ico" href=(vote_compare_href(nav, pi, row_item, None)) title=(tip) aria-label=(aria) { + a class="ont-garden-vote-ico" href=(vote_compare_href(nav, pi, row_item, None, None)) title=(tip) aria-label=(aria) { span class="ont-garden-vote-glyph" aria-hidden="true" { "⚖" } span class="ont-garden-vote-count" { (format!("{}", nv)) } } diff --git a/server/src/html/garden/render.rs b/server/src/html/garden/render.rs index 5c3986ca36902f6c9019a4b5590f0b3b9d2cb4ff..bd8cbce059ee789de6e8dc9b6f69f54beee2f994 100644 --- a/server/src/html/garden/render.rs +++ b/server/src/html/garden/render.rs @@ -29,6 +29,7 @@ use super::{ item::{child_depth_from_uri, item_code_label, item_display_path, item_href}, item_page::{build_item_page_view_model, sibling_nav_markup}, pin::{child_row_pin_or_vote, ont_pin_vote_controls, pinned_item_from_jar}, + vote::vote_pool_href, }; pub(super) async fn render_scope_view( @@ -186,12 +187,21 @@ pub(super) async fn render_scope_view( } section class="ont-tab-panel ont-tab-panel-children" { + @let total_children = model.child_rankings.component_rankings + .iter().map(|c| c.ranked.len()).sum::() + + model.child_rankings.unranked_items.len(); h3 { "ranked child groups" @if model.child_depth > 1 { " " span class="muted" { (format!("(depth {})", model.child_depth)) } } + @if total_children >= 2 { + " " + a class="ont-vote-children-btn" href=(vote_pool_href(&nav, &model.item)) { + "vote on children" + } + } } @if model.child_rankings.component_rankings.is_empty() { p class="muted" { "no voted pairs yet in this scope" } diff --git a/server/src/html/garden/tests.rs b/server/src/html/garden/tests.rs index 6900a6795bcde866a176722149d6378e5127b4c3..c2036fca7752aef63d260e36cfe9649f63b5c550 100644 --- a/server/src/html/garden/tests.rs +++ b/server/src/html/garden/tests.rs @@ -105,7 +105,7 @@ fn suggest_next_vote_pair_prefers_unvoted_sibling_pair() { let content = content_for_garden_view(&reduced, &ScopeId::Public); let a = ItemId::parse("~/topic/a").unwrap().normalized_storage(); let b = ItemId::parse("~/topic/b").unwrap().normalized_storage(); - let next = suggest_next_vote_pair(content, &a, &b).expect("next sibling pair"); + let next = suggest_next_vote_pair(content, &a, &b, None).expect("next sibling pair"); assert_ne!( canonical_edge_items(&next.0, &next.1), canonical_edge_items(&a, &b) diff --git a/server/src/html/garden/vote.rs b/server/src/html/garden/vote.rs index 1d7fc8aa7436bfa9c1186dfd940a8d751ab7e088..2682cfcbd2f834b56459a02831aa225cffe67c58 100644 --- a/server/src/html/garden/vote.rs +++ b/server/src/html/garden/vote.rs @@ -211,14 +211,15 @@ pub(crate) async fn vote_compare_post_success_js( _thread_tag: &str, left: &ItemId, right: &ItemId, + pool: Option<&ItemId>, _post_id: &str, _post_idx: Option, ) -> String { let reduced = state.reduced.read().await; let content = content_for_garden_view(&reduced, &nav.scope()); let edge_history = vote_edge_history_markup(content, left, right); - let next_pair = suggest_next_vote_pair(content, left, right); - let nav_markup = vote_compare_nav_markup(nav, next_pair.as_ref()); + let next_pair = suggest_next_vote_pair(content, left, right, pool); + let nav_markup = vote_compare_nav_markup(nav, next_pair.as_ref(), pool); drop(reduced); JsBuilder::new() .morph_inner_selector("#vote-edge-history-region", edge_history) @@ -231,27 +232,39 @@ pub(super) fn vote_compare_href( left: &ItemId, right: &ItemId, thread_override: Option<&str>, + pool: Option<&ItemId>, ) -> String { let left_q = urlencoding::encode(left.as_str()); let right_q = urlencoding::encode(right.as_str()); - let base = format!( + let mut base = format!( "{}/vote?left={}&right={}", nav.room_path_prefix_for_vote_compare(), left_q, right_q ); if let Some(t) = thread_override.filter(|s| !s.is_empty()) { - format!("{}&thread={}", base, urlencoding::encode(t)) - } else { - base + base = format!("{}&thread={}", base, urlencoding::encode(t)); + } + if let Some(p) = pool { + base = format!("{}&pool={}", base, urlencoding::encode(p.as_str())); } + base +} + +pub(super) fn vote_pool_href(nav: &ThreadNav, pool_item_str: &str) -> String { + format!( + "{}/vote?pool={}", + nav.room_path_prefix_for_vote_compare(), + urlencoding::encode(pool_item_str) + ) } fn vote_compare_nav_markup( nav: &ThreadNav, next_pair: Option<&(ItemId, ItemId)>, + pool: Option<&ItemId>, ) -> maud::Markup { - let next_pair_href = next_pair.map(|(nl, nr)| vote_compare_href(nav, nl, nr, None)); + let next_pair_href = next_pair.map(|(nl, nr)| vote_compare_href(nav, nl, nr, None, pool)); html! { div class="vote-compare-nav" { @if let Some(href) = &next_pair_href { @@ -267,8 +280,15 @@ pub(super) fn suggest_next_vote_pair( content: &ContentState, current_left: &ItemId, current_right: &ItemId, + pool_parent: Option<&ItemId>, ) -> Option<(ItemId, ItemId)> { - let pool: Vec = if current_left.parent().as_ref().map(|p| p.as_str()) + let pool: Vec = if let Some(parent) = pool_parent { + content + .item_children + .get(parent) + .map(|s| s.iter().cloned().collect()) + .unwrap_or_default() + } else if current_left.parent().as_ref().map(|p| p.as_str()) == current_right.parent().as_ref().map(|p| p.as_str()) { current_left @@ -322,10 +342,14 @@ pub(super) fn vote_compare_item_card( } #[derive(Debug, Deserialize)] pub struct VoteCompareQuery { - pub left: String, - pub right: String, + #[serde(default)] + pub left: Option, + #[serde(default)] + pub right: Option, #[serde(default)] pub thread: Option, + #[serde(default)] + pub pool: Option, } /// Public pairwise vote UI — `/vote?left=&right=&thread=`. @@ -376,17 +400,53 @@ async fn vote_compare_inner( jar: CookieJar, uri: Uri, ) -> axum::response::Response { - let left = match ItemId::parse(q.left.trim()) { - Some(i) => i.normalized_storage(), - None => return (StatusCode::NOT_FOUND, "bad left item").into_response(), + let pool_id: Option = match q.pool.as_deref() { + Some(p) => match ItemId::parse(p.trim()) { + Some(i) => Some(i.normalized_storage()), + None => return (StatusCode::BAD_REQUEST, "bad pool item").into_response(), + }, + None => None, }; - let right = match ItemId::parse(q.right.trim()) { - Some(i) => i.normalized_storage(), - None => return (StatusCode::NOT_FOUND, "bad right item").into_response(), + + let (left, right) = match (q.left.as_deref(), q.right.as_deref()) { + (Some(l), Some(r)) => { + let left = match ItemId::parse(l.trim()) { + Some(i) => i.normalized_storage(), + None => return (StatusCode::NOT_FOUND, "bad left item").into_response(), + }; + let right = match ItemId::parse(r.trim()) { + Some(i) => i.normalized_storage(), + None => return (StatusCode::NOT_FOUND, "bad right item").into_response(), + }; + if left == right { + return (StatusCode::BAD_REQUEST, "items must differ").into_response(); + } + (left, right) + } + (None, None) => { + let Some(pool) = pool_id.as_ref() else { + return (StatusCode::BAD_REQUEST, "provide left+right or pool").into_response(); + }; + let reduced = state.reduced.read().await; + let content = content_for_garden_view(&reduced, &nav.scope()); + let children: Vec = content + .item_children + .get(pool) + .map(|s| s.iter().cloned().collect()) + .unwrap_or_default(); + if children.len() < 2 { + drop(reduced); + return (StatusCode::BAD_REQUEST, "pool has fewer than 2 children to compare").into_response(); + } + let pair = suggest_next_pair_in_pool(&content.ranking_group, &children, None); + drop(reduced); + match pair { + Some(p) => p, + None => return (StatusCode::BAD_REQUEST, "no pairs available in pool").into_response(), + } + } + _ => return (StatusCode::BAD_REQUEST, "provide both left and right, or just pool").into_response(), }; - if left == right { - return (StatusCode::BAD_REQUEST, "items must differ").into_response(); - } let reduced = state.reduced.read().await; let content = content_for_garden_view(&reduced, &nav.scope()); @@ -409,7 +469,7 @@ async fn vote_compare_inner( let left_body = content.item_bodies.get(&left).cloned(); let right_body = content.item_bodies.get(&right).cloned(); let item_bodies_for_cards = content.item_bodies.clone(); - let next_pair = suggest_next_vote_pair(content, &left, &right); + let next_pair = suggest_next_vote_pair(content, &left, &right, pool_id.as_ref()); drop(reduced); let title = format!( @@ -432,6 +492,7 @@ async fn vote_compare_inner( "ratio_right": {"$form": "ratio_right"}, "explanation": {"$form": "explanation"}, "next": next_path, + "pool": pool_id.as_ref().map(|p| p.as_str()), "form_action": "/ui", })) .expect("vote compare rpc json"); @@ -456,7 +517,7 @@ async fn vote_compare_inner( Some(&item_bodies_for_cards), )) } - (vote_compare_nav_markup(&nav, next_pair.as_ref())) + (vote_compare_nav_markup(&nav, next_pair.as_ref(), pool_id.as_ref())) div id="vote-edge-history-region" { (edge_history) } diff --git a/server/src/html/ui_action.rs b/server/src/html/ui_action.rs index dd5294202569454acf9f41b458718700bbf96f39..2589a2cc00bb7b18cd19ebcbb938083122d6921d 100644 --- a/server/src/html/ui_action.rs +++ b/server/src/html/ui_action.rs @@ -50,6 +50,9 @@ pub enum HtmlUiAction { explanation: String, /// Same-origin path after successful post (JS redirect). next: String, + /// Pool parent item path, if the vote was initiated from a pool URL. + #[serde(default)] + pool: Option, #[serde(default = "default_ui_form_action")] form_action: String, },