From 8b8285b5d27aa19714b23bb9c222c424032213b9 Mon Sep 17 00:00:00 2001 From: feco Date: Sat, 21 Nov 2026 21:13:41 +0000 Subject: [PATCH] No browser storage for referrals; the birth chart opens at the drawn chart The share page stores nothing in the browser any more: the shared link that brought a visitor travels in its login link (/belepes?ref=...) to the Google, Apple and password sign-up. The backend counts the same visitor of a link once in half an hour, instead of a sessionStorage flag. The public birth chart scrolls to the drawn chart after a calculation and when coming back to the page. Tabs scrolled to themselves on every re-render of their parent when the address had a tab (#bolygok); they now react only to the tab ids and hash changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL --- services/backend/src/main.rs | 4 ++++ services/backend/src/routes/shares.rs | 5 +++++ services/backend/src/tests.rs | 11 +++++++---- .../frontend/src/app/belepes/AppleLogin.tsx | 14 +++----------- .../frontend/src/app/belepes/GoogleLogin.tsx | 16 ++++------------ .../src/app/belepes/PasswordLogin.tsx | 9 +++------ services/frontend/src/app/belepes/page.tsx | 13 ++++++++++--- services/frontend/src/app/globals.css | 2 +- services/frontend/src/app/s/[slug]/page.tsx | 2 +- .../app/szuletesi-horoszkop/PublicChart.tsx | 19 +++++++++++++------ .../frontend/src/components/ShareVisit.tsx | 19 ++++--------------- services/frontend/src/components/Tabs.tsx | 7 +++++-- 12 files changed, 60 insertions(+), 61 deletions(-) diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index 8e552c8..93572c5 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -47,6 +47,9 @@ pub struct AppState { pub calculator_limiter: LoginLimiter, /// The public place search (typing makes several calls), per visitor address. pub places_limiter: LoginLimiter, + /// Share visits already counted (link and visitor address, for half an hour): + /// a reload is not a new visit, without storing anything in the browser. + pub share_visits: LoginLimiter, pub models: models::Catalog, pub stripe: stripe::Client, } @@ -60,6 +63,7 @@ impl AppState { login_limiter: LoginLimiter::new(10, Duration::from_secs(15 * 60)), calculator_limiter: LoginLimiter::new(30, Duration::from_secs(60 * 60)), places_limiter: LoginLimiter::new(300, Duration::from_secs(60 * 60)), + share_visits: LoginLimiter::new(1, Duration::from_secs(30 * 60)), models: models::Catalog::new(&config.openrouter_models_url), stripe: stripe::Client::default(), db, diff --git a/services/backend/src/routes/shares.rs b/services/backend/src/routes/shares.rs index 31e9b61..9bf91b1 100644 --- a/services/backend/src/routes/shares.rs +++ b/services/backend/src/routes/shares.rs @@ -326,6 +326,11 @@ pub async fn visit( if sharer || same_place || is_robot(user_agent(&headers).as_deref()) { return Ok(Json(json!({ "counted": false }))); } + // The same visitor again within half an hour (a reload, back and forth). + let visitor = format!("{}:{}", share.slug, client_ip(&headers).unwrap_or_default()); + if state.share_visits.hit(&visitor).is_err() { + 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( diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 641207f..d2b981a 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -1046,10 +1046,13 @@ async fn a_visit_by_someone_else_earns_one_question_once(pool: PgPool) { 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 r = app.call_with("POST", &visit, None, None, &[browser, elsewhere]).await; + assert_eq!(r.body["counted"], true); + // the same visitor again soon (a reload) is not a new visit + let r = app.call_with("POST", &visit, None, None, &[browser, elsewhere]).await; + assert_eq!(r.body["counted"], false); + let r = app.call_with("POST", &visit, None, None, &[browser, ("x-real-ip", "198.51.100.3")]).await; + assert_eq!(r.body["counted"], true); let body = me().await; assert_eq!( (body["analyses_left"]["question"].as_i64(), &body["share_reward_granted"]), diff --git a/services/frontend/src/app/belepes/AppleLogin.tsx b/services/frontend/src/app/belepes/AppleLogin.tsx index 0e5b66f..8eef023 100644 --- a/services/frontend/src/app/belepes/AppleLogin.tsx +++ b/services/frontend/src/app/belepes/AppleLogin.tsx @@ -55,10 +55,13 @@ export function AppleLogin({ clientId, target, inviteToken = null, + referral = null, }: { clientId: string; target: string; inviteToken?: string | null; + /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ + referral?: string | null; }) { const router = useRouter(); const [ready, setReady] = useState(false); @@ -95,20 +98,9 @@ export function AppleLogin({ setBusy(true); const name = [response.user?.name?.lastName, response.user?.name?.firstName].filter(Boolean).join(" ") || null; try { - let referral: string | null = null; - try { - referral = localStorage.getItem("sf_ref"); - } catch { - // storage blocked - } await api("/auth/apple", { body: { id_token: response.authorization.id_token, name, invite_token: inviteToken, referral }, }); - try { - localStorage.removeItem("sf_ref"); - } catch { - // storage blocked - } router.replace(target); router.refresh(); } catch (e) { diff --git a/services/frontend/src/app/belepes/GoogleLogin.tsx b/services/frontend/src/app/belepes/GoogleLogin.tsx index 11a317f..4b3117d 100644 --- a/services/frontend/src/app/belepes/GoogleLogin.tsx +++ b/services/frontend/src/app/belepes/GoogleLogin.tsx @@ -52,11 +52,14 @@ export function GoogleLogin({ clientId, target, inviteToken = null, + referral = null, }: { clientId: string; target: string; /** From an invitation link: lets in any Google account. */ inviteToken?: string | null; + /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ + referral?: string | null; }) { const router = useRouter(); const slot = useRef(null); @@ -72,18 +75,7 @@ export function GoogleLogin({ setError(null); setUninvited(null); try { - let referral: string | null = null; - try { - referral = localStorage.getItem("sf_ref"); - } catch { - // storage blocked - } await api("/auth/google", { body: { id_token: response.credential, invite_token: inviteToken, referral } }); - try { - localStorage.removeItem("sf_ref"); - } catch { - // storage blocked - } router.replace(target); router.refresh(); } catch (e) { @@ -92,7 +84,7 @@ export function GoogleLogin({ setBusy(false); } }, - [router, target, inviteToken], + [router, target, inviteToken, referral], ); useEffect(() => { diff --git a/services/frontend/src/app/belepes/PasswordLogin.tsx b/services/frontend/src/app/belepes/PasswordLogin.tsx index 7e5346e..14e6cbf 100644 --- a/services/frontend/src/app/belepes/PasswordLogin.tsx +++ b/services/frontend/src/app/belepes/PasswordLogin.tsx @@ -24,10 +24,13 @@ function loginError(e: unknown): string { export function PasswordLogin({ target, inviteToken = null, + referral = null, initialMode = "login", }: { target: string; inviteToken?: string | null; + /** The shared link the visitor came from (in the login link: `?ref=`), for the sharer's reward. */ + referral?: string | null; initialMode?: Mode; }) { const router = useRouter(); @@ -60,12 +63,6 @@ export function PasswordLogin({ return; } if (mode === "register") { - let referral: string | null = null; - try { - referral = localStorage.getItem("sf_ref"); - } catch { - // storage blocked - } await api("/auth/register", { body: { email, display_name: name.trim() || null, locale: "hu", invite_token: inviteToken, referral }, }); diff --git a/services/frontend/src/app/belepes/page.tsx b/services/frontend/src/app/belepes/page.tsx index 981fdd7..93650e2 100644 --- a/services/frontend/src/app/belepes/page.tsx +++ b/services/frontend/src/app/belepes/page.tsx @@ -101,6 +101,9 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis const clientId = config?.google_login.enabled ? config.google_login.client_id : null; const appleId = config?.apple_login?.enabled ? config.apple_login.client_id : null; const pendingInvite = invitation?.status === "pending" ? inviteToken : null; + // The shared link that brought the visitor (from its login button), for the sharer's reward. + const rawRef = Array.isArray(params.ref) ? params.ref[0] : params.ref; + const referral = rawRef && /^[A-Za-z0-9_-]{4,64}$/.test(rawRef) ? rawRef : null; const inviteOnly = config?.signup_mode === "invite"; const password = config?.password_login === true; const mod = Array.isArray(params.mod) ? params.mod[0] : params.mod; @@ -139,8 +142,10 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis <> {clientId && (
- - {appleId && } + + {appleId && ( + + )}
)} {clientId && password && ( @@ -148,7 +153,9 @@ export default async function LoginPage({ searchParams }: { searchParams: Promis vagy )} - {password && } + {password && ( + + )} ) : (

diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 0543a9a..1d79442 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -1144,7 +1144,7 @@ span.tarot-fan-card { cursor: default; } /* Public sign calculator (/aszcendens-kalkulator) */ .calc-form { margin-bottom: 8px; } -.calc-result { display: flex; flex-direction: column; gap: 16px; margin: 24px 0 8px; scroll-margin-top: 16px; } +.calc-result { display: flex; flex-direction: column; gap: 16px; margin: 24px 0 8px; scroll-margin-top: 84px; } .calc-signs { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(220px, 100%), 1fr)); gap: 16px; } .calc-sign { display: flex; flex-direction: column; gap: 10px; } .calc-sign-main { display: flex; align-items: baseline; gap: 10px; } diff --git a/services/frontend/src/app/s/[slug]/page.tsx b/services/frontend/src/app/s/[slug]/page.tsx index bb96947..3f6e626 100644 --- a/services/frontend/src/app/s/[slug]/page.tsx +++ b/services/frontend/src/app/s/[slug]/page.tsx @@ -92,7 +92,7 @@ export default async function SharedChartPage({ params }: Props) {

Add meg a születési adataidat, és megkapod a saját képletedet a rövid összefoglalóval együtt, ingyen.

- + {me ? "A saját képletem" : "Elkészítem a sajátomat"} diff --git a/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx b/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx index 8e79ff4..a612aa9 100644 --- a/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx +++ b/services/frontend/src/app/szuletesi-horoszkop/PublicChart.tsx @@ -172,6 +172,8 @@ export function PublicChart() { const [error, setError] = useState(null); const [result, setResult] = useState(null); const [stored, setStored] = useState(false); + /** After a calculation (smooth) or on coming back (at once): show the drawn chart. */ + const [reveal, setReveal] = useState(null); const minuteRef = useRef(null); const resultRef = useRef(null); const today = useMemo(() => new Date().toISOString().slice(0, 10), []); @@ -206,9 +208,19 @@ export function PublicChart() { if (saved?.result?.chart && saved.birth?.date) { setResult(saved); setStored(true); + setReveal("instant"); } }, []); + // Scrolls to the drawn chart, once it is on the page. An old tab in the + // address (#bolygok) would pull the page down to the tables instead. + useEffect(() => { + if (!reveal || !result) return; + if (window.location.hash) history.replaceState(null, "", window.location.pathname + window.location.search); + resultRef.current?.scrollIntoView({ behavior: reveal, block: "start" }); + setReveal(null); + }, [reveal, result]); + /** Forgets the birth data and the chart in this browser. */ function clear() { try { @@ -262,12 +274,7 @@ export function PublicChart() { } catch { // storage blocked or full: the chart is still shown } - requestAnimationFrame(() => - resultRef.current?.scrollIntoView({ - behavior: "smooth", - block: "start", - }), - ); + setReveal("smooth"); } catch (err) { if (err instanceof ApiError && err.code === "ambiguous_local_time") { setAmbiguous(true); diff --git a/services/frontend/src/components/ShareVisit.tsx b/services/frontend/src/components/ShareVisit.tsx index 9cbbe8c..9b66853 100644 --- a/services/frontend/src/components/ShareVisit.tsx +++ b/services/frontend/src/components/ShareVisit.tsx @@ -4,24 +4,13 @@ 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). + * robots do not run scripts, so only people are counted; the backend leaves + * out the sharer and counts the same visitor once in half an hour. Nothing is + * stored in the browser (the sharer who brought a new user travels in the + * login link instead). */ export function ShareVisit({ slug }: { slug: string }) { useEffect(() => { - const key = `share-visit:${slug}`; - try { - // If they sign up later, the sharer who brought them is remembered. - localStorage.setItem("sf_ref", slug); - } catch { - // storage blocked - } - 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; diff --git a/services/frontend/src/components/Tabs.tsx b/services/frontend/src/components/Tabs.tsx index 97a324d..c9c53f8 100644 --- a/services/frontend/src/components/Tabs.tsx +++ b/services/frontend/src/components/Tabs.tsx @@ -22,17 +22,20 @@ export function Tabs({ tabs, label }: { tabs: Tab[]; label: string }) { const root = useRef(null); // A link to # (on load, or from elsewhere on the page) opens that tab and scrolls to it. + // Keyed by the tab ids, not the array (new on every render of the parent), + // so a re-render does not scroll the page back to the tabs. + const ids = tabs.map((t) => t.id).join(" "); useEffect(() => { const open = () => { const id = window.location.hash.slice(1); - if (!tabs.some((t) => t.id === id)) return; + if (!ids.split(" ").includes(id)) return; setActive(id); root.current?.scrollIntoView({ behavior: "smooth", block: "start" }); }; open(); window.addEventListener("hashchange", open); return () => window.removeEventListener("hashchange", open); - }, [tabs]); + }, [ids]); function choose(id: string) { setActive(id);