Merge pull request 'a' (#19) from main into prod
Reviewed-on: #19
This commit was merged in pull request #19.
This commit is contained in:
@@ -0,0 +1,14 @@
|
|||||||
|
-- A free natal analysis, once per user, when someone else first opens a link
|
||||||
|
-- they shared (counted from the share page in the visitor's browser, so link
|
||||||
|
-- preview robots do not count).
|
||||||
|
ALTER TABLE credit_ledger DROP CONSTRAINT credit_ledger_reason_check;
|
||||||
|
ALTER TABLE credit_ledger ADD CONSTRAINT credit_ledger_reason_check
|
||||||
|
CHECK (reason IN ('monthly_grant', 'analysis', 'chat', 'refund', 'admin_adjust', 'purchase', 'person', 'package',
|
||||||
|
'question', 'share_reward'));
|
||||||
|
CREATE UNIQUE INDEX credit_ledger_share_reward_once ON credit_ledger (user_id) WHERE reason = 'share_reward';
|
||||||
|
|
||||||
|
-- Hash of the sharer's address when the link was made (salted with the slug):
|
||||||
|
-- a visit from there is the sharer, not someone else.
|
||||||
|
ALTER TABLE shares ADD COLUMN owner_ip_hash bytea;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN shares.view_count IS 'visits by people (the share page reports them), robots excluded';
|
||||||
@@ -6,6 +6,28 @@ A képletoldalon, a rövid összefoglaló alatt van a **Megosztás** gomb. Ez eg
|
|||||||
- **Visszavonás:** a „Link visszavonása” gomb után az oldal és a kép is 404-et ad.
|
- **Visszavonás:** a „Link visszavonása” gomb után az oldal és a kép is 404-et ad.
|
||||||
- **Keresők:** az oldal `noindex`, a keresők nem listázzák.
|
- **Keresők:** az oldal `noindex`, a keresők nem listázzák.
|
||||||
|
|
||||||
|
## Ajándék elemzés a megosztásért
|
||||||
|
|
||||||
|
**Mit kap:** felhasználónként **egyszer** +1 képletelemzést, amikor valaki más először megnyitja a megosztott linkjét. A gomb apró betűvel kiírja: „+1 ajándék elemzés jár érte, ha valaki megnézi”. Ha már megkapta, ezt: „Az ajándék elemzést már megkaptad”.
|
||||||
|
|
||||||
|
**Hogyan számolunk:**
|
||||||
|
|
||||||
|
- **A böngésző jelez.** A látogatást a megosztott oldal betöltése után maga a látogató böngészője jelzi (`POST /v1/public/shares/{slug}/visit`). Az előnézet-robotok nem futtatják az oldal szkriptjét, így ők nem számítanak.
|
||||||
|
- **Ami nem számít:**
|
||||||
|
- robotnak látszó vagy hiányzó böngészőazonosító;
|
||||||
|
- a belépett tulajdonos;
|
||||||
|
- látogatás arról az IP-címről, ahonnan a linket létrehozták. A cím a sluggal sózva, hash-ként van tárolva (`shares.owner_ip_hash`).
|
||||||
|
- **Számláló:** a `shares.view_count` csak ezeket a valódi látogatásokat számolja.
|
||||||
|
- **Jutalom egyszer:** a `credit_ledger` `share_reward` sora egyedi indexszel felhasználónként csak egyszer jöhet létre (`credit_ledger_share_reward_once`).
|
||||||
|
- **`/v1/me`:** a `share_reward_granted` jelzi, ha már megkapta.
|
||||||
|
|
||||||
|
## Robotok
|
||||||
|
|
||||||
|
- **Az olvasás nem ír.** A megosztott tartalom lekérése (`GET /v1/public/shares/{slug}`) semmit nem ír az adatbázisba.
|
||||||
|
- **Gyorsítótár:** a frontend 5 percig tartja (`fetch` `revalidate: 300`, `shares` tag), így a sűrűn visszatérő robotok el sem jutnak a backendig. Visszavonáskor az `/api/v1` proxy azonnal törli a taget.
|
||||||
|
- **robots.txt** (`src/app/robots.ts`): kitiltja az ismert AI-robotokat (GPTBot, ClaudeBot, CCBot, PerplexityBot, Bytespider, meta-externalagent stb.). Az előnézet-robotok (facebookexternalhit, Slackbot, WhatsApp, Twitterbot, LinkedInBot) engedélyezve maradnak.
|
||||||
|
- **Cloudflare:** a robots.txt-t be nem tartó robotokra a Cloudflare „Block AI bots” beállítása való (Security → Bots). Ez az előnézet-robotokat nem tiltja le. A „Bot Fight Mode” viszont az előnézeteket is elronthatja, azt ne kapcsoljuk be.
|
||||||
|
|
||||||
## Előnézet (Facebook, Messenger, WhatsApp, LinkedIn, X)
|
## Előnézet (Facebook, Messenger, WhatsApp, LinkedIn, X)
|
||||||
|
|
||||||
Az oldal `og:` és `twitter:` meta tagjei:
|
Az oldal `og:` és `twitter:` meta tagjei:
|
||||||
|
|||||||
@@ -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 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 persons = crate::persons::slots(&mut conn, &auth, state.config.free_person_slots).await?;
|
||||||
let package = crate::packages::current(&mut conn, auth.id()).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!({
|
Ok(Json(json!({
|
||||||
"user": UserView::from(&auth.user),
|
"user": UserView::from(&auth.user),
|
||||||
"providers": providers.into_iter().map(|(p,)| p).collect::<Vec<_>>(),
|
"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,
|
"birth_change": birth_change,
|
||||||
"persons": persons.view(),
|
"persons": persons.view(),
|
||||||
"package": package.map(|(p, since)| json!({ "id": p.id, "name": p.name, "since": rfc3339(since) })),
|
"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,
|
||||||
})))
|
})))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -100,6 +100,7 @@ pub fn router(state: Arc<AppState>) -> Router {
|
|||||||
.route("/v1/shares/{id}", delete(shares::revoke))
|
.route("/v1/shares/{id}", delete(shares::revoke))
|
||||||
// public, no login
|
// public, no login
|
||||||
.route("/v1/public/shares/{slug}", get(shares::public_view))
|
.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/invites/{token}", get(synastries::public_invite))
|
||||||
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
|
.route("/v1/public/invitations/unsubscribe", post(invitations::unsubscribe))
|
||||||
.route("/v1/public/invitations/{token}", get(invitations::public_view))
|
.route("/v1/public/invitations/{token}", get(invitations::public_view))
|
||||||
|
|||||||
@@ -4,13 +4,21 @@
|
|||||||
//! A shared chart comes with its newest short summary (the share page and
|
//! 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
|
//! its preview image show both). Sharing the same thing again returns the
|
||||||
//! link that is already open.
|
//! 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::Json;
|
||||||
use axum::extract::{Path, State};
|
use axum::extract::{Path, State};
|
||||||
use axum::http::StatusCode;
|
use axum::http::{HeaderMap, StatusCode};
|
||||||
use axum_extra::extract::WithRejection;
|
use axum_extra::extract::WithRejection;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
use time::OffsetDateTime;
|
use time::OffsetDateTime;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
@@ -19,7 +27,7 @@ use super::analyses::{can_see, find_analysis};
|
|||||||
use super::charts::{ChartRow, find_chart, owned_chart};
|
use super::charts::{ChartRow, find_chart, owned_chart};
|
||||||
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
|
use super::synastries::{VisibleSynastry, load_synastry, visible_synastry};
|
||||||
use super::{Body, IdPath, St};
|
use super::{Body, IdPath, St};
|
||||||
use crate::auth::AuthUser;
|
use crate::auth::{AuthUser, user_agent};
|
||||||
use crate::error::{ApiError, ApiResult};
|
use crate::error::{ApiError, ApiResult};
|
||||||
use crate::views::{public_chart, rfc3339, rfc3339_opt};
|
use crate::views::{public_chart, rfc3339, rfc3339_opt};
|
||||||
|
|
||||||
@@ -45,10 +53,53 @@ struct ShareRow {
|
|||||||
view_count: i64,
|
view_count: i64,
|
||||||
created_at: OffsetDateTime,
|
created_at: OffsetDateTime,
|
||||||
revoked_at: Option<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, \
|
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.
|
/// 96 random bits, 16 URL-safe characters.
|
||||||
fn new_slug() -> String {
|
fn new_slug() -> String {
|
||||||
@@ -89,6 +140,7 @@ pub struct CreateShare {
|
|||||||
pub async fn create(
|
pub async fn create(
|
||||||
State(state): St,
|
State(state): St,
|
||||||
auth: AuthUser,
|
auth: AuthUser,
|
||||||
|
headers: HeaderMap,
|
||||||
WithRejection(Json(req), _): Body<CreateShare>,
|
WithRejection(Json(req), _): Body<CreateShare>,
|
||||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||||
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
|
let (chart_id, synastry_id, analysis_id, kind) = match req.kind {
|
||||||
@@ -130,19 +182,22 @@ pub async fn create(
|
|||||||
if let Some(row) = open {
|
if let Some(row) = open {
|
||||||
return Ok((StatusCode::OK, Json(row.view(&state.config.public_base_url))));
|
return Ok((StatusCode::OK, Json(row.view(&state.config.public_base_url))));
|
||||||
}
|
}
|
||||||
|
let slug = new_slug();
|
||||||
let row: ShareRow = sqlx::query_as(&format!(
|
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) \
|
"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}"
|
owner_ip_hash) \
|
||||||
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING {SHARE_COLUMNS}"
|
||||||
))
|
))
|
||||||
.bind(Uuid::now_v7())
|
.bind(Uuid::now_v7())
|
||||||
.bind(auth.id())
|
.bind(auth.id())
|
||||||
.bind(new_slug())
|
.bind(&slug)
|
||||||
.bind(kind)
|
.bind(kind)
|
||||||
.bind(chart_id)
|
.bind(chart_id)
|
||||||
.bind(synastry_id)
|
.bind(synastry_id)
|
||||||
.bind(analysis_id)
|
.bind(analysis_id)
|
||||||
.bind(title)
|
.bind(title)
|
||||||
.bind(req.show_birth_data)
|
.bind(req.show_birth_data)
|
||||||
|
.bind(client_ip(&headers).map(|ip| ip_hash(&slug, &ip)))
|
||||||
.fetch_one(&state.db)
|
.fetch_one(&state.db)
|
||||||
.await?;
|
.await?;
|
||||||
Ok((StatusCode::CREATED, Json(row.view(&state.config.public_base_url))))
|
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> {
|
||||||
pub async fn public_view(State(state): St, Path(slug): Path<String>) -> ApiResult<Json<Value>> {
|
sqlx::query_as(&format!("SELECT {SHARE_COLUMNS} FROM shares WHERE slug = $1 AND revoked_at IS NULL"))
|
||||||
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())
|
.bind(slug.trim())
|
||||||
.fetch_optional(&state.db)
|
.fetch_optional(db)
|
||||||
.await?
|
.await?
|
||||||
.ok_or(ApiError::NotFound("share"))?;
|
.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 = open_share(&state.db, &slug).await?;
|
||||||
Ok(Json(public_body(&state.db, &share).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
|
||||||
|
}
|
||||||
|
|||||||
@@ -163,7 +163,22 @@ impl TestApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option<Value>) -> Response {
|
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);
|
let mut req = Request::builder().method(method).uri(uri);
|
||||||
|
for (name, value) in headers {
|
||||||
|
req = req.header(*name, *value);
|
||||||
|
}
|
||||||
if let Some(t) = token {
|
if let Some(t) = token {
|
||||||
req = req.header("authorization", format!("Bearer {t}"));
|
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
|
/// config and catalog, shared links, invitation pages, the waitlist and
|
||||||
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
|
||||||
/// logged-in user, so other apps cannot use them.
|
/// logged-in user, so other apps cannot use them.
|
||||||
const PUBLIC_ROUTES: [&str; 14] = [
|
const PUBLIC_ROUTES: [&str; 15] = [
|
||||||
"/healthz",
|
"/healthz",
|
||||||
"/v1/config",
|
"/v1/config",
|
||||||
"/v1/packages",
|
"/v1/packages",
|
||||||
@@ -717,12 +732,64 @@ const PUBLIC_ROUTES: [&str; 14] = [
|
|||||||
"/v1/auth/password-reset",
|
"/v1/auth/password-reset",
|
||||||
"/v1/auth/password-reset/confirm",
|
"/v1/auth/password-reset/confirm",
|
||||||
"/v1/public/shares/{slug}",
|
"/v1/public/shares/{slug}",
|
||||||
|
"/v1/public/shares/{slug}/visit",
|
||||||
"/v1/public/invites/{token}",
|
"/v1/public/invites/{token}",
|
||||||
"/v1/public/invitations/unsubscribe",
|
"/v1/public/invitations/unsubscribe",
|
||||||
"/v1/public/invitations/{token}",
|
"/v1/public/invitations/{token}",
|
||||||
"/v1/public/waitlist",
|
"/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")]
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
async fn everything_else_needs_login(pool: PgPool) {
|
async fn everything_else_needs_login(pool: PgPool) {
|
||||||
let app = TestApp::new(pool).await;
|
let app = TestApp::new(pool).await;
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
// Forwards /api/v1/* to the backend, so the browser talks to one origin and
|
// Forwards /api/v1/* to the backend, so the browser talks to one origin and
|
||||||
// the session cookie belongs to the frontend's host (no CORS needed).
|
// the session cookie belongs to the frontend's host (no CORS needed).
|
||||||
|
import { revalidateTag } from "next/cache";
|
||||||
import type { NextRequest } from "next/server";
|
import type { NextRequest } from "next/server";
|
||||||
|
|
||||||
import { BACKEND_URL } from "@/lib/server";
|
import { BACKEND_URL } from "@/lib/server";
|
||||||
|
import { SHARES_TAG } from "@/lib/share";
|
||||||
|
|
||||||
const REQUEST_HEADERS = ["accept", "accept-language", "authorization", "content-type", "cookie", "user-agent"];
|
const REQUEST_HEADERS = ["accept", "accept-language", "authorization", "content-type", "cookie", "user-agent"];
|
||||||
// Hop-by-hop or re-computed by the runtime.
|
// Hop-by-hop or re-computed by the runtime.
|
||||||
@@ -38,6 +40,8 @@ async function forward(req: NextRequest, ctx: { params: Promise<{ path: string[]
|
|||||||
if (!SKIP_RESPONSE_HEADERS.has(name)) out.set(name, value);
|
if (!SKIP_RESPONSE_HEADERS.has(name)) out.set(name, value);
|
||||||
});
|
});
|
||||||
for (const cookie of res.headers.getSetCookie()) out.append("set-cookie", cookie);
|
for (const cookie of res.headers.getSetCookie()) out.append("set-cookie", cookie);
|
||||||
|
// A revoked link must disappear at once from the cached share pages.
|
||||||
|
if (req.method === "DELETE" && path[0] === "shares" && res.ok) revalidateTag(SHARES_TAG, { expire: 0 });
|
||||||
return new Response(res.body, { status: res.status, headers: out });
|
return new Response(res.body, { status: res.status, headers: out });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -697,7 +697,23 @@ a.pair-row:hover strong { color: var(--gold); }
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* Sharing a chart (summary card) and the public share page */
|
/* Sharing a chart (summary card) and the public share page */
|
||||||
.share { display: flex; flex-direction: column; gap: 10px; align-items: flex-start; }
|
.share { display: flex; flex-direction: column; gap: 10px; align-items: stretch; }
|
||||||
|
.share-button {
|
||||||
|
display: flex; align-items: center; gap: 14px; width: 100%; padding: 12px 16px; text-align: left; cursor: pointer;
|
||||||
|
border: 1px solid rgba(217, 180, 106, 0.55); border-radius: 12px; color: var(--ink); font: inherit;
|
||||||
|
background: linear-gradient(135deg, rgba(217, 180, 106, 0.14), rgba(217, 180, 106, 0.03));
|
||||||
|
transition: border-color 0.15s, background 0.15s;
|
||||||
|
}
|
||||||
|
.share-button:hover { border-color: var(--gold); background: linear-gradient(135deg, rgba(217, 180, 106, 0.22), rgba(217, 180, 106, 0.06)); }
|
||||||
|
.share-button:disabled { opacity: 0.7; cursor: default; }
|
||||||
|
.share-icon {
|
||||||
|
flex: none; width: 40px; height: 40px; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center;
|
||||||
|
background: var(--gold); color: var(--gold-ink);
|
||||||
|
}
|
||||||
|
.share-button-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||||
|
.share-button-text strong { font-family: var(--font-display); font-size: 21px; font-weight: 600; line-height: 1.15; }
|
||||||
|
.share-button-text small { font-size: 12.5px; color: var(--gold); }
|
||||||
|
.share-fine { margin: 0; font-size: 12.5px; color: var(--muted); line-height: 1.5; }
|
||||||
.share-open { align-items: stretch; padding: 14px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
|
.share-open { align-items: stretch; padding: 14px; border: 1px solid var(--line-2); border-radius: var(--radius); background: var(--panel-2); }
|
||||||
.share-link { display: flex; gap: 8px; }
|
.share-link { display: flex; gap: 8px; }
|
||||||
.share-link .inp { min-height: 36px; font-size: 14px; }
|
.share-link .inp { min-height: 36px; font-size: 14px; }
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ export default async function ChartPage({ params }: { params: Promise<{ id: stri
|
|||||||
initial={summary}
|
initial={summary}
|
||||||
detailedDone={detailed?.status === "done"}
|
detailedDone={detailed?.status === "done"}
|
||||||
isAdmin={me.user.roles.includes("admin")}
|
isAdmin={me.user.roles.includes("admin")}
|
||||||
|
shareRewardGranted={me.share_reward_granted}
|
||||||
/>
|
/>
|
||||||
<BigThree chart={chart} />
|
<BigThree chart={chart} />
|
||||||
{(elements || modalities || phase) && (
|
{(elements || modalities || phase) && (
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import type { MetadataRoute } from "next";
|
||||||
|
|
||||||
|
// AI crawlers that train models or answer from the site: they load pages
|
||||||
|
// far more often than visitors do. Link preview robots (Facebook, Messenger,
|
||||||
|
// Slack, WhatsApp, X, LinkedIn) stay allowed, they make the shared links work.
|
||||||
|
const AI_CRAWLERS = [
|
||||||
|
"GPTBot",
|
||||||
|
"ChatGPT-User",
|
||||||
|
"OAI-SearchBot",
|
||||||
|
"ClaudeBot",
|
||||||
|
"Claude-User",
|
||||||
|
"Claude-SearchBot",
|
||||||
|
"anthropic-ai",
|
||||||
|
"CCBot",
|
||||||
|
"Google-Extended",
|
||||||
|
"GoogleOther",
|
||||||
|
"Applebot-Extended",
|
||||||
|
"PerplexityBot",
|
||||||
|
"Perplexity-User",
|
||||||
|
"Bytespider",
|
||||||
|
"Amazonbot",
|
||||||
|
"meta-externalagent",
|
||||||
|
"meta-externalfetcher",
|
||||||
|
"FacebookBot",
|
||||||
|
"cohere-ai",
|
||||||
|
"cohere-training-data-crawler",
|
||||||
|
"Diffbot",
|
||||||
|
"ImagesiftBot",
|
||||||
|
"Omgilibot",
|
||||||
|
"Omgili",
|
||||||
|
"YouBot",
|
||||||
|
"Timpibot",
|
||||||
|
"AI2Bot",
|
||||||
|
"Ai2Bot-Dolma",
|
||||||
|
"DuckAssistBot",
|
||||||
|
"MistralAI-User",
|
||||||
|
"PetalBot",
|
||||||
|
"Scrapy",
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function robots(): MetadataRoute.Robots {
|
||||||
|
return {
|
||||||
|
rules: [
|
||||||
|
{ userAgent: AI_CRAWLERS, disallow: "/" },
|
||||||
|
// Logged-in pages redirect anyway; shared links carry noindex.
|
||||||
|
{ userAgent: "*", allow: "/", disallow: ["/api/", "/admin", "/profil", "/kepletek", "/osszevetesek", "/szemelyek"] },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import { notFound } from "next/navigation";
|
|||||||
|
|
||||||
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
|
import { ChartWheel, WheelLegend } from "@/components/ChartWheel";
|
||||||
import { Rich } from "@/components/Rich";
|
import { Rich } from "@/components/Rich";
|
||||||
|
import { ShareVisit } from "@/components/ShareVisit";
|
||||||
import { Logo } from "@/components/SiteHeader";
|
import { Logo } from "@/components/SiteHeader";
|
||||||
import { SIGNS, signName } from "@/lib/astro";
|
import { SIGNS, signName } from "@/lib/astro";
|
||||||
import { getMe } from "@/lib/server";
|
import { getMe } from "@/lib/server";
|
||||||
@@ -45,6 +46,7 @@ export default async function SharedChartPage({ params }: Props) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<ShareVisit slug={slug} />
|
||||||
{!me && (
|
{!me && (
|
||||||
<header className="site-header">
|
<header className="site-header">
|
||||||
<Logo />
|
<Logo />
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ export function ChartSummary({
|
|||||||
initial,
|
initial,
|
||||||
detailedDone = false,
|
detailedDone = false,
|
||||||
isAdmin = false,
|
isAdmin = false,
|
||||||
|
shareRewardGranted = false,
|
||||||
}: {
|
}: {
|
||||||
chartId: string;
|
chartId: string;
|
||||||
initial: Analysis | null;
|
initial: Analysis | null;
|
||||||
@@ -32,6 +33,8 @@ export function ChartSummary({
|
|||||||
detailedDone?: boolean;
|
detailedDone?: boolean;
|
||||||
/** Admins can write the summary again. */
|
/** Admins can write the summary again. */
|
||||||
isAdmin?: boolean;
|
isAdmin?: boolean;
|
||||||
|
/** The free analysis for sharing is used up. */
|
||||||
|
shareRewardGranted?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [summary, setSummary] = useState<Analysis | null>(initial);
|
const [summary, setSummary] = useState<Analysis | null>(initial);
|
||||||
const [gaveUp, setGaveUp] = useState(false);
|
const [gaveUp, setGaveUp] = useState(false);
|
||||||
@@ -82,7 +85,7 @@ export function ChartSummary({
|
|||||||
<p className="summary-text" lang={summary?.language}>
|
<p className="summary-text" lang={summary?.language}>
|
||||||
<Rich text={content.summary ?? ""} />
|
<Rich text={content.summary ?? ""} />
|
||||||
</p>
|
</p>
|
||||||
<ShareChart chartId={chartId} />
|
<ShareChart chartId={chartId} rewardGranted={shareRewardGranted} />
|
||||||
<a
|
<a
|
||||||
href="#elemzes"
|
href="#elemzes"
|
||||||
className="summary-more"
|
className="summary-more"
|
||||||
|
|||||||
@@ -9,8 +9,23 @@ interface Share {
|
|||||||
url: string;
|
url: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Share link of a chart with its short summary: copy, Facebook, the phone's share menu, revoke. */
|
function ShareIcon() {
|
||||||
export function ShareChart({ chartId }: { chartId: string }) {
|
return (
|
||||||
|
<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" fill="none" stroke="currentColor" strokeWidth="1.8">
|
||||||
|
<circle cx="18" cy="5" r="2.6" />
|
||||||
|
<circle cx="6" cy="12" r="2.6" />
|
||||||
|
<circle cx="18" cy="19" r="2.6" />
|
||||||
|
<path d="M8.3 10.8l7.4-4.4M8.3 13.2l7.4 4.4" strokeLinecap="round" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Share link of a chart with its short summary: copy, Facebook, the phone's
|
||||||
|
* share menu, revoke. The first visit by someone else earns one free natal
|
||||||
|
* analysis, once per user (`rewardGranted`: already received).
|
||||||
|
*/
|
||||||
|
export function ShareChart({ chartId, rewardGranted = false }: { chartId: string; rewardGranted?: boolean }) {
|
||||||
const [share, setShare] = useState<Share | null>(null);
|
const [share, setShare] = useState<Share | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
@@ -67,8 +82,18 @@ export function ShareChart({ chartId }: { chartId: string }) {
|
|||||||
if (!share) {
|
if (!share) {
|
||||||
return (
|
return (
|
||||||
<div className="share">
|
<div className="share">
|
||||||
<button type="button" className="btn btn-sm" onClick={open} disabled={busy}>
|
<button type="button" className="share-button" onClick={open} disabled={busy} aria-busy={busy}>
|
||||||
{busy ? "Link készül…" : "Megosztás"}
|
<span className="share-icon">
|
||||||
|
<ShareIcon />
|
||||||
|
</span>
|
||||||
|
<span className="share-button-text">
|
||||||
|
<strong>{busy ? "Link készül…" : "Oszd meg a képleted"}</strong>
|
||||||
|
<small>
|
||||||
|
{rewardGranted
|
||||||
|
? "Küldd el a barátaidnak, vagy tedd ki Facebookra"
|
||||||
|
: "+1 ajándék elemzés jár érte, ha valaki megnézi"}
|
||||||
|
</small>
|
||||||
|
</span>
|
||||||
</button>
|
</button>
|
||||||
{revoked && <p className="hint">A linket visszavontad.</p>}
|
{revoked && <p className="hint">A linket visszavontad.</p>}
|
||||||
{error && (
|
{error && (
|
||||||
@@ -87,6 +112,11 @@ export function ShareChart({ chartId }: { chartId: string }) {
|
|||||||
A linken a képleted rajza és ez az összefoglaló látszik, név és születési adatok nélkül. Bárki megnyithatja,
|
A linken a képleted rajza és ez az összefoglaló látszik, név és születési adatok nélkül. Bárki megnyithatja,
|
||||||
akinek elküldöd.
|
akinek elküldöd.
|
||||||
</p>
|
</p>
|
||||||
|
<p className="share-fine">
|
||||||
|
{rewardGranted
|
||||||
|
? "Az ajándék elemzést már megkaptad. Köszönjük, hogy megosztottad!"
|
||||||
|
: "Ajándék képletelemzés egyszer jár: amikor valaki más először megnyitja a linkedet. A saját megnyitásod nem számít."}
|
||||||
|
</p>
|
||||||
<div className="share-link">
|
<div className="share-link">
|
||||||
<input
|
<input
|
||||||
className="inp"
|
className="inp"
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reports a visit of the share page from the visitor's browser. Link preview
|
||||||
|
* robots do not run scripts, so only people are counted (the backend also
|
||||||
|
* leaves out the sharer).
|
||||||
|
*/
|
||||||
|
export function ShareVisit({ slug }: { slug: string }) {
|
||||||
|
useEffect(() => {
|
||||||
|
const key = `share-visit:${slug}`;
|
||||||
|
try {
|
||||||
|
if (sessionStorage.getItem(key)) return;
|
||||||
|
sessionStorage.setItem(key, "1");
|
||||||
|
} catch {
|
||||||
|
// storage blocked: report anyway
|
||||||
|
}
|
||||||
|
fetch(`/api/v1/public/shares/${slug}/visit`, { method: "POST", credentials: "same-origin" }).catch(() => {});
|
||||||
|
}, [slug]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -27,10 +27,19 @@ export interface PublicShare {
|
|||||||
|
|
||||||
const SLUG = /^[A-Za-z0-9_-]{8,64}$/;
|
const SLUG = /^[A-Za-z0-9_-]{8,64}$/;
|
||||||
|
|
||||||
/** The shared content, or `null` if the link is unknown or revoked (one backend call per request). */
|
/** Cache tag of the shared content; revoking a link clears it (see the /api/v1 proxy). */
|
||||||
|
export const SHARES_TAG = "shares";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The shared content, or `null` if the link is unknown or revoked. Kept for
|
||||||
|
* five minutes, so robots opening the page again and again do not reach the
|
||||||
|
* backend; one backend call per request at most.
|
||||||
|
*/
|
||||||
export const loadShare = cache(async (slug: string): Promise<PublicShare | null> => {
|
export const loadShare = cache(async (slug: string): Promise<PublicShare | null> => {
|
||||||
if (!SLUG.test(slug)) return null;
|
if (!SLUG.test(slug)) return null;
|
||||||
const res = await fetch(`${BACKEND_URL}/v1/public/shares/${slug}`, { cache: "no-store" });
|
const res = await fetch(`${BACKEND_URL}/v1/public/shares/${slug}`, {
|
||||||
|
next: { revalidate: 300, tags: [SHARES_TAG] },
|
||||||
|
});
|
||||||
if (res.status === 404) return null;
|
if (res.status === 404) return null;
|
||||||
if (!res.ok) throw new Error(`share ${slug}: HTTP ${res.status}`);
|
if (!res.ok) throw new Error(`share ${slug}: HTTP ${res.status}`);
|
||||||
return (await res.json()) as PublicShare;
|
return (await res.json()) as PublicShare;
|
||||||
|
|||||||
@@ -21,6 +21,8 @@ export interface Me {
|
|||||||
persons: PersonSlots;
|
persons: PersonSlots;
|
||||||
/** The latest main package bought or given (null: none). */
|
/** The latest main package bought or given (null: none). */
|
||||||
package: { id: string; name: string; since: string } | null;
|
package: { id: string; name: string; since: string } | null;
|
||||||
|
/** The free analysis for a shared link is used up (once per user). */
|
||||||
|
share_reward_granted: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A package from the catalog (`GET /v1/packages`). */
|
/** A package from the catalog (`GET /v1/packages`). */
|
||||||
|
|||||||
Reference in New Issue
Block a user