//! Public sharing links. Creating and revoking a link needs login; opening //! one (`GET /v1/public/shares/{slug}`) does not. The public view never //! contains birth data unless the owner allowed it for their own chart. //! A shared chart comes with its newest short summary (the share page and //! its preview image show both). Sharing the same thing again returns the //! link that is already open. //! //! Reading a share writes nothing, so robots cost no database writes. The //! share page reports a visit from the visitor's browser //! (`POST /v1/public/shares/{slug}/visit`): it is counted unless it comes //! from a robot or from the sharer (logged in, or from the address the link //! was made at). The sharer's first such visit earns one free question, once //! per user: a click proves little. A natal analysis is earned by bringing a //! new user (`REFERRAL_REWARDS`): someone who signs up from a shared link and //! makes their own chart, at most [`REFERRAL_LIMIT`] times. use axum::Json; use axum::extract::{Path, State}; use axum::http::{HeaderMap, StatusCode}; use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; use sqlx::PgPool; use time::OffsetDateTime; use uuid::Uuid; use super::analyses::{can_see, find_analysis}; use super::charts::{ChartRow, find_chart, owned_chart}; use super::synastries::{VisibleSynastry, load_synastry, visible_synastry}; use super::{Body, IdPath, St}; use crate::auth::{AuthUser, user_agent}; use crate::error::{ApiError, ApiResult}; use crate::views::{public_chart, rfc3339, rfc3339_opt}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ShareKind { Chart, Synastry, Analysis, } #[derive(Debug, sqlx::FromRow)] struct ShareRow { id: Uuid, owner_id: Uuid, slug: String, kind: String, chart_id: Option, synastry_id: Option, analysis_id: Option, title: Option, show_birth_data: bool, view_count: i64, created_at: OffsetDateTime, revoked_at: Option, owner_ip_hash: Option>, } const SHARE_COLUMNS: &str = "id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \ view_count, created_at, revoked_at, owner_ip_hash"; /// The visitor's address: the first `X-Forwarded-For` entry (Caddy writes it /// from Cloudflare's, the frontend passes it on). fn client_ip(headers: &HeaderMap) -> Option { let first = headers.get("x-forwarded-for")?.to_str().ok()?.split(',').next()?.trim(); (!first.is_empty()).then(|| first.to_string()) } /// An address salted with the slug, so the stored value says nothing by itself. fn ip_hash(slug: &str, ip: &str) -> Vec { Sha256::digest(format!("{slug}:{ip}").as_bytes()).to_vec() } /// Link preview robots, crawlers and scripts (they do not run the page's /// script anyway; this also stops a direct call). fn is_robot(user_agent: Option<&str>) -> bool { const MARKS: [&str; 16] = [ "bot", "crawl", "spider", "slurp", "facebookexternalhit", "preview", "fetch", "curl", "wget", "python", "headless", "http-client", "okhttp", "java/", "go-http", "scrapy", ]; match user_agent { Some(ua) if !ua.trim().is_empty() => { let ua = ua.to_lowercase(); MARKS.iter().any(|m| ua.contains(m)) } _ => true, } } /// 96 random bits, 16 URL-safe characters. fn new_slug() -> String { db::random_token(12) } impl ShareRow { fn view(&self, base_url: &str) -> Value { json!({ "id": self.id, "slug": self.slug, "url": format!("{base_url}/s/{}", self.slug), "kind": self.kind, "chart_id": self.chart_id, "synastry_id": self.synastry_id, "analysis_id": self.analysis_id, "title": self.title, "show_birth_data": self.show_birth_data, "view_count": self.view_count, "created_at": rfc3339(self.created_at), "revoked_at": rfc3339_opt(self.revoked_at), }) } } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateShare { kind: ShareKind, /// Id of the chart, synastry or analysis. target_id: Uuid, title: Option, /// Show birth date, time and place (only ever of the sharer's own charts). #[serde(default)] show_birth_data: bool, } pub async fn create( State(state): St, auth: AuthUser, headers: HeaderMap, WithRejection(Json(req), _): Body, ) -> ApiResult<(StatusCode, Json)> { let (chart_id, synastry_id, analysis_id, kind) = match req.kind { ShareKind::Chart => { owned_chart(&state.db, req.target_id, auth.id()).await?; (Some(req.target_id), None, None, "chart") } ShareKind::Synastry => { visible_synastry(&state.db, req.target_id, auth.id()).await?; (None, Some(req.target_id), None, "synastry") } ShareKind::Analysis => { let analysis = find_analysis(&state.db, req.target_id).await?.ok_or(ApiError::NotFound("analysis"))?; if !can_see(&state.db, &analysis, auth.id()).await? { return Err(ApiError::NotFound("analysis")); } if analysis.status != "done" { return Err(ApiError::conflict("analysis_not_ready", "only finished analyses can be shared")); } (None, None, Some(req.target_id), "analysis") } }; let title = req.title.map(|t| t.trim().chars().take(120).collect::()).filter(|t| !t.is_empty()); let open: Option = sqlx::query_as(&format!( "SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 AND kind = $2 AND revoked_at IS NULL \ AND chart_id IS NOT DISTINCT FROM $3 AND synastry_id IS NOT DISTINCT FROM $4 \ AND analysis_id IS NOT DISTINCT FROM $5 AND title IS NOT DISTINCT FROM $6 AND show_birth_data = $7 \ ORDER BY created_at DESC LIMIT 1" )) .bind(auth.id()) .bind(kind) .bind(chart_id) .bind(synastry_id) .bind(analysis_id) .bind(&title) .bind(req.show_birth_data) .fetch_optional(&state.db) .await?; if let Some(row) = open { return Ok((StatusCode::OK, Json(row.view(&state.config.public_base_url)))); } let slug = new_slug(); let row: ShareRow = sqlx::query_as(&format!( "INSERT INTO shares (id, owner_id, slug, kind, chart_id, synastry_id, analysis_id, title, show_birth_data, \ owner_ip_hash) \ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}" )) .bind(Uuid::now_v7()) .bind(auth.id()) .bind(&slug) .bind(kind) .bind(chart_id) .bind(synastry_id) .bind(analysis_id) .bind(title) .bind(req.show_birth_data) .bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip))) .fetch_one(&state.db) .await?; Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url)))) } pub async fn list(State(state): St, auth: AuthUser) -> ApiResult> { let rows: Vec = sqlx::query_as(&format!("SELECT {SHARE_COLUMNS} FROM shares WHERE owner_id = $1 ORDER BY created_at DESC")) .bind(auth.id()) .fetch_all(&state.db) .await?; let base = &state.config.public_base_url; Ok(Json(json!({ "shares": rows.iter().map(|r| r.view(base)).collect::>() }))) } pub async fn revoke(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult { let result = sqlx::query("UPDATE shares SET revoked_at = now() WHERE id = $1 AND owner_id = $2 AND revoked_at IS NULL") .bind(id) .bind(auth.id()) .execute(&state.db) .await?; if result.rows_affected() == 0 { return Err(ApiError::NotFound("share")); } Ok(StatusCode::NO_CONTENT) } // --- public view ------------------------------------------------------------------------------- fn public_chart_block(chart: &ChartRow, share: &ShareRow) -> Value { // Birth data only of the sharer's own chart, never of a partner's. let show = share.show_birth_data && chart.owner_id == share.owner_id; json!({ "label": chart.label, "chart": public_chart(&chart.result, show) }) } fn public_synastry_block(s: &VisibleSynastry, share: &ShareRow) -> Value { json!({ "chart1": public_chart_block(&s.chart1, share), "chart2": public_chart_block(&s.chart2, share), "synastry": s.synastry.result, }) } async fn public_body(db: &PgPool, share: &ShareRow) -> Result { let mut body = json!({ "kind": share.kind, "title": share.title, "created_at": rfc3339(share.created_at), }); if let Some(chart_id) = share.chart_id { let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?; body["chart"] = public_chart_block(&chart, share); body["summary"] = latest_summary(db, chart_id).await?; } else if let Some(synastry_id) = share.synastry_id { let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?; body["synastry"] = public_synastry_block(&s, share); } else if let Some(analysis_id) = share.analysis_id { let analysis = find_analysis(db, analysis_id).await?.ok_or(ApiError::NotFound("share"))?; body["analysis"] = json!({ "kind": analysis.kind, "language": analysis.language, "content": analysis.content, "completed_at": rfc3339_opt(analysis.completed_at), }); if let Some(chart_id) = analysis.chart_id { let chart = find_chart(db, chart_id).await?.ok_or(ApiError::NotFound("share"))?; body["chart"] = public_chart_block(&chart, share); } if let Some(synastry_id) = analysis.synastry_id { let s = load_synastry(db, synastry_id).await?.ok_or(ApiError::NotFound("share"))?; body["synastry"] = public_synastry_block(&s, share); } } Ok(body) } /// The newest finished short summary of a chart (`null` if none). async fn latest_summary(db: &PgPool, chart_id: Uuid) -> Result { type Row = (Uuid, String, Option, Option); let row: Option = sqlx::query_as( "SELECT id, language, content, completed_at FROM analyses \ WHERE chart_id = $1 AND kind = 'summary' AND status = 'done' ORDER BY completed_at DESC LIMIT 1", ) .bind(chart_id) .fetch_optional(db) .await?; Ok(match row { Some((id, language, content, completed_at)) => json!({ "id": id, "language": language, "title": content.as_ref().and_then(|c| c["title"].as_str()), "summary": content.as_ref().and_then(|c| c["summary"].as_str()), "completed_at": rfc3339_opt(completed_at), }), None => Value::Null, }) } async fn open_share(db: &PgPool, slug: &str) -> Result { sqlx::query_as(&format!("SELECT {SHARE_COLUMNS} FROM shares WHERE slug = $1 AND revoked_at IS NULL")) .bind(slug.trim()) .fetch_optional(db) .await? .ok_or(ApiError::NotFound("share")) } /// Public: the shared content for the share page and its OG image (read only). pub async fn public_view(State(state): St, Path(slug): Path) -> ApiResult> { let share = open_share(&state.db, &slug).await?; Ok(Json(public_body(&state.db, &share).await?)) } /// Public: the share page reports that someone opened it. Counted unless a /// robot or the sharer; the sharer's first counted visit ever earns the reward. pub async fn visit( State(state): St, auth: Result, headers: HeaderMap, Path(slug): Path, ) -> ApiResult> { let share = open_share(&state.db, &slug).await?; let sharer = auth.as_ref().is_ok_and(|a| a.id() == share.owner_id); let same_place = match (client_ip(&headers), &share.owner_ip_hash) { (Some(ip), Some(hash)) => ip_hash(&share.slug, &ip) == *hash, _ => false, }; if sharer || same_place || is_robot(user_agent(&headers).as_deref()) { return Ok(Json(json!({ "counted": false }))); } let mut tx = state.db.begin().await?; sqlx::query("UPDATE shares SET view_count = view_count + 1 WHERE id = $1").bind(share.id).execute(&mut *tx).await?; let rewarded = sqlx::query( "INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \ VALUES ($1, $2, 'question', 1, 'share_reward', $3) ON CONFLICT DO NOTHING", ) .bind(Uuid::now_v7()) .bind(share.owner_id) .bind(format!("first visit of share {}", share.id)) .execute(&mut *tx) .await? .rows_affected() == 1; tx.commit().await?; if rewarded { tracing::info!(share = %share.id, "share reward granted"); } Ok(Json(json!({ "counted": true }))) } /// Natal analyses a user can earn by bringing new users through shared links. pub const REFERRAL_LIMIT: i64 = 3; /// A new user came from a shared link (`slug`): remembered for the reward, /// unless rewards are off, the link is unknown or revoked, or it is their own. pub(super) async fn record_referral( conn: &mut sqlx::PgConnection, enabled: bool, user_id: Uuid, slug: Option<&str>, ) -> Result<(), sqlx::Error> { let Some(slug) = slug.map(str::trim).filter(|s| enabled && !s.is_empty()) else { return Ok(()); }; sqlx::query( "INSERT INTO referrals (user_id, referrer_id, share_id) \ SELECT $1, owner_id, id FROM shares WHERE slug = $2 AND revoked_at IS NULL AND owner_id <> $1 \ ON CONFLICT DO NOTHING", ) .bind(user_id) .bind(slug) .execute(conn) .await?; Ok(()) } /// The new user made their own chart: the sharer who brought them gets a /// natal analysis, while under the limit. Runs once per new user. pub(super) async fn reward_referral(state: &crate::AppState, user_id: Uuid) -> Result<(), ApiError> { if !state.config.referral_rewards { return Ok(()); } let mut tx = state.db.begin().await?; let referrer: Option = sqlx::query_scalar("SELECT referrer_id FROM referrals WHERE user_id = $1 AND rewarded_at IS NULL FOR UPDATE") .bind(user_id) .fetch_optional(&mut *tx) .await?; let Some(referrer) = referrer else { return Ok(()) }; sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(referrer).execute(&mut *tx).await?; let earned = referral_rewards(&mut tx, referrer).await?; if earned < REFERRAL_LIMIT { sqlx::query( "INSERT INTO credit_ledger (id, user_id, unit, delta, reason, note) \ VALUES ($1, $2, 'natal', 1, 'referral_reward', $3)", ) .bind(Uuid::now_v7()) .bind(referrer) .bind(format!("new user {user_id} from a shared link")) .execute(&mut *tx) .await?; tracing::info!(referrer = %referrer, user = %user_id, "referral reward granted"); } sqlx::query("UPDATE referrals SET rewarded_at = now() WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?; tx.commit().await?; Ok(()) } /// Natal analyses the user has earned by bringing new users. pub async fn referral_rewards(conn: &mut sqlx::PgConnection, user_id: Uuid) -> Result { sqlx::query_scalar("SELECT count(*) FROM credit_ledger WHERE user_id = $1 AND reason = 'referral_reward'") .bind(user_id) .fetch_one(conn) .await } /// Whether the user has already received the reward for sharing. pub async fn reward_granted(db: &PgPool, user_id: Uuid) -> Result { sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM credit_ledger WHERE user_id = $1 AND reason = 'share_reward')") .bind(user_id) .fetch_one(db) .await }