Share reward and less robot load on shared links
CI / test (push) Successful in 1m9s
CI / build (push) Successful in 5m9s
CI / deploy (push) Skipped

The first visit of a shared link by someone else earns the sharer one free
natal analysis, once per user. The share page reports visits from the
visitor's browser; robots, the logged-in sharer and the address the link was
made at do not count. The share button is a proper card that says so in small
print; /v1/me tells whether the reward is used up.

Robots: reading a share writes nothing (view_count counts people only), the
frontend keeps shared content for five minutes (cleared when a link is
revoked), and robots.txt turns away the known AI crawlers while leaving the
link preview robots alone.

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-19 09:26:06 +00:00
co-authored by Claude Opus 5.5
parent c7600608d3
commit 19df36369c
16 changed files with 370 additions and 23 deletions
+3
View File
@@ -33,6 +33,7 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
let birth_change = crate::birth_changes::view(&mut conn, &auth).await?;
let persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
let package = crate::packages::current(&mut conn, auth.id()).await?;
let share_reward = super::shares::reward_granted(&state.db, auth.id()).await?;
Ok(Json(json!({
"user": UserView::from(&auth.user),
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
@@ -41,6 +42,8 @@ pub async fn me(State(state): St, auth: AuthUser) -> ApiResult<Json<Value>> {
"birth_change": birth_change,
"persons": persons.view(),
"package": package.map(|(p, since)| json!({ "id": p.id, "name": p.name, "since": rfc3339(since) })),
// The free analysis for a shared link is used up (once per user).
"share_reward_granted": share_reward,
})))
}
+1
View File
@@ -100,6 +100,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/v1/shares/{id}", delete(shares::revoke))
// public, no login
.route("/v1/public/shares/{slug}", get(shares::public_view))
.route("/v1/public/shares/{slug}/visit", post(shares::visit))
.route("/v1/public/invites/{token}", get(synastries::public_invite))
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
.route("/v1/public/invitations/{token}", get(invitations::public_view))
+116 -14
View File
@@ -4,13 +4,21 @@
//! 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 natal analysis,
//! once per user.
use axum::Json;
use axum::extract::{Path, State};
use axum::http::StatusCode;
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;
@@ -19,7 +27,7 @@ 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;
use crate::auth::{AuthUser, user_agent};
use crate::error::{ApiError, ApiResult};
use crate::views::{public_chart, rfc3339, rfc3339_opt};
@@ -45,10 +53,53 @@ struct ShareRow {
view_count: i64,
created_at: OffsetDateTime,
revoked_at: Option<OffsetDateTime>,
owner_ip_hash: Option<Vec<u8>>,
}
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";
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<String> {
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<u8> {
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 {
@@ -89,6 +140,7 @@ pub struct CreateShare {
pub async fn create(
State(state): St,
auth: AuthUser,
headers: HeaderMap,
WithRejection(Json(req), _): Body<CreateShare>,
) -> ApiResult<(StatusCode, Json<Value>)> {
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
@@ -130,19 +182,22 @@ pub async fn create(
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) \
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {SHARE_COLUMNS}"
"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(new_slug())
.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))))
@@ -242,14 +297,61 @@ async fn latest_summary(db: &PgPool, chart_id: Uuid) -> Result<Value, sqlx::Erro
})
}
/// Public: the shared content for the share page and its OG image.
async fn open_share(db: &PgPool, slug: &str) -> Result<ShareRow, ApiError> {
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<String>) -> ApiResult<Json<Value>> {
let share: ShareRow = sqlx::query_as(&format!(
"UPDATE shares SET view_count = view_count + 1 WHERE slug = $1 AND revoked_at IS NULL RETURNING {SHARE_COLUMNS}"
))
.bind(slug.trim())
.fetch_optional(&state.db)
.await?
.ok_or(ApiError::NotFound("share"))?;
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<AuthUser, ApiError>,
headers: HeaderMap,
Path(slug): Path<String>,
) -> ApiResult<Json<Value>> {
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, 'natal', 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 })))
}
/// Whether the user has already received the reward for sharing.
pub async fn reward_granted(db: &PgPool, user_id: Uuid) -> Result<bool, sqlx::Error> {
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
}
+68 -1
View File
@@ -163,7 +163,22 @@ impl TestApp {
}
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
self.call_with(method, uri, token, body, &[]).await
}
/// A request with extra headers (user agent, forwarded address).
async fn call_with(
&self,
method: &str,
uri: &str,
token: Option<&str>,
body: Option<Value>,
headers: &[(&str, &str)],
) -> Response {
let mut req = Request::builder().method(method).uri(uri);
for (name, value) in headers {
req = req.header(*name, *value);
}
if let Some(t) = token {
req = req.header("authorization", format!("Bearer {t}"));
}
@@ -706,7 +721,7 @@ async fn export_and_delete_account(pool: PgPool) {
/// config and catalog, shared links, invitation pages, the waitlist and
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
/// logged-in user, so other apps cannot use them.
const PUBLIC_ROUTES: [&str; 14] = [
const PUBLIC_ROUTES: [&str; 15] = [
"/healthz",
"/v1/config",
"/v1/packages",
@@ -717,12 +732,64 @@ const PUBLIC_ROUTES: [&str; 14] = [
"/v1/auth/password-reset",
"/v1/auth/password-reset/confirm",
"/v1/public/shares/{slug}",
"/v1/public/shares/{slug}/visit",
"/v1/public/invites/{token}",
"/v1/public/invitations/unsubscribe",
"/v1/public/invitations/{token}",
"/v1/public/waitlist",
];
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn a_visit_by_someone_else_earns_one_analysis_once(pool: PgPool) {
let app = TestApp::new(pool).await;
let anna = app.register("anna@example.com", "Anna").await;
let chart = app.chart(&anna, "Saját", true, "1990-03-15").await;
let share = json!({"kind": "chart", "target_id": chart["id"]});
let home = ("x-forwarded-for", "203.0.113.7");
let r = app.call_with("POST", "/v1/shares", Some(&anna), Some(share), &[home]).await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
let visit = format!("/v1/public/shares/{}/visit", r.body["slug"].as_str().unwrap());
let browser = ("user-agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) Mobile/15E148");
let me = || async { app.get("/v1/me", Some(&anna)).await.body };
let before = me().await["analyses_left"]["natal"].as_i64().unwrap();
// robots, a missing user agent, the sharer's address and the sharer do not count
let elsewhere = ("x-forwarded-for", "198.51.100.1, 172.70.1.1");
for (token, headers) in [
(None, vec![("user-agent", "facebookexternalhit/1.1"), elsewhere]),
(None, vec![elsewhere]),
(None, vec![browser, home]),
(Some(anna.as_str()), vec![browser, elsewhere]),
] {
let r = app.call_with("POST", &visit, token, None, &headers).await;
assert_eq!((r.status, &r.body["counted"]), (StatusCode::OK, &json!(false)), "{headers:?}");
}
let body = me().await;
assert_eq!((body["analyses_left"]["natal"].as_i64(), &body["share_reward_granted"]), (Some(before), &json!(false)));
// reading the share counts nothing either
app.get(&visit.replace("/visit", ""), None).await;
// someone else: counted, and the reward comes once
for _ in 0..2 {
let r = app.call_with("POST", &visit, None, None, &[browser, elsewhere]).await;
assert_eq!(r.body["counted"], true);
}
let body = me().await;
assert_eq!(
(body["analyses_left"]["natal"].as_i64(), &body["share_reward_granted"]),
(Some(before + 1), &json!(true))
);
let r = app.get("/v1/shares", Some(&anna)).await;
assert_eq!(r.body["shares"][0]["view_count"], 2);
// a second link earns nothing more
let r =
app.post("/v1/shares", Some(&anna), json!({"kind": "chart", "target_id": chart["id"], "title": "Új"})).await;
let other = format!("/v1/public/shares/{}/visit", r.body["slug"].as_str().unwrap());
app.call_with("POST", &other, None, None, &[browser, elsewhere]).await;
assert_eq!(me().await["analyses_left"]["natal"].as_i64(), Some(before + 1));
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn everything_else_needs_login(pool: PgPool) {
let app = TestApp::new(pool).await;