feat(onboarding): popup de selección de plan + quitar tope diario free y 'free trial'

- Quitado el tope de 3 jobs/día por cuenta y 5 por IP en el plan free: la
  cuota de 20 min/mes es el único límite (el ledger ya capa el coste real y el
  tope diario confundía). Verificado que un free NO puede pasar de 20 min ni
  con reservas concurrentes: 10 reservas simultáneas de 5min -> solo 4
  concedidas, ledger clavado en 20, el lock por usuario serializa.
- Registro por email ya no tira a la página de pricing (rayaba): aterriza en
  la app y sale un popup PlanChoiceModal para elegir plan — free (via Google,
  por el gate anti-abuso) o los de pago inline con su precio.
- Eliminado 'start free trial' / '3 days free' de la cabecera y de settings;
  ahora dicen 'choose a plan'.
- vite.config: target del proxy configurable con VITE_PROXY_TARGET para dev
  en el host contra localhost:8000 sin CORS.

Probado en dev local: el popup aparece al aterrizar sin plan y desde el botón
'choose a plan', con free + starter/creator/pro.
This commit is contained in:
juancarlos.cavero 2026-07-21 00:30:56 +02:00
parent 3a2741bb33
commit fe0f32e86b
6 changed files with 153 additions and 84 deletions

50
app.py
View file

@ -130,18 +130,9 @@ def gemini_missing_error():
return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") return HTTPException(status_code=400, detail="Missing X-Gemini-Key header")
def _client_ip(request) -> str: # Probe rate limiter. In-memory, resets on restart by design — the hard monthly
"""Client IP, honoring the proxy's X-Forwarded-For (Traefik in prod).""" # quota lives in the metering ledger; this only stops someone hammering the
fwd = request.headers.get("x-forwarded-for") # proxy with metadata probes.
if fwd:
return fwd.split(",")[0].strip()
return request.client.host if request.client else "unknown"
# In-memory abuse counters. Reset on restart by design — the hard monthly
# quota lives in the metering ledger; these only flatten bursts and casual
# multi-accounting, so losing them on a deploy is fine.
_daily_counters = {"date": None, "users": {}, "ips": {}}
_probe_times: dict = {} # user_id -> [monotonic timestamps] _probe_times: dict = {} # user_id -> [monotonic timestamps]
PROBES_PER_HOUR = 15 PROBES_PER_HOUR = 15
@ -164,13 +155,6 @@ def _maybe_send_quota_email(user):
asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url)) asyncio.create_task(send_out_of_minutes_email(user.email, upgrade_url))
def _daily_bucket(kind: str) -> dict:
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
if _daily_counters["date"] != today:
_daily_counters.update(date=today, users={}, ips={})
return _daily_counters[kind]
def _check_probe_rate(user_id): def _check_probe_rate(user_id):
now = time.monotonic() now = time.monotonic()
times = _probe_times.setdefault(str(user_id), []) times = _probe_times.setdefault(str(user_id), [])
@ -212,23 +196,9 @@ async def reserve_process_minutes(request, url, input_path, job_id):
raise HTTPException(status_code=429, raise HTTPException(status_code=429,
detail="You already have the maximum number of jobs running. Please wait.") detail="You already have the maximum number of jobs running. Please wait.")
# Free-plan daily burst caps, checked BEFORE the probe so URL spam never # Probe rate limit: probing costs a (cheap) proxied metadata call. The
# reaches the proxy. Per-account and per-IP (multi-account abuse). # 20-minute monthly quota is the real bound on free usage; there is no daily
if user.plan == "free": # job cap.
user_counts = _daily_bucket("users")
if user_counts.get(str(user.id), 0) >= _cloud_config.FREE_DAILY_JOBS:
raise HTTPException(status_code=429, detail={
"error": "daily_limit",
"message": "Free plan daily limit reached. Come back tomorrow or upgrade for more.",
})
ip_counts = _daily_bucket("ips")
if ip_counts.get(_client_ip(request), 0) >= _cloud_config.FREE_DAILY_JOBS_PER_IP:
raise HTTPException(status_code=429, detail={
"error": "daily_limit",
"message": "Free plan daily limit reached for this network. Come back tomorrow or upgrade.",
})
# Probe rate limit: probing costs a (cheap) proxied metadata call.
_check_probe_rate(user.id) _check_probe_rate(user.id)
# Probe input duration (blocking → run in a thread). # Probe input duration (blocking → run in a thread).
@ -253,14 +223,6 @@ async def reserve_process_minutes(request, url, input_path, job_id):
"minutes_remaining": e.remaining, "minutes_remaining": e.remaining,
}) })
# Count the job against the free daily caps only once it actually reserved.
if user.plan == "free":
user_counts = _daily_bucket("users")
user_counts[str(user.id)] = user_counts.get(str(user.id), 0) + 1
ip_counts = _daily_bucket("ips")
ip = _client_ip(request)
ip_counts[ip] = ip_counts.get(ip, 0) + 1
return user.id, priority, reservation_id, user.plan return user.id, priority, reservation_id, user.plan

