Free chart summaries; password login off by default

- New analysis kind 'summary' (migration 0005): saving a chart queues a
  free 3-4 sentence summary written by SUMMARY_MODEL (default Sonnet
  5.5, about 1 cent; Haiku was tested too but chose weaker highlights).
  POST /v1/charts/{id}/summary returns it and re-queues a failed one.
- The chart page shows it in a "Röviden" card and polls until ready.
- PASSWORD_LOGIN (default false): register, login and password reset
  answer 403; only Google (later Apple, Facebook) logins remain.
- Prompt v2: Hungarian names for elements and modalities (an English
  "Fire" slipped into a summary); worker compare-models --summary.
- The worker also reads a lower-case openrouter_api_key.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-16 17:12:17 +00:00
co-authored by Claude Opus 5.5
parent 269e3167e2
commit 450174c273
19 changed files with 339 additions and 38 deletions
+1
View File
@@ -85,6 +85,7 @@ pub async fn change_password(
auth: AuthUser,
WithRejection(Json(req), _): Body<ChangePassword>,
) -> ApiResult<StatusCode> {
super::auth::password_login_enabled(&state)?;
validate_password(&req.new_password)?;
let existing: Option<(String,)> =
sqlx::query_as("SELECT password_hash FROM auth_identities WHERE user_id = $1 AND provider = 'password'")
+52 -14
View File
@@ -4,6 +4,9 @@
//! writes the text later. A finished analysis with the same cache key (same
//! chart or synastry hash, prompt version, model and language) is copied
//! instead, free of charge, so the same chart is never paid for twice.
//!
//! Every saved chart also gets a free short summary (`summary` kind, written
//! by `SUMMARY_MODEL`); the detailed analyses are paid.
use axum::Json;
use axum::body::Bytes;
@@ -17,7 +20,7 @@ use time::OffsetDateTime;
use uuid::Uuid;
use super::auth::validate_locale;
use super::charts::{find_chart, owned_chart};
use super::charts::{ChartRow, find_chart, owned_chart};
use super::synastries::{load_synastry, visible_synastry};
use super::{IdPath, St};
use crate::AppState;
@@ -104,6 +107,7 @@ fn optional_body(body: &[u8]) -> Result<AnalysisRequest, ApiError> {
enum Target {
Natal { chart_id: Uuid, hash: String },
Summary { chart_id: Uuid, hash: String },
Synastry { synastry_id: Uuid, hash: String },
}
@@ -127,9 +131,25 @@ async fn request(
{
return Err(ApiError::Forbidden(format!("the model '{}' needs the '{}' role", chosen.id, role.as_str())));
}
let model = chosen.id.clone();
let (kind, hash, chart_id, synastry_id) = match &target {
let cost = chosen.credits;
let (status, row) = queue(state, auth.id(), &target, &language, &chosen.id, cost).await?;
Ok((status, Json(row.view())))
}
/// Returns the existing analysis with the same cache key for this target,
/// copies a finished one from another chart with the same data, or queues a
/// new one (spending `cost` credits). 200, 201 and 202 respectively.
async fn queue(
state: &AppState,
user: Uuid,
target: &Target,
language: &str,
model: &str,
cost: i32,
) -> Result<(StatusCode, AnalysisRow), ApiError> {
let (kind, hash, chart_id, synastry_id) = match target {
Target::Natal { chart_id, hash } => ("natal", hash, Some(*chart_id), None),
Target::Summary { chart_id, hash } => ("summary", hash, Some(*chart_id), None),
Target::Synastry { synastry_id, hash } => ("synastry", hash, None, Some(*synastry_id)),
};
let prompt_version = &state.config.prompt_version;
@@ -147,7 +167,7 @@ async fn request(
.fetch_optional(&state.db)
.await?;
if let Some(row) = existing {
return Ok((StatusCode::OK, Json(row.view())));
return Ok((StatusCode::OK, row));
}
let insert = format!(
@@ -170,9 +190,9 @@ async fn request(
.bind(kind)
.bind(chart_id)
.bind(synastry_id)
.bind(auth.id())
.bind(&language)
.bind(&model)
.bind(user)
.bind(language)
.bind(model)
.bind(prompt_version)
.bind(&cache_key)
.bind("done")
@@ -183,20 +203,19 @@ async fn request(
.bind(OffsetDateTime::now_utc())
.fetch_one(&state.db)
.await?;
return Ok((StatusCode::CREATED, Json(row.view())));
return Ok((StatusCode::CREATED, row));
}
// New analysis: spend credits and queue it for the worker.
let cost = chosen.credits;
let mut tx = state.db.begin().await?;
let row: AnalysisRow = sqlx::query_as(&insert)
.bind(id)
.bind(kind)
.bind(chart_id)
.bind(synastry_id)
.bind(auth.id())
.bind(&language)
.bind(&model)
.bind(user)
.bind(language)
.bind(model)
.bind(prompt_version)
.bind(&cache_key)
.bind("pending")
@@ -207,9 +226,28 @@ async fn request(
.bind(None::<OffsetDateTime>)
.fetch_one(&mut *tx)
.await?;
credits::spend(&mut tx, auth.id(), cost, state.config.monthly_free_credits, "analysis", Some(id)).await?;
if cost > 0 {
credits::spend(&mut tx, user, cost, state.config.monthly_free_credits, "analysis", Some(id)).await?;
}
tx.commit().await?;
Ok((StatusCode::ACCEPTED, Json(row.view())))
Ok((StatusCode::ACCEPTED, row))
}
/// The free short summary of a chart (in the owner's language): queued if
/// it does not exist yet or the last attempt failed.
pub async fn ensure_summary(state: &AppState, owner: &AuthUser, chart: &ChartRow) -> Result<AnalysisRow, ApiError> {
let target = Target::Summary { chart_id: chart.id, hash: chart.chart_hash.clone() };
let model = state.config.summary_model.clone();
Ok(queue(state, owner.id(), &target, &owner.user.locale, &model, 0).await?.1)
}
pub async fn summary_for_chart(
State(state): St,
auth: AuthUser,
WithRejection(Path(id), _): IdPath,
) -> ApiResult<Json<Value>> {
let chart = owned_chart(&state.db, id, auth.id()).await?;
Ok(Json(ensure_summary(&state, &auth, &chart).await?.view()))
}
async fn list_where(db: &PgPool, column: &str, id: Uuid) -> Result<Json<Value>, ApiError> {
+13
View File
@@ -158,12 +158,22 @@ pub struct RegisterRequest {
locale: Option<String>,
}
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
if state.config.password_login {
Ok(())
} else {
Err(ApiError::Forbidden("e-mail and password login is disabled; use Google, Apple or Facebook".into()))
}
}
pub async fn register(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<RegisterRequest>,
) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?;
let email = normalize_email(&req.email)?;
validate_password(&req.password)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
@@ -213,6 +223,7 @@ pub async fn login(
jar: CookieJar,
WithRejection(Json(req), _): Body<LoginRequest>,
) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?;
let invalid = || ApiError::InvalidCredentials("wrong e-mail address or password".into());
let email = normalize_email(&req.email).map_err(|_| invalid())?;
state.login_limiter.check(&email)?;
@@ -394,6 +405,7 @@ pub async fn request_password_reset(
State(state): St,
WithRejection(Json(req), _): Body<ResetRequest>,
) -> ApiResult<StatusCode> {
password_login_enabled(&state)?;
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
let mut tx = state.db.begin().await?;
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1"))
@@ -422,6 +434,7 @@ pub async fn confirm_password_reset(
State(state): St,
WithRejection(Json(req), _): Body<ResetConfirmRequest>,
) -> ApiResult<StatusCode> {
password_login_enabled(&state)?;
validate_password(&req.password)?;
let hash = hash_password(req.password).await?;
let mut tx = state.db.begin().await?;
+11
View File
@@ -112,6 +112,14 @@ pub async fn calculate(state: &AppState, birth: Value) -> Result<(Value, Value,
Ok((birth, result, hash))
}
/// Queues the free short summary; a failure here does not fail the save
/// (the chart page asks for the summary again).
async fn queue_summary(state: &AppState, auth: &AuthUser, chart: &ChartRow) {
if let Err(e) = super::analyses::ensure_summary(state, auth, chart).await {
tracing::warn!(chart = %chart.id, error = %e, "queueing the chart summary failed");
}
}
fn clean_birth(birth: Value) -> Result<Value, ApiError> {
let Value::Object(mut birth) = birth else {
return Err(ApiError::BadRequest("birth must be an object".into()));
@@ -150,8 +158,10 @@ pub async fn create(
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
queue_summary(&state, &auth, &row).await;
return Ok((StatusCode::OK, Json(row.owner_view())));
}
queue_summary(&state, &auth, &chart).await;
return Ok((StatusCode::OK, Json(chart.owner_view())));
}
let (count,): (i64,) =
@@ -185,6 +195,7 @@ pub async fn create(
.fetch_one(&mut *tx)
.await?;
tx.commit().await?;
queue_summary(&state, &auth, &row).await;
Ok((StatusCode::CREATED, Json(row.owner_view())))
}
+2
View File
@@ -67,6 +67,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/charts", get(charts::list).post(charts::create))
.route("/v1/charts/{id}", get(charts::get_one).patch(charts::update).delete(charts::remove))
.route("/v1/charts/{id}/analyses", get(analyses::list_for_chart).post(analyses::request_for_chart))
.route("/v1/charts/{id}/summary", post(analyses::summary_for_chart))
// synastries and invitations
.route("/v1/synastries", get(synastries::list).post(synastries::create))
.route("/v1/synastries/{id}", get(synastries::get_one).delete(synastries::remove))
@@ -118,6 +119,7 @@ async fn public_config(State(state): St) -> Json<Value> {
"llm_models": c.llm_models,
"default_model": c.llm_models[0].id,
"monthly_free_credits": c.monthly_free_credits,
"password_login": c.password_login,
"password_min_length": crate::auth::MIN_PASSWORD_LEN,
}))
}