diff --git a/cloud/auth.py b/cloud/auth.py index 7c7ab04..80a081f 100644 --- a/cloud/auth.py +++ b/cloud/auth.py @@ -19,7 +19,7 @@ from sqlalchemy import select, func, and_ from .config import settings from . import config, database, metering, email_policy -from .models import User, MagicLinkToken, UploadPostProfile +from .models import User, MagicLinkToken, UploadPostProfile, SignupAttribution router = APIRouter() @@ -28,6 +28,11 @@ JWT_TTL_DAYS = 30 MAGIC_TTL_MINUTES = 15 MAGIC_RATE_LIMIT = 3 # per email MAGIC_RATE_WINDOW_MIN = 15 +# Only accept attribution for an account this young. Both sign-in flows post it +# right after the redirect, so anything older is a returning user whose "source" +# would be their re-entry, not their sign-up. +ATTRIBUTION_MAX_AGE_MIN = 60 +ATTRIBUTION_FIELD_MAX = 500 # client-supplied strings are truncated to this def _now(): @@ -196,6 +201,71 @@ async def verify_magic_link(payload: MagicVerifyRequest): return {"token": token, "user": {"id": str(user_id), "email": user_email, "entitled": cu.entitled}} +# --------------------------------------------------------------------------- # +# Signup attribution +# --------------------------------------------------------------------------- # +class AttributionPayload(BaseModel): + referrer: Optional[str] = None + landing_path: Optional[str] = None + utm_source: Optional[str] = None + utm_medium: Optional[str] = None + utm_campaign: Optional[str] = None + + +def _clip(value: Optional[str]) -> Optional[str]: + if not value: + return None + value = value.strip() + return value[:ATTRIBUTION_FIELD_MAX] or None + + +def _referrer_host(referrer: Optional[str]) -> Optional[str]: + """Bare host of the referrer, the key we actually group by.""" + if not referrer: + return None + try: + from urllib.parse import urlparse + host = (urlparse(referrer).hostname or "").lower() + except Exception: + return None + return host or None + + +@router.post("/api/auth/attribution") +async def record_attribution(payload: AttributionPayload, request: Request): + """Record where a brand-new account came from. First touch wins. + + Fire-and-forget from the client right after sign-in: it never fails the + sign-up, it just returns ``recorded: false`` when the row already exists or + the account is too old to be a genuine sign-up. + """ + from sqlalchemy.dialects.postgresql import insert as pg_insert + + user = await get_current_user_required(request) + async with database.session() as session: + async with session.begin(): + row = await session.get(User, user.id) + if row is None or row.created_at is None: + return {"ok": True, "recorded": False} + if _now() - row.created_at > timedelta(minutes=ATTRIBUTION_MAX_AGE_MIN): + return {"ok": True, "recorded": False} + referrer = _clip(payload.referrer) + # ON CONFLICT DO NOTHING keeps first touch even if the client posts + # twice concurrently (two tabs finishing the same redirect). + result = await session.execute( + pg_insert(SignupAttribution).values( + user_id=user.id, + referrer=referrer, + referrer_host=_referrer_host(referrer), + landing_path=_clip(payload.landing_path), + utm_source=_clip(payload.utm_source), + utm_medium=_clip(payload.utm_medium), + utm_campaign=_clip(payload.utm_campaign), + ).on_conflict_do_nothing(index_elements=["user_id"]) + ) + return {"ok": True, "recorded": result.rowcount > 0} + + # --------------------------------------------------------------------------- # # /api/me # --------------------------------------------------------------------------- # diff --git a/cloud/models.py b/cloud/models.py index 07cc526..bde3bd9 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -89,6 +89,34 @@ class UsageLedger(Base): ) +class SignupAttribution(Base): + """Where a user came from, captured once at sign-up (first touch wins). + + Its own table rather than columns on ``users`` because the schema bootstrap + is ``create_all`` (see cloud/database.py), which creates missing tables but + never ALTERs an existing one — a new table lands on deploy with no migration. + + ``referrer_host`` is the grouping key ("github.com", "www.youtube.com", + "google"); the full ``referrer`` is kept for the long tail. Rows are only + written for users whose account is minutes old, so returning users from + before this shipped never get a misleading "signup" source. + """ + __tablename__ = "signup_attribution" + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), + primary_key=True) + referrer = Column(Text, nullable=True) + referrer_host = Column(Text, nullable=True) + landing_path = Column(Text, nullable=True) + utm_source = Column(Text, nullable=True) + utm_medium = Column(Text, nullable=True) + utm_campaign = Column(Text, nullable=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + __table_args__ = ( + Index("ix_attrib_host", "referrer_host"), + Index("ix_attrib_utm_source", "utm_source"), + ) + + class UploadPostProfile(Base): __tablename__ = "upload_post_profiles" user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx index 960fae5..cf9939d 100644 --- a/dashboard/src/contexts/AuthContext.jsx +++ b/dashboard/src/contexts/AuthContext.jsx @@ -8,6 +8,7 @@ import { createContext, useContext, useState, useEffect, useCallback } from 'rea import { getApiUrl } from '../config'; import { apiFetch, apiJson, getToken, setToken, clearToken } from '../lib/api'; import { track } from '../lib/analytics'; +import { report as reportAttribution } from '../lib/attribution'; const AuthContext = createContext(null); export const useAuth = () => useContext(AuthContext); @@ -68,7 +69,12 @@ export function AuthProvider({ children }) { const signedInMe = await refreshMe(); // This handler only runs on the auth redirect, so a resolved user here is // a fresh sign-in / sign-up — the top of the conversion funnel. - if (signedInMe?.user) track('Signup', { props: { method: kind === 'verify' ? 'magic_link' : 'google' } }); + if (signedInMe?.user) { + track('Signup', { props: { method: kind === 'verify' ? 'magic_link' : 'google' } }); + // Server-side twin of the Signup event: the one place we learn which + // channel produced an account. Awaited but never allowed to throw. + await reportAttribution(apiJson); + } // Everyone lands in the app. Show the welcome plan-choice popup once per // browser (on the first auth) for anyone not already on a paid plan — // free is the default, paid is one click away. Never a pricing-page dump. diff --git a/dashboard/src/lib/attribution.js b/dashboard/src/lib/attribution.js new file mode 100644 index 0000000..49f159b --- /dev/null +++ b/dashboard/src/lib/attribution.js @@ -0,0 +1,57 @@ +// First-touch attribution: where a visitor came from, captured before anything +// can overwrite it. +// +// `document.referrer` is only populated on the very first page of a session and +// is wiped by our own auth redirects (Google bounces through accounts.google.com, +// magic links arrive from the mail client). So we snapshot it on the first load +// and keep it in localStorage until the user actually signs up, which can be +// several navigations later. +// +// First touch wins: once stored, capture() never overwrites. That way a visitor +// who arrives from GitHub, wanders off and comes back via a Google search is +// still attributed to GitHub. + +const KEY = 'os_attrib'; +const SENT_KEY = 'os_attrib_sent'; + +const read = (k) => { try { return localStorage.getItem(k); } catch (_) { return null; } }; +const write = (k, v) => { try { localStorage.setItem(k, v); } catch (_) { /* private mode */ } }; + +/** Snapshot the entry point. Safe to call on every load; only the first sticks. */ +export function capture() { + if (read(KEY)) return; + try { + const params = new URLSearchParams(window.location.search); + const referrer = document.referrer || ''; + // Ignore self-referrals: an internal navigation is not an acquisition source. + const sameOrigin = referrer.startsWith(window.location.origin); + const data = { + referrer: sameOrigin ? '' : referrer, + landing_path: window.location.pathname + window.location.search, + utm_source: params.get('utm_source') || '', + utm_medium: params.get('utm_medium') || '', + utm_campaign: params.get('utm_campaign') || '', + }; + // Nothing worth storing (direct hit, no campaign): still record it, so a + // genuine direct visit is distinguishable from "we failed to capture". + write(KEY, JSON.stringify(data)); + } catch (_) { /* never break boot over analytics */ } +} + +/** + * Post the snapshot for a freshly signed-up user. Fire-and-forget: the server + * drops it if the account is not brand new or already has a row. + */ +export async function report(apiJson) { + if (read(SENT_KEY) === '1') return; + const raw = read(KEY); + if (!raw) return; + try { + await apiJson('/api/auth/attribution', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: raw, + }); + write(SENT_KEY, '1'); + } catch (_) { /* attribution must never affect the sign-in */ } +} diff --git a/dashboard/src/main.jsx b/dashboard/src/main.jsx index d1e8c5d..ef2c7c3 100644 --- a/dashboard/src/main.jsx +++ b/dashboard/src/main.jsx @@ -5,6 +5,7 @@ import App from './App.jsx' import Landing from './Landing.jsx' import Legal from './Legal.jsx' import { AuthProvider, useAuth } from './contexts/AuthContext' +import { capture as captureAttribution } from './lib/attribution' import PricingPage from './components/PricingPage' import AccountPage from './components/AccountPage' import LoginModal from './components/LoginModal' @@ -79,6 +80,10 @@ function Root() { return ; } +// Before React mounts: AuthContext rewrites the URL on auth redirects, which +// would destroy the referrer and any UTM params we still need to read. +captureAttribution(); + createRoot(document.getElementById('root')).render(