View file

@ -35,11 +35,8 @@ FREE_PLAN_MINUTES = 20
# Gate the free allowance behind Google sign-in; magic-link-only accounts are # Gate the free allowance behind Google sign-in; magic-link-only accounts are
# disposable-email fodder and stay unentitled. # disposable-email fodder and stay unentitled.
FREE_REQUIRES_GOOGLE = True FREE_REQUIRES_GOOGLE = True
# Max processing jobs per free account per UTC day (abuse bound on GPU/proxy). # The 20-minute monthly quota is the only bound on free usage — no daily job
FREE_DAILY_JOBS = 3 # cap (it confused users and the minute ledger already caps real cost).
# Same bound per client IP across free accounts. Generous on purpose: much of
# the audience is behind CGNAT (India/Indonesia share IPs among thousands).
FREE_DAILY_JOBS_PER_IP = 5
# Free users' clips expire from R2 after this many days (paid libraries are # Free users' clips expire from R2 after this many days (paid libraries are
# durable). Also an upgrade lever, mirroring OpusClip's 3-day free exports. # durable). Also an upgrade lever, mirroring OpusClip's 3-day free exports.
FREE_CLIP_RETENTION_DAYS = 7 FREE_CLIP_RETENTION_DAYS = 7

View file

@ -12,6 +12,7 @@ import ScheduleWeekModal from './components/ScheduleWeekModal';
import UsageMeter from './components/UsageMeter'; import UsageMeter from './components/UsageMeter';
import TopUpModal from './components/TopUpModal'; import TopUpModal from './components/TopUpModal';
import StarBanner from './components/StarBanner'; import StarBanner from './components/StarBanner';
import PlanChoiceModal from './components/PlanChoiceModal';
import TrialUpgradeModal from './components/TrialUpgradeModal'; import TrialUpgradeModal from './components/TrialUpgradeModal';
import LoginModal from './components/LoginModal'; import LoginModal from './components/LoginModal';
import TrialGate from './components/TrialGate'; import TrialGate from './components/TrialGate';
@ -174,6 +175,7 @@ function App() {
const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe } = useAuth(); const { billingEnabled, isManaged, isSignedIn, me, plan, refreshMe } = useAuth();
const [showLogin, setShowLogin] = useState(false); const [showLogin, setShowLogin] = useState(false);
const [showTopUp, setShowTopUp] = useState(false); const [showTopUp, setShowTopUp] = useState(false);
const [showPlanChoice, setShowPlanChoice] = useState(false);
const [showTrialUpgrade, setShowTrialUpgrade] = useState(false); const [showTrialUpgrade, setShowTrialUpgrade] = useState(false);
const [topUpInfo, setTopUpInfo] = useState({}); const [topUpInfo, setTopUpInfo] = useState({});
// Durable R2 URLs (per clip index) for the current job — used as a fallback when // Durable R2 URLs (per clip index) for the current job — used as a fallback when
@ -538,6 +540,19 @@ function App() {
// `keysMissing` now means "self-host BYOK keys missing" — it never fires on hosted. // `keysMissing` now means "self-host BYOK keys missing" — it never fires on hosted.
const keysMissing = !billingEnabled && (!apiKey || !uploadPostKey); const keysMissing = !billingEnabled && (!apiKey || !uploadPostKey);
const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial
// Fresh sign-up with no entitlement yet: show the plan-choice popup once
// (AuthContext set the flag after the auth redirect) instead of the pricing page.
useEffect(() => {
if (billingEnabled && isSignedIn && !isManaged) {
let flagged = false;
try { flagged = localStorage.getItem('os_show_plan_choice') === '1'; } catch (_) { /* ignore */ }
if (flagged) {
setShowPlanChoice(true);
try { localStorage.removeItem('os_show_plan_choice'); } catch (_) { /* ignore */ }
}
}
}, [billingEnabled, isSignedIn, isManaged]);
// Included in the plan (fully managed, no keys): Clip Generator + YouTube Studio. // Included in the plan (fully managed, no keys): Clip Generator + YouTube Studio.
// Advanced (bring your own fal.ai + ElevenLabs keys): AI Shorts + AI Agent. // Advanced (bring your own fal.ai + ElevenLabs keys): AI Shorts + AI Agent.
const INCLUDED_TOOL_TABS = ['dashboard', 'thumbnails']; const INCLUDED_TOOL_TABS = ['dashboard', 'thumbnails'];
@ -769,9 +784,9 @@ function App() {
<UsageMeter onClick={() => { window.location.hash = '#/account'; }} /> <UsageMeter onClick={() => { window.location.hash = '#/account'; }} />
)} )}
{billingEnabled && isSignedIn && !isManaged && ( {billingEnabled && isSignedIn && !isManaged && (
<button onClick={() => { window.location.hash = '#/pricing'; }} <button onClick={() => setShowPlanChoice(true)}
className="btn-primary px-4 py-2 text-xs"> className="btn-primary px-4 py-2 text-xs">
Start free trial Choose a plan
</button> </button>
)} )}
{billingEnabled && !isSignedIn && ( {billingEnabled && !isSignedIn && (
@ -894,15 +909,15 @@ function App() {
<div className="w-9 h-9 rounded-input bg-paper3 flex items-center justify-center shrink-0"> <div className="w-9 h-9 rounded-input bg-paper3 flex items-center justify-center shrink-0">
<Sparkles size={16} className="text-brass" /> <Sparkles size={16} className="text-brass" />
</div> </div>
<h2 className="text-base font-medium text-ink lowercase">Start your free trial</h2> <h2 className="text-base font-medium text-ink lowercase">Choose your plan</h2>
</div> </div>
<span className="badge-brass">3 days free</span> <span className="badge-ok">Free plan available</span>
</div> </div>
<p className="text-xs text-muted mb-5 leading-relaxed"> <p className="text-xs text-muted mb-5 leading-relaxed">
Generate shorts with zero setup — no API keys needed. 3 days free, then from $12/mo. Cancel anytime. Generate shorts with zero setup — no API keys needed. Start free with 20 min/month, or go paid from $12/mo. Cancel anytime.
</p> </p>
<button onClick={() => { window.location.hash = '#/pricing'; }} className="btn-primary py-2 px-4 text-sm"> <button onClick={() => setShowPlanChoice(true)} className="btn-primary py-2 px-4 text-sm">
<Sparkles size={16} /> See plans & start trial <Sparkles size={16} /> Choose a plan
</button> </button>
</div> </div>
) : ( ) : (
@ -1552,6 +1567,7 @@ function App() {
{showLogin && <LoginModal onClose={() => setShowLogin(false)} />} {showLogin && <LoginModal onClose={() => setShowLogin(false)} />}
{showPlanChoice && <PlanChoiceModal onClose={() => setShowPlanChoice(false)} />}
{showTopUp && ( {showTopUp && (
<TopUpModal <TopUpModal
onClose={() => setShowTopUp(false)} onClose={() => setShowTopUp(false)}

View file

@ -0,0 +1,103 @@
import React, { useState, useEffect } from 'react';
import { Check, Loader2, Zap, ArrowRight } from 'lucide-react';
import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import Modal from './ui/Modal';
const PLAN_ORDER = ['starter', 'creator', 'pro'];
const FREE_MINUTES = 20;
const fmt = (a, c) => new Intl.NumberFormat('en-US', { style: 'currency', currency: (c || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((a || 0) / 100);
// Shown right after a sign-up that isn't entitled yet, instead of dumping the
// user on the full pricing page. Free is the default choice; paid plans check
// out inline. The free tier needs a Google account (abuse gate), so for an
// email-only user the free CTA offers Google sign-in.
export default function PlanChoiceModal({ onClose }) {
const { loginWithGoogle, googleAuthEnabled } = useAuth();
const [plans, setPlans] = useState([]);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(null);
useEffect(() => {
apiJson('/api/billing/plans')
.then((d) => setPlans(d.plans || []))
.catch(() => setPlans([]))
.finally(() => setLoading(false));
}, []);
const byPlan = (p) => plans.find((x) => x.plan === p && x.interval === 'month');
const checkout = async (price_id) => {
setBusy(price_id);
try {
const { url } = await apiJson('/api/billing/checkout', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ price_id }),
});
window.location.href = url;
} catch (e) { setBusy(null); alert('Could not start checkout. Please try again.'); }
};
const startFree = () => {
// Free needs Google; loginWithGoogle re-auths the account as Google-linked,
// which flips them to entitled. A user already on Google never sees this.
if (googleAuthEnabled) loginWithGoogle();
else onClose();
};
return (
<Modal isOpen onClose={onClose} eyebrow="WELCOME" title="Pick how you want to start" size="lg">
{loading ? (
<div className="flex justify-center py-10"><Loader2 className="animate-spin text-brass" /></div>
) : (
<div className="grid sm:grid-cols-2 gap-4">
{/* Free — the default */}
<div className="card p-5 flex flex-col border-brass">
<div className="flex items-center justify-between mb-1">
<h3 className="font-display lowercase text-lg text-ink">free</h3>
<span className="badge-ok">$0</span>
</div>
<p className="text-muted text-xs mb-3 lowercase">try it on your own videos</p>
<ul className="space-y-1.5 text-sm text-ink2 mb-4 flex-1">
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span><b>{FREE_MINUTES} min</b> / month</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-ok shrink-0 mt-0.5" /> <span>No credit card</span></li>
<li className="flex items-start gap-2"><Check size={15} className="text-muted shrink-0 mt-0.5" /> <span className="text-muted">Watermark · clips kept 7 days</span></li>
</ul>
<button onClick={startFree} className="w-full btn-primary text-sm">
Start free <ArrowRight size={15} />
</button>
{googleAuthEnabled && (
<p className="text-center text-[11px] text-muted mt-2 lowercase">continue with google</p>
)}
</div>
{/* Paid — compact list */}
<div className="card p-5 flex flex-col">
<div className="flex items-center justify-between mb-1">
<h3 className="font-display lowercase text-lg text-ink">paid plans</h3>
<Zap size={16} className="text-brass" />
</div>
<p className="text-muted text-xs mb-3 lowercase">no watermark · more minutes · durable library</p>
<div className="space-y-2 flex-1">
{PLAN_ORDER.map((p) => {
const e = byPlan(p);
if (!e) return null;
return (
<button key={p} onClick={() => checkout(e.price_id)} disabled={busy === e.price_id}
className="w-full flex items-center justify-between border border-rule hover:border-brass rounded-input px-3 py-2 text-left transition-colors disabled:opacity-50">
<span className="text-sm text-ink capitalize">{p} <span className="text-muted">· {e.minutes} min</span></span>
<span className="readout">{busy === e.price_id ? '…' : `${fmt(e.amount, e.currency)}/mo`}</span>
</button>
);
})}
</div>
<button onClick={() => { onClose(); window.location.hash = '#/pricing'; }}
className="text-center text-[11px] text-muted mt-3 lowercase hover:text-ink transition-colors">
see full pricing & yearly →
</button>
</div>
</div>
)}
</Modal>
);
}

View file

@ -69,10 +69,13 @@ export function AuthProvider({ children }) {
// This handler only runs on the auth redirect, so a resolved user here is // 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. // 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' } });
// Google sign-ins are entitled (free plan) and land in the app; only // Everyone lands in the app. A signed-in user with no entitlement yet
// magic-link-only accounts (no entitlement) are routed to pricing, where // (email-only sign-up) gets a plan-choice popup there instead of being
// the free card tells them to use Google. // dumped on the pricing page. Google sign-ins are already on the free
if (signedInMe?.user && !signedInMe?.entitled) destination = '#/pricing'; // plan, so they never see it.
if (signedInMe?.user && !signedInMe?.entitled) {
try { localStorage.setItem('os_show_plan_choice', '1'); } catch (_) { /* ignore */ }
}
} catch (e) { } catch (e) {
// fall through — user lands signed-out // fall through — user lands signed-out
} finally { } finally {

View file

@ -1,6 +1,12 @@
import { defineConfig } from 'vite' import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
// Backend target for the dev proxy. Defaults to the docker-compose service
// name; set VITE_PROXY_TARGET=http://localhost:8000 to run the dev server on
// the host against a backend reachable at localhost (no CORS, same-origin).
const backend = process.env.VITE_PROXY_TARGET || 'http://backend:8000'
const renderer = process.env.VITE_RENDER_TARGET || 'http://renderer:3100'
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig({
plugins: [react()], plugins: [react()],
@ -10,30 +16,12 @@ export default defineConfig({
'www.openshorts.app' 'www.openshorts.app'
], ],
proxy: { proxy: {
'/api': { '/api': { target: backend, changeOrigin: true },
target: 'http://backend:8000', '/videos': { target: backend, changeOrigin: true },
changeOrigin: true, '/thumbnails': { target: backend, changeOrigin: true },
}, '/gallery': { target: backend, changeOrigin: true },
'/videos': { '/video': { target: backend, changeOrigin: true },
target: 'http://backend:8000', '/render': { target: renderer, changeOrigin: true },
changeOrigin: true,
},
'/thumbnails': {
target: 'http://backend:8000',
changeOrigin: true,
},
'/gallery': {
target: 'http://backend:8000',
changeOrigin: true,
},
'/video': {
target: 'http://backend:8000',
changeOrigin: true,
},
'/render': {
target: 'http://renderer:3100',
changeOrigin: true,
}
} }
} }
}) })