From 05578c545688d5067f59b746763cfc4e1edb850f Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 14 Jul 2026 13:04:43 +0200 Subject: [PATCH 01/12] feat: add hosted paid mode (managed keys, Stripe trial, metering) Adds an optional cloud/paid mode behind a BILLING_ENABLED flag. With the flag off the app is byte-identical to today's self-hosted BYOK build (regression-zero). Backend (cloud/ package, only imported when BILLING_ENABLED): - Auth: magic link (Resend) + Google OAuth (authlib) + JWT sessions - Stripe: hosted Checkout with 3-day card trial, Customer Portal, idempotent order-safe webhooks; 3 plans (Starter/Creator/Pro) resolved by lookup_key - Postgres + SQLAlchemy async; atomic minute metering (reserve/commit/release, plan->topup FIFO, restart-safe) with sweeper - Managed keys: Gemini + Upload-Post server-side for entitled users; paid-only (BYOK core header ignored on hosted); Upload-Post white-label per-user profiles - Metering wired into /api/process (probe->reserve->402, priority queue) and thumbnail image generation (3 min/batch) - yt-dlp residential PROXY_URL support + 720p cap for hosted YouTube downloads Frontend: - AuthContext, LoginModal, PricingSection (3-day trial), AccountPage, UsageMeter, TopUpModal, TrialGate/AdvancedBanner - Paid-only UI: hide BYOK core inputs, trial prompts per tool - Included (Clip Generator, YouTube Studio) vs BYOK (AI Shorts/dubbing: fal.ai + ElevenLabs) clearly separated; ThumbnailStudio + SaaShortsTab managed-aware - Landing: free-self-host vs paid-hosted messaging Verified end-to-end against real Postgres + Stripe test mode. --- .env.cloud.example | 38 ++ Dockerfile | 5 +- alembic.ini | 41 +++ alembic/env.py | 60 ++++ alembic/script.py.mako | 22 ++ app.py | 345 ++++++++++++++++--- cloud/__init__.py | 47 +++ cloud/auth.py | 214 ++++++++++++ cloud/billing.py | 329 ++++++++++++++++++ cloud/config.py | 151 ++++++++ cloud/database.py | 49 +++ cloud/emails.py | 36 ++ cloud/managed_keys.py | 25 ++ cloud/metering.py | 271 +++++++++++++++ cloud/models.py | 105 ++++++ cloud/oauth.py | 93 +++++ cloud/social_profiles.py | 102 ++++++ dashboard/src/App.jsx | 145 +++++++- dashboard/src/Landing.jsx | 47 ++- dashboard/src/components/AccountPage.jsx | 135 ++++++++ dashboard/src/components/AdvancedBanner.jsx | 27 ++ dashboard/src/components/LoginModal.jsx | 91 +++++ dashboard/src/components/PricingSection.jsx | 171 +++++++++ dashboard/src/components/SaaShortsTab.jsx | 19 +- dashboard/src/components/ThumbnailStudio.jsx | 45 +-- dashboard/src/components/TopUpModal.jsx | 52 +++ dashboard/src/components/TrialGate.jsx | 25 ++ dashboard/src/components/UsageMeter.jsx | 28 ++ dashboard/src/contexts/AuthContext.jsx | 123 +++++++ dashboard/src/lib/api.js | 48 +++ dashboard/src/main.jsx | 51 ++- docker-compose.cloud.yml | 52 +++ docker-compose.e2e.local.yml | 10 + main.py | 18 +- requirements-billing.txt | 11 + 35 files changed, 2927 insertions(+), 104 deletions(-) create mode 100644 .env.cloud.example create mode 100644 alembic.ini create mode 100644 alembic/env.py create mode 100644 alembic/script.py.mako create mode 100644 cloud/__init__.py create mode 100644 cloud/auth.py create mode 100644 cloud/billing.py create mode 100644 cloud/config.py create mode 100644 cloud/database.py create mode 100644 cloud/emails.py create mode 100644 cloud/managed_keys.py create mode 100644 cloud/metering.py create mode 100644 cloud/models.py create mode 100644 cloud/oauth.py create mode 100644 cloud/social_profiles.py create mode 100644 dashboard/src/components/AccountPage.jsx create mode 100644 dashboard/src/components/AdvancedBanner.jsx create mode 100644 dashboard/src/components/LoginModal.jsx create mode 100644 dashboard/src/components/PricingSection.jsx create mode 100644 dashboard/src/components/TopUpModal.jsx create mode 100644 dashboard/src/components/TrialGate.jsx create mode 100644 dashboard/src/components/UsageMeter.jsx create mode 100644 dashboard/src/contexts/AuthContext.jsx create mode 100644 dashboard/src/lib/api.js create mode 100644 docker-compose.cloud.yml create mode 100644 docker-compose.e2e.local.yml create mode 100644 requirements-billing.txt diff --git a/.env.cloud.example b/.env.cloud.example new file mode 100644 index 0000000..b5f42e2 --- /dev/null +++ b/.env.cloud.example @@ -0,0 +1,38 @@ +# Cloud (paid / managed-keys) mode — env template for openshorts.app. +# Copy to .env and fill in. Only needed when running with docker-compose.cloud.yml. +# Self-hosters running plain BYOK do NOT need any of this. + +BILLING_ENABLED=true + +# Postgres (docker-compose.cloud.yml provisions the `db` service) +POSTGRES_PASSWORD=change-me +DATABASE_URL=postgresql+asyncpg://openshorts:change-me@db:5432/openshorts + +# Auth +JWT_SECRET=generate-a-long-random-string +FRONTEND_URL=https://openshorts.app +ALLOWED_ORIGINS=https://openshorts.app + +# Email — magic link (Resend) +RESEND_API_KEY=re_... +EMAIL_FROM=OpenShorts + +# Google OAuth (optional; magic link works without it) +GOOGLE_CLIENT_ID= +GOOGLE_CLIENT_SECRET= + +# Stripe (test keys shown; use live keys in production). +# Prices are resolved by lookup_key (starter_monthly, topup_60, ...) at runtime, +# so no price IDs are needed here. Create the prices with those lookup_keys. +STRIPE_SECRET_KEY=sk_test_... +STRIPE_WEBHOOK_SECRET=whsec_... + +# Managed provider keys (server-owned; only handed to entitled paid users) +MANAGED_GEMINI_API_KEY= +MANAGED_UPLOAD_POST_API_KEY= +OPENSHORTS_LOGO_URL=https://openshorts.app/logo.png + +# Residential proxy for YouTube downloads (avoids datacenter-IP bans on the +# hosted server). Recommended: DataImpulse (~$1/GB PAYG). Downloads are capped +# to 720p when this is set, to control bandwidth cost. Empty = direct download. +PROXY_URL= diff --git a/Dockerfile b/Dockerfile index 95bfd1f..31895e2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,11 +10,14 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ # Copy and install Python dependencies # Copy and install Python dependencies -COPY requirements.txt . +COPY requirements.txt requirements-billing.txt ./ RUN python -m venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt +# Cloud (paid mode) deps: installed always so one image serves both modes; they +# are only imported when BILLING_ENABLED is set. Harmless/unused in self-host. +RUN pip install --no-cache-dir -r requirements-billing.txt # Final stage FROM python:3.11-slim diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..6b8c0ee --- /dev/null +++ b/alembic.ini @@ -0,0 +1,41 @@ +# Alembic config for cloud-mode schema migrations. +# The boot path uses create_all (see cloud/database.init_engine); Alembic is here +# for controlled migrations once the schema needs to evolve. +# Usage: DATABASE_URL=... alembic revision --autogenerate -m "msg" && alembic upgrade head +[alembic] +script_location = alembic +prepend_sys_path = . + +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..d41af74 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,60 @@ +"""Alembic environment (async) for cloud-mode migrations. + +Reads the DB URL from the DATABASE_URL env var and targets cloud.models metadata, +so `alembic revision --autogenerate` works out of the box. +""" +import asyncio +import os +from logging.config import fileConfig + +from sqlalchemy import pool +from sqlalchemy.ext.asyncio import async_engine_from_config +from alembic import context + +# Register model metadata. +from cloud.database import Base +import cloud.models # noqa: F401 + +config = context.config +if config.config_file_name is not None: + fileConfig(config.config_file_name) + +db_url = os.environ.get("DATABASE_URL", "") +if db_url: + config.set_main_option("sqlalchemy.url", db_url) + +target_metadata = Base.metadata + + +def run_migrations_offline(): + context.configure( + url=config.get_main_option("sqlalchemy.url"), + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + with context.begin_transaction(): + context.run_migrations() + + +def _do_run(connection): + context.configure(connection=connection, target_metadata=target_metadata) + with context.begin_transaction(): + context.run_migrations() + + +async def run_migrations_online(): + connectable = async_engine_from_config( + config.get_section(config.config_ini_section, {}), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + async with connectable.connect() as connection: + await connection.run_sync(_do_run) + await connectable.dispose() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + asyncio.run(run_migrations_online()) diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..9dab8a1 --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,22 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/app.py b/app.py index 0da7234..6dcde0e 100644 --- a/app.py +++ b/app.py @@ -6,6 +6,8 @@ import json import shutil import glob import time +import math +import itertools import asyncio from dotenv import load_dotenv from typing import Dict, Optional, List @@ -32,14 +34,168 @@ MAX_FILE_SIZE_MB = 2048 # 2GB limit JOB_RETENTION_SECONDS = 3600 # 1 hour retention DISABLE_YOUTUBE_URL = os.environ.get("DISABLE_YOUTUBE_URL", "false").lower() in ("1", "true", "yes") +# ---- Cloud billing (paid / managed-keys) integration -------------------------- +# All paid-mode code lives in the optional `cloud/` package and is imported ONLY +# when BILLING_ENABLED is set. With the flag off, the app behaves exactly as the +# self-hosted BYOK app does today (no extra dependencies required). +BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true", "yes") + +if BILLING_ENABLED: + import cloud + from cloud import managed_keys, metering as _metering, config as _cloud_config + from cloud.auth import get_current_user_optional +else: + cloud = None + managed_keys = None + _metering = None + _cloud_config = None + + async def get_current_user_optional(request: Request): + # No-op dependency in self-host mode: every request is anonymous / BYOK. + return None + + +async def _user_from_request(request: Request): + """Load the authenticated cloud user (or None). Cheap indexed lookup.""" + return await get_current_user_optional(request) + + +async def resolve_gemini(request: Request) -> Optional[str]: + """Resolve the Gemini API key for a request. + + Cloud (hosted) is PAID-ONLY: there is no BYOK for the core pipeline, so the + ``X-Gemini-Key`` header is ignored — an entitled user (active plan or trial) + gets the managed server key, everyone else gets ``None`` (→ 402, start trial). + Self-host keeps BYOK: header wins, else the env fallback. + """ + if BILLING_ENABLED: + user = await _user_from_request(request) + if managed_keys.has_active_entitlement(user): + return managed_keys.gemini_key() + return None + header = request.headers.get("X-Gemini-Key") + if header: + return header + return os.environ.get("GEMINI_API_KEY") + + +async def resolve_upload_post(request: Request, body_key: Optional[str] = None): + """Resolve the Upload-Post key and the profile to post as. + + Returns ``(api_key, forced_profile_username_or_None)``. Cloud is paid-only: + an entitled user gets the managed key + their own forced profile (body key / + user_id ignored); a non-entitled user gets ``(None, None)``. Self-host keeps + BYOK: header, then body key, then env. + """ + if BILLING_ENABLED: + user = await _user_from_request(request) + if managed_keys.has_active_entitlement(user): + profile = await cloud.social_profiles.ensure_profile(user) + return managed_keys.upload_post_key(), profile + return None, None + header = request.headers.get("X-Upload-Post-Key") + key = header or body_key or os.environ.get("UPLOAD_POST_API_KEY") + return key, None + + +def gemini_missing_error(): + """The right 4xx when no Gemini key could be resolved. + + 402 for a signed-in-but-not-entitled cloud user (needs a plan); 400 otherwise + (BYOK header simply missing). + """ + if BILLING_ENABLED: + return HTTPException(status_code=402, detail={ + "error": "no_plan", + "message": "This action needs an active plan. Choose a plan or add your own API key.", + }) + return HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + + +async def reserve_process_minutes(request, url, input_path, job_id): + """Meter a managed /api/process request. Returns (user_id, priority, reservation_id). + + BYOK / self-host requests don't consume minutes (priority 2, no reservation). + For a managed (entitled, no BYOK header) request this probes the input + duration, enforces the per-user concurrent-job limit, and reserves minutes — + raising 402 (quota) or 429 (too many jobs) as needed. + """ + if not BILLING_ENABLED or request.headers.get("X-Gemini-Key"): + return None, 2, None + user = await _user_from_request(request) + if not managed_keys.has_active_entitlement(user): + return None, 2, None # shouldn't happen (resolve_gemini would have 402'd) + + priority = _cloud_config.PLAN_PRIORITY.get(user.plan, 1) + + # Per-user simultaneous job cap. + limit = _cloud_config.PLAN_JOB_LIMIT.get(user.plan, 2) + active = sum(1 for j in jobs.values() + if j.get('user_id') == user.id and j.get('status') in ('queued', 'processing')) + if active >= limit: + raise HTTPException(status_code=429, + detail="You already have the maximum number of jobs running. Please wait.") + + # Probe input duration (blocking → run in a thread). + loop = asyncio.get_event_loop() + try: + if url: + minutes = await loop.run_in_executor(None, _metering.probe_url_minutes, url) + else: + minutes = await loop.run_in_executor(None, _metering.probe_file_minutes, input_path) + except Exception: + raise HTTPException(status_code=400, + detail="Could not determine the video duration. Try a different source.") + minutes = max(1, math.ceil(minutes)) + + try: + reservation_id = await _metering.reserve_minutes(user.id, minutes, job_id) + except _metering.QuotaExceeded as e: + raise HTTPException(status_code=402, detail={ + "error": "quota_exceeded", + "minutes_required": e.required, + "minutes_remaining": e.remaining, + }) + return user.id, priority, reservation_id + + +async def reserve_managed_action(request, minutes, job_id, job_type): + """Reserve quota for a synchronous managed action (e.g. thumbnail image gen). + + Returns a reservation_id to commit/release around the work, or None for + BYOK / self-host. Raises 402 when the user is out of minutes. + """ + if not BILLING_ENABLED: + return None + user = await _user_from_request(request) + if not managed_keys.has_active_entitlement(user): + return None # BYOK header path (self-host) — not metered + try: + return await _metering.reserve_minutes(user.id, minutes, job_id, job_type) + except _metering.QuotaExceeded as e: + raise HTTPException(status_code=402, detail={ + "error": "quota_exceeded", + "minutes_required": e.required, + "minutes_remaining": e.remaining, + }) + # Application State -job_queue = asyncio.Queue() +# PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first: +# pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps +# FIFO order within a priority and makes the tuples always comparable. With +# BILLING disabled every job enqueues at priority 2 → plain FIFO as before. +job_queue = asyncio.PriorityQueue() +_job_seq = itertools.count() jobs: Dict[str, Dict] = {} thumbnail_sessions: Dict[str, Dict] = {} publish_jobs: Dict[str, Dict] = {} # {publish_id: {status, result, error}} # Semester to limit concurrency to MAX_CONCURRENT_JOBS concurrency_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS) + +def _enqueue_job(job_id: str, priority: int = 2): + job_queue.put_nowait((priority, next(_job_seq), job_id)) + def _relocate_root_job_artifacts(job_id: str, job_output_dir: str) -> bool: """ Backward-compat rescue: @@ -131,9 +287,9 @@ async def process_queue(): print(f"🚀 Job Queue Worker started with {MAX_CONCURRENT_JOBS} concurrent slots.") while True: try: - # Wait for a job - job_id = await job_queue.get() - + # Wait for a job (priority, seq, job_id) — lowest priority first. + _priority, _seq, job_id = await job_queue.get() + # Acquire semaphore slot (waits if max jobs are running) await concurrency_semaphore.acquire() print(f"🔄 Acquired slot for job: {job_id}") @@ -154,25 +310,51 @@ async def run_job_wrapper(job_id): except Exception as e: print(f"❌ Job wrapper error {job_id}: {e}") finally: + # Settle the minute reservation (managed jobs only): commit on success, + # release otherwise so the minutes go back to the user. + await _settle_reservation(job_id) # Always release semaphore and mark queue task done concurrency_semaphore.release() job_queue.task_done() print(f"✅ Released slot for job: {job_id}") + +async def _settle_reservation(job_id): + if not BILLING_ENABLED: + return + job = jobs.get(job_id) or {} + reservation_id = job.get('reservation_id') + if not reservation_id: + return + try: + if job.get('status') == 'completed': + await cloud.metering.commit_reservation(reservation_id) + else: + await cloud.metering.release_reservation(reservation_id) + except Exception as e: + print(f"⚠️ Reservation settle error for {job_id}: {e}") + @asynccontextmanager async def lifespan(app: FastAPI): # Start worker and cleanup worker_task = asyncio.create_task(process_queue()) cleanup_task = asyncio.create_task(cleanup_jobs()) + if BILLING_ENABLED: + await cloud.setup_async(app) yield # Cleanup (optional: cancel worker) app = FastAPI(lifespan=lifespan) -# Enable CORS for frontend +# Cloud mode: attach middleware + routers at import time (before the app serves). +if BILLING_ENABLED: + cloud.setup_sync(app) + +# Enable CORS for frontend. Cloud mode locks this down to the configured origins; +# self-host keeps the permissive wildcard it has always used. app.add_middleware( CORSMiddleware, - allow_origins=["*"], + allow_origins=cloud.settings.allowed_origins if BILLING_ENABLED else ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], @@ -311,7 +493,11 @@ async def run_job(job_id, job_data): @app.get("/api/config") async def get_config(): - return {"youtubeUrlEnabled": not DISABLE_YOUTUBE_URL} + return { + "youtubeUrlEnabled": not DISABLE_YOUTUBE_URL, + "billingEnabled": BILLING_ENABLED, + "googleAuthEnabled": bool(BILLING_ENABLED and cloud.settings.google_auth_enabled), + } @app.post("/api/process") async def process_endpoint( @@ -320,9 +506,9 @@ async def process_endpoint( url: Optional[str] = Form(None), acknowledged: Optional[str] = Form(None) ): - api_key = request.headers.get("X-Gemini-Key") + api_key = await resolve_gemini(request) if not api_key: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() ack_flag = str(acknowledged).lower() in ("1", "true", "yes") @@ -365,6 +551,7 @@ async def process_endpoint( env = os.environ.copy() env["GEMINI_API_KEY"] = api_key # Override with key from request + input_path = None if url: cmd.extend(["-u", url]) else: @@ -390,6 +577,9 @@ async def process_endpoint( print(f"[attestation] job={job_id} ip={attestation['ip']} source={attestation['source']} ack=true") + # Meter + reserve minutes for managed users (no-op for BYOK / self-host). + user_id, priority, reservation_id = await reserve_process_minutes(request, url, input_path, job_id) + # Enqueue Job jobs[job_id] = { 'status': 'queued', @@ -397,10 +587,12 @@ async def process_endpoint( 'cmd': cmd, 'env': env, 'output_dir': job_output_dir, - 'attestation': attestation + 'attestation': attestation, + 'user_id': user_id, + 'reservation_id': reservation_id, } - await job_queue.put(job_id) + _enqueue_job(job_id, priority) return {"job_id": job_id, "status": "queued"} @@ -431,13 +623,13 @@ class EditRequest(BaseModel): @app.post("/api/edit") async def edit_clip( req: EditRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") + request: Request, ): - # Determine API Key - final_api_key = req.api_key or x_gemini_key or os.environ.get("GEMINI_API_KEY") - + # BYOK body key wins; otherwise resolve header / managed / self-host env. + final_api_key = req.api_key or await resolve_gemini(request) + if not final_api_key: - raise HTTPException(status_code=400, detail="Missing Gemini API Key (Header or Body)") + raise gemini_missing_error() if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") @@ -647,13 +839,13 @@ class EffectsGenerateRequest(BaseModel): @app.post("/api/effects/generate") async def generate_effects_config( req: EffectsGenerateRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") + request: Request, ): """Generate structured EffectsConfig JSON for Remotion rendering via Gemini AI.""" - final_api_key = x_gemini_key or os.environ.get("GEMINI_API_KEY") + final_api_key = await resolve_gemini(request) if not final_api_key: - raise HTTPException(status_code=400, detail="Missing Gemini API Key (Header)") + raise gemini_missing_error() if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") @@ -1044,8 +1236,8 @@ async def translate_clip( class SocialPostRequest(BaseModel): job_id: str clip_index: int - api_key: str - user_id: str + api_key: Optional[str] = None # BYOK; ignored for managed users + user_id: Optional[str] = None # BYOK profile; ignored for managed users platforms: List[str] # ["tiktok", "instagram", "youtube"] # Optional overrides if frontend wants to edit them title: Optional[str] = None @@ -1056,14 +1248,23 @@ class SocialPostRequest(BaseModel): import httpx @app.post("/api/social/post") -async def post_to_socials(req: SocialPostRequest): +async def post_to_socials(req: SocialPostRequest, request: Request): if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") - + + # Resolve the Upload-Post key + profile. For managed users the server key is + # used and their own profile is forced (body api_key / user_id are ignored). + upload_key, forced_profile = await resolve_upload_post(request, req.api_key) + if not upload_key: + raise HTTPException(status_code=400, detail="Missing Upload-Post API key") + post_user = forced_profile or req.user_id + if not post_user: + raise HTTPException(status_code=400, detail="Missing Upload-Post user profile") + job = jobs[req.job_id] if 'result' not in job or 'clips' not in job['result']: raise HTTPException(status_code=400, detail="Job result not available") - + try: clip = job['result']['clips'][req.clip_index] # Video URL is relative /videos/..., we need absolute file path @@ -1085,12 +1286,12 @@ async def post_to_socials(req: SocialPostRequest): # Prepare form data url = "https://api.upload-post.com/api/upload" headers = { - "Authorization": f"Apikey {req.api_key}" + "Authorization": f"Apikey {upload_key}" } - + # Prepare data as dict (httpx handles lists for multiple values) data_payload = { - "user": req.user_id, + "user": post_user, "title": final_title, "platform[]": req.platforms, # Pass list directly "async_upload": "true" # Enable async upload @@ -1142,11 +1343,16 @@ async def post_to_socials(req: SocialPostRequest): raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/social/user") -async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")): - """Proxy to fetch user ID from Upload-Post""" +async def get_social_user(request: Request): + """Proxy to fetch user profiles from Upload-Post. + + BYOK: uses the caller's key and returns all profiles on that account. + Managed: uses the server key but returns ONLY the caller's own profile. + """ + api_key, forced_profile = await resolve_upload_post(request, None) if not api_key: raise HTTPException(status_code=400, detail="Missing X-Upload-Post-Key header") - + url = "https://api.upload-post.com/api/uploadposts/users" print(f"🔍 Fetching User ID from: {url}") headers = {"Authorization": f"Apikey {api_key}"} @@ -1185,10 +1391,14 @@ async def get_social_user(api_key: str = Header(..., alias="X-Upload-Post-Key")) "connected": connected }) + # Managed users must only ever see their own profile. + if forced_profile is not None: + profiles_list = [p for p in profiles_list if p.get("username") == forced_profile] + if not profiles_list: # Fallback if no profiles found return {"profiles": [], "error": "No profiles found"} - + return {"profiles": profiles_list} @@ -1276,9 +1486,9 @@ async def thumbnail_analyze( x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") ): """Analyze a video and suggest viral YouTube titles.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) if not api_key: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() pre_transcript = None @@ -1357,12 +1567,12 @@ class ThumbnailTitlesRequest(BaseModel): @app.post("/api/thumbnail/titles") async def thumbnail_titles( req: ThumbnailTitlesRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") + request: Request, ): """Refine title suggestions or accept a manual title.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) if not api_key: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() # Manual title mode - just create a session with the user's title if req.title: @@ -1419,16 +1629,20 @@ async def thumbnail_generate( count: int = Form(3), face: Optional[UploadFile] = File(None), background: Optional[UploadFile] = File(None), - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") ): """Generate YouTube thumbnails with Gemini image generation.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) if not api_key: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() # Clamp count count = min(max(1, count), 6) + # Gemini image generation is the expensive managed call — meter it against the + # plan quota (a batch ≈ THUMBNAIL_MINUTES). No-op for BYOK / self-host. + thumb_minutes = _cloud_config.THUMBNAIL_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action(request, thumb_minutes, session_id, "thumbnail") + # Save optional uploaded images face_path = None bg_path = None @@ -1469,11 +1683,18 @@ async def thumbnail_generate( if not thumbnails: raise HTTPException(status_code=500, detail="Thumbnail generation failed. Please check your Gemini API key has access to image generation (gemini-3.1-flash-image-preview model).") + # Success — charge the reserved minutes. + if reservation_id: + await _metering.commit_reservation(reservation_id) return {"thumbnails": thumbnails} except HTTPException: + if reservation_id: + await _metering.release_reservation(reservation_id) raise except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) print(f"❌ Thumbnail Generate Error: {e}") raise HTTPException(status_code=500, detail=str(e)) @@ -1485,12 +1706,12 @@ class ThumbnailDescribeRequest(BaseModel): @app.post("/api/thumbnail/describe") async def thumbnail_describe( req: ThumbnailDescribeRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key") + request: Request, ): """Generate a YouTube description with chapters from the transcript.""" - api_key = x_gemini_key + api_key = await resolve_gemini(request) if not api_key: - raise HTTPException(status_code=400, detail="Missing X-Gemini-Key header") + raise gemini_missing_error() if req.session_id not in thumbnail_sessions: raise HTTPException(status_code=404, detail="Session not found") @@ -1520,18 +1741,27 @@ async def thumbnail_describe( @app.post("/api/thumbnail/publish") async def thumbnail_publish( + request: Request, background_tasks: BackgroundTasks, session_id: str = Form(...), title: str = Form(...), description: str = Form(...), thumbnail_url: str = Form(...), - api_key: str = Form(...), - user_id: str = Form(...), + api_key: Optional[str] = Form(None), # BYOK; ignored for managed users + user_id: Optional[str] = Form(None), # BYOK profile; ignored for managed users ): """Kick off a background upload to YouTube via Upload-Post and return immediately.""" if session_id not in thumbnail_sessions: raise HTTPException(status_code=404, detail="Session not found") + # Managed users: server key + forced own profile; body fields ignored. + upload_key, forced_profile = await resolve_upload_post(request, api_key) + if not upload_key: + raise HTTPException(status_code=400, detail="Missing Upload-Post API key") + post_user = forced_profile or user_id + if not post_user: + raise HTTPException(status_code=400, detail="Missing Upload-Post user profile") + session = thumbnail_sessions[session_id] video_path = session.get("video_path") if not video_path or not os.path.exists(video_path): @@ -1555,9 +1785,9 @@ async def thumbnail_publish( """Runs in a thread via BackgroundTasks — does the actual multipart upload.""" try: upload_url = "https://api.upload-post.com/api/upload" - headers = {"Authorization": f"Apikey {api_key}"} + headers = {"Authorization": f"Apikey {upload_key}"} data_payload = { - "user": user_id, + "user": post_user, "platform[]": ["youtube"], "title": title, # required base field (fallback) "async_upload": "true", @@ -1670,12 +1900,12 @@ class SaaSAnalyzeRequest(BaseModel): @app.post("/api/saasshorts/analyze") async def saasshorts_analyze( req: SaaSAnalyzeRequest, - x_gemini_key: Optional[str] = Header(None, alias="X-Gemini-Key"), + request: Request, ): """Analyze a URL or manual description and generate video scripts.""" - gemini_key = x_gemini_key or os.environ.get("GEMINI_API_KEY") + gemini_key = await resolve_gemini(request) if not gemini_key: - raise HTTPException(status_code=400, detail="Missing Gemini API Key") + raise gemini_missing_error() if not req.url and not req.description: raise HTTPException(status_code=400, detail="Provide a URL or a product description") @@ -1811,8 +2041,8 @@ async def saasshorts_video_gallery(limit: int = 50): class SaaSPostRequest(BaseModel): job_id: str - api_key: str - user_id: str + api_key: Optional[str] = None # BYOK; ignored for managed users + user_id: Optional[str] = None # BYOK profile; ignored for managed users platforms: List[str] title: Optional[str] = None description: Optional[str] = None @@ -1821,11 +2051,18 @@ class SaaSPostRequest(BaseModel): @app.post("/api/saasshorts/post") -async def saasshorts_post_to_socials(req: SaaSPostRequest): +async def saasshorts_post_to_socials(req: SaaSPostRequest, request: Request): """Post an AI Shorts video to social media via Upload-Post.""" if req.job_id not in saas_jobs: raise HTTPException(status_code=404, detail="Job not found") + upload_key, forced_profile = await resolve_upload_post(request, req.api_key) + if not upload_key: + raise HTTPException(status_code=400, detail="Missing Upload-Post API key") + post_user = forced_profile or req.user_id + if not post_user: + raise HTTPException(status_code=400, detail="Missing Upload-Post user profile") + job = saas_jobs[req.job_id] result = job.get("result") if not result or not result.get("video_url"): @@ -1847,10 +2084,10 @@ async def saasshorts_post_to_socials(req: SaaSPostRequest): final_description = script.get("full_narration", "Check this out!") url = "https://api.upload-post.com/api/upload" - headers = {"Authorization": f"Apikey {req.api_key}"} + headers = {"Authorization": f"Apikey {upload_key}"} data_payload = { - "user": req.user_id, + "user": post_user, "title": final_title, "platform[]": req.platforms, "async_upload": "true", diff --git a/cloud/__init__.py b/cloud/__init__.py new file mode 100644 index 0000000..13b8227 --- /dev/null +++ b/cloud/__init__.py @@ -0,0 +1,47 @@ +"""Optional cloud (paid / managed-keys) mode for OpenShorts. + +This whole package is dormant unless the ``BILLING_ENABLED`` env flag is set. +``app.py`` imports it only in that case, so self-hosters never need the extra +dependencies in ``requirements-billing.txt``. + +Wiring is split in two because Starlette forbids adding middleware after the app +has started: + - ``setup_sync(app)`` -> runs at import time (middleware + routers) + - ``setup_async(app)`` -> runs in the lifespan (DB engine, sweeper, orphans) + +Both are built up phase by phase; each phase appends its own wiring. +""" +from .config import is_enabled, settings, validate_required # noqa: F401 + + +def setup_sync(app): + """Synchronous wiring done at import time (before the app serves). + + Middleware and routers must be attached here. Fails fast on missing config + so a misconfigured deploy never boots half-enabled. + """ + validate_required() + + # SessionMiddleware backs the OAuth state handshake. + from starlette.middleware.sessions import SessionMiddleware + app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret) + + from . import auth, oauth, billing, social_profiles + oauth.register() + billing._init_stripe() + app.include_router(auth.router) + app.include_router(oauth.router) + app.include_router(billing.router) + app.include_router(social_profiles.router) + + +async def setup_async(app): + """Async initialization done inside the FastAPI lifespan. + + DB engine, orphaned-reservation cleanup and the metering sweeper live here. + """ + from . import database, metering + await database.init_engine() + await metering.release_orphaned_reservations() + metering.start_sweeper() + print("☁️ Cloud billing mode ENABLED (DB ready, metering active).") diff --git a/cloud/auth.py b/cloud/auth.py new file mode 100644 index 0000000..41c072d --- /dev/null +++ b/cloud/auth.py @@ -0,0 +1,214 @@ +"""Authentication for cloud mode: magic link + JWT sessions + current-user loading. + +- Magic link: POST /api/auth/magic-link -> emailed single-use token (15 min). + POST /api/auth/magic-link/verify consumes it (POST, not GET, so email scanners + that prefetch links can't burn them) and returns a 30-day JWT. +- get_current_user_optional never raises: a missing/expired token degrades to the + anonymous BYOK flow rather than breaking it. +- /api/me returns the user's plan + minute balance (no Stripe call needed). +""" +import hashlib +import secrets +from datetime import datetime, timezone, timedelta +from typing import Optional + +import jwt +from fastapi import APIRouter, Request, HTTPException +from pydantic import BaseModel, EmailStr +from sqlalchemy import select, func, and_ + +from .config import settings +from . import database, metering +from .models import User, MagicLinkToken, UploadPostProfile + +router = APIRouter() + +JWT_ALGO = "HS256" +JWT_TTL_DAYS = 30 +MAGIC_TTL_MINUTES = 15 +MAGIC_RATE_LIMIT = 3 # per email +MAGIC_RATE_WINDOW_MIN = 15 + + +def _now(): + return datetime.now(timezone.utc) + + +# --------------------------------------------------------------------------- # +# JWT + current user +# --------------------------------------------------------------------------- # +def issue_jwt(user_id, email) -> str: + payload = { + "sub": str(user_id), + "email": email, + "exp": _now() + timedelta(days=JWT_TTL_DAYS), + "iat": _now(), + } + return jwt.encode(payload, settings.jwt_secret, algorithm=JWT_ALGO) + + +def _decode_jwt(token: str) -> Optional[dict]: + try: + return jwt.decode(token, settings.jwt_secret, algorithms=[JWT_ALGO]) + except Exception: + return None + + +class CurrentUser: + """Lightweight per-request user snapshot carried through endpoints. + + Kept small and eager (no lazy DB access) so sync helpers like + ``managed_keys.has_active_entitlement`` can read it without awaiting. + """ + + def __init__(self, id, email, entitled=False, plan=None, upload_post_profile=None): + self.id = id + self.email = email + self.entitled = entitled + self.plan = plan + self.upload_post_profile = upload_post_profile + + +async def _load_current_user(session, user_id) -> Optional["CurrentUser"]: + user = await session.get(User, user_id) + if user is None: + return None + sub = await metering._active_subscription(session, user_id) + topups = await metering._topups_fifo(session, user_id) + topup_remaining = sum( + (float(t.minutes_total) - float(t.minutes_consumed) for t in topups), 0.0 + ) + profile = await session.get(UploadPostProfile, user_id) + # Entitled to managed keys if they have an active plan OR any top-up credit. + entitled = bool(sub is not None or topup_remaining > 0) + return CurrentUser( + id=user.id, + email=user.email, + entitled=entitled, + plan=sub.plan if sub else None, + upload_post_profile=profile.profile_username if profile else None, + ) + + +async def get_current_user_optional(request: Request) -> Optional[CurrentUser]: + """Return the authenticated user, or None for anonymous / BYOK requests.""" + auth = request.headers.get("Authorization", "") + if not auth.lower().startswith("bearer "): + return None + payload = _decode_jwt(auth[7:].strip()) + if not payload: + return None + try: + import uuid + user_id = uuid.UUID(payload["sub"]) + except Exception: + return None + async with database.session() as session: + return await _load_current_user(session, user_id) + + +async def get_current_user_required(request: Request) -> CurrentUser: + user = await get_current_user_optional(request) + if user is None: + raise HTTPException(status_code=401, detail="Authentication required") + return user + + +# --------------------------------------------------------------------------- # +# Magic link +# --------------------------------------------------------------------------- # +class MagicLinkRequest(BaseModel): + email: EmailStr + + +class MagicVerifyRequest(BaseModel): + token: str + + +@router.post("/api/auth/magic-link") +async def request_magic_link(payload: MagicLinkRequest, request: Request): + from .emails import send_magic_link_email + + email = payload.email.lower() + async with database.session() as session: + async with session.begin(): + window_start = _now() - timedelta(minutes=MAGIC_RATE_WINDOW_MIN) + recent = (await session.execute( + select(func.count(MagicLinkToken.id)).where(and_( + MagicLinkToken.email == email, + MagicLinkToken.created_at >= window_start, + )) + )).scalar_one() + if recent >= MAGIC_RATE_LIMIT: + raise HTTPException(status_code=429, detail="Too many login attempts. Try again in a few minutes.") + + raw_token = secrets.token_urlsafe(32) + token_hash = hashlib.sha256(raw_token.encode()).hexdigest() + session.add(MagicLinkToken( + email=email, + token_hash=token_hash, + expires_at=_now() + timedelta(minutes=MAGIC_TTL_MINUTES), + request_ip=request.client.host if request.client else None, + )) + + link = f"{settings.frontend_url}/#/auth/verify?ml={raw_token}" + await send_magic_link_email(email, link) + return {"ok": True} + + +@router.post("/api/auth/magic-link/verify") +async def verify_magic_link(payload: MagicVerifyRequest): + token_hash = hashlib.sha256(payload.token.encode()).hexdigest() + async with database.session() as session: + async with session.begin(): + row = (await session.execute( + select(MagicLinkToken).where(MagicLinkToken.token_hash == token_hash) + .with_for_update() + )).scalar_one_or_none() + if row is None or row.used_at is not None or row.expires_at < _now(): + raise HTTPException(status_code=400, detail="This sign-in link is invalid or expired.") + row.used_at = _now() + email = row.email.lower() + + user = (await session.execute( + select(User).where(User.email == email) + )).scalar_one_or_none() + if user is None: + user = User(email=email, last_login_at=_now()) + session.add(user) + await session.flush() + else: + user.last_login_at = _now() + user_id, user_email = user.id, user.email + + token = issue_jwt(user_id, user_email) + cu = await _load_current_user(session, user_id) + return {"token": token, "user": {"id": str(user_id), "email": user_email, "entitled": cu.entitled}} + + +# --------------------------------------------------------------------------- # +# /api/me +# --------------------------------------------------------------------------- # +@router.get("/api/me") +async def get_me(request: Request): + user = await get_current_user_required(request) + async with database.session() as session: + bal = await metering._balance(session, user.id) + sub = bal["_sub"] + return { + "user": {"id": str(user.id), "email": user.email}, + "entitled": user.entitled, + "plan": bal["plan"], + "status": sub.status if sub else None, + "interval": sub.interval if sub else None, + "period_end": bal["period_end"].isoformat() if bal["period_end"] else None, + "cancel_at_period_end": sub.cancel_at_period_end if sub else False, + "minutes": { + "plan_allowance": bal["plan_allowance"], + "plan_used": bal["plan_used"], + "plan_remaining": bal["plan_remaining"], + "topup_remaining": bal["topup_remaining"], + "remaining": bal["remaining"], + }, + "upload_post_profile": user.upload_post_profile, + } diff --git a/cloud/billing.py b/cloud/billing.py new file mode 100644 index 0000000..1c81aed --- /dev/null +++ b/cloud/billing.py @@ -0,0 +1,329 @@ +"""Stripe billing: catalog, checkout, customer portal and webhooks. + +Design (matches the Stripe implementation planner for this use case): +- Stripe-hosted Checkout: subscription mode for plans, payment mode for top-ups. +- Stripe-hosted Customer Portal for self-service plan management. +- Prices resolved by stable lookup_key at runtime (no price IDs in env). +- Webhooks are idempotent (stripe_events dedupe) and order-safe (last_event_at); + every handler upserts the full object rather than applying deltas. +""" +import asyncio +from datetime import datetime, timezone + +import stripe +from fastapi import APIRouter, Request, HTTPException +from pydantic import BaseModel +from sqlalchemy import select + +from .config import settings, PLAN_MINUTES, TRIAL_DAYS, SUBSCRIPTION_LOOKUP_KEYS, TOPUP_LOOKUP_KEYS +from . import database +from .models import User, Subscription, CreditTopup, StripeEvent +from .auth import get_current_user_required + +router = APIRouter() + +_catalog = None + + +def _init_stripe(): + stripe.api_key = settings.stripe_secret_key + + +def _ts(unix) -> datetime: + return datetime.fromtimestamp(unix, tz=timezone.utc) + + +# --------------------------------------------------------------------------- # +# Catalog (resolved once by lookup_key) +# --------------------------------------------------------------------------- # +async def get_catalog(force=False): + global _catalog + if _catalog is not None and not force: + return _catalog + _init_stripe() + prices = await asyncio.to_thread( + lambda: stripe.Price.list( + lookup_keys=SUBSCRIPTION_LOOKUP_KEYS + TOPUP_LOOKUP_KEYS, + expand=["data.product"], limit=100, active=True, + ) + ) + plans, topups, by_id = [], [], {} + for p in prices.data: + md = p.metadata or {} + if p.recurring: + plan = md.get("plan") + interval = md.get("interval") or p.recurring.get("interval") + if plan not in PLAN_MINUTES: + continue + entry = { + "kind": "subscription", "price_id": p.id, "lookup_key": p.lookup_key, + "plan": plan, "interval": interval, "minutes": PLAN_MINUTES[plan], + "amount": p.unit_amount, "currency": p.currency, + } + plans.append(entry) + else: + minutes = int(md.get("topup_minutes", 0)) + entry = { + "kind": "topup", "price_id": p.id, "lookup_key": p.lookup_key, + "minutes": minutes, "amount": p.unit_amount, "currency": p.currency, + } + topups.append(entry) + by_id[p.id] = entry + _catalog = {"plans": plans, "topups": topups, "by_id": by_id} + return _catalog + + +def plan_info_for_price(price_id: str): + """Sync lookup into the cached catalog (webhook path). Returns entry or None.""" + if _catalog is None: + return None + return _catalog["by_id"].get(price_id) + + +# --------------------------------------------------------------------------- # +# Customer helper +# --------------------------------------------------------------------------- # +async def ensure_stripe_customer(user_id, email) -> str: + async with database.session() as s: + async with s.begin(): + u = await s.get(User, user_id) + if u.stripe_customer_id: + return u.stripe_customer_id + cust = await asyncio.to_thread( + lambda: stripe.Customer.create(email=email, metadata={"user_id": str(user_id)}) + ) + u.stripe_customer_id = cust.id + return cust.id + + +async def _active_sub_exists(user_id) -> bool: + async with database.session() as s: + sub = (await s.execute( + select(Subscription).where(Subscription.user_id == user_id) + )).scalar_one_or_none() + return bool(sub and sub.status in ("active", "trialing")) + + +# --------------------------------------------------------------------------- # +# Endpoints +# --------------------------------------------------------------------------- # +@router.get("/api/billing/plans") +async def list_plans(): + cat = await get_catalog() + return {"plans": cat["plans"], "topups": cat["topups"]} + + +class CheckoutRequest(BaseModel): + price_id: str + + +@router.post("/api/billing/checkout") +async def create_checkout(body: CheckoutRequest, request: Request): + user = await get_current_user_required(request) + cat = await get_catalog() + entry = cat["by_id"].get(body.price_id) + if not entry: + raise HTTPException(status_code=400, detail="Unknown price") + + mode = "subscription" if entry["kind"] == "subscription" else "payment" + if mode == "subscription" and await _active_sub_exists(user.id): + raise HTTPException(status_code=409, + detail="You already have an active plan. Manage it from your account.") + + customer_id = await ensure_stripe_customer(user.id, user.email) + fe = settings.frontend_url + kwargs = dict( + mode=mode, + customer=customer_id, + line_items=[{"price": body.price_id, "quantity": 1}], + client_reference_id=str(user.id), + success_url=f"{fe}/#/account?checkout=success", + cancel_url=f"{fe}/#/pricing?checkout=cancel", + allow_promotion_codes=True, + metadata={ + "user_id": str(user.id), + "kind": entry["kind"], + "minutes": str(entry.get("minutes", "")), + }, + ) + # Subscriptions start with a card-required free trial that auto-charges. + if mode == "subscription" and TRIAL_DAYS > 0: + kwargs["subscription_data"] = {"trial_period_days": TRIAL_DAYS} + session = await asyncio.to_thread(lambda: stripe.checkout.Session.create(**kwargs)) + return {"url": session.url} + + +@router.post("/api/billing/portal") +async def create_portal(request: Request): + user = await get_current_user_required(request) + customer_id = await ensure_stripe_customer(user.id, user.email) + session = await asyncio.to_thread(lambda: stripe.billing_portal.Session.create( + customer=customer_id, return_url=f"{settings.frontend_url}/#/account", + )) + return {"url": session.url} + + +# --------------------------------------------------------------------------- # +# Webhook +# --------------------------------------------------------------------------- # +@router.post("/api/stripe/webhook") +async def stripe_webhook(request: Request): + payload = await request.body() + sig = request.headers.get("stripe-signature", "") + try: + event = stripe.Webhook.construct_event(payload, sig, settings.stripe_webhook_secret) + except Exception: + raise HTTPException(status_code=400, detail="Invalid signature") + + # Dedupe: if we've already recorded this event, ack and skip. + async with database.session() as s: + if await s.get(StripeEvent, event["id"]): + return {"ok": True, "dedup": True} + + await handle_event(event) + + async with database.session() as s: + async with s.begin(): + from sqlalchemy.dialects.postgresql import insert as pg_insert + await s.execute(pg_insert(StripeEvent).values( + id=event["id"], type=event["type"], created=_ts(event["created"]), + ).on_conflict_do_nothing(index_elements=["id"])) + return {"ok": True} + + +async def handle_event(event: dict): + """Idempotent event dispatch. Public so tests can call it directly.""" + etype = event["type"] + obj = event["data"]["object"] + created = _ts(event["created"]) + + if etype == "checkout.session.completed" and obj.get("mode") == "payment": + await _apply_topup(obj) + elif etype in ("customer.subscription.created", "customer.subscription.updated"): + await _upsert_subscription(obj, created) + elif etype == "customer.subscription.deleted": + await _set_subscription_status(obj, "canceled", created) + elif etype == "invoice.payment_failed": + await _set_subscription_status_by_invoice(obj, "past_due", created) + elif etype == "invoice.paid": + await _set_subscription_status_by_invoice(obj, "active", created) + + +async def _user_id_for_customer(session, customer_id): + return (await session.execute( + select(User.id).where(User.stripe_customer_id == customer_id) + )).scalar_one_or_none() + + +async def _apply_topup(session_obj: dict): + """Credit a top-up from a completed one-off Checkout (idempotent by session id).""" + session_id = session_obj["id"] + minutes = int((session_obj.get("metadata") or {}).get("minutes") or 0) + if minutes <= 0: + return + async with database.session() as s: + async with s.begin(): + existing = (await s.execute( + select(CreditTopup).where(CreditTopup.stripe_session_id == session_id) + )).scalar_one_or_none() + if existing: + return + user_id = (session_obj.get("metadata") or {}).get("user_id") + if not user_id: + user_id = await _user_id_for_customer(s, session_obj.get("customer")) + if not user_id: + return + s.add(CreditTopup( + user_id=user_id, stripe_session_id=session_id, + minutes_total=minutes, minutes_consumed=0, + )) + + +def _sub_item(sub_obj: dict): + try: + return sub_obj["items"]["data"][0] + except Exception: + return {} + + +def _sub_price_id(sub_obj: dict): + try: + return _sub_item(sub_obj)["price"]["id"] + except Exception: + return None + + +def _sub_period(sub_obj: dict): + """Return (start, end) unix timestamps, from the subscription or its item. + + Newer Stripe API versions expose current_period_* on the item, older ones on + the subscription itself — support both. + """ + item = _sub_item(sub_obj) + start = sub_obj.get("current_period_start") or item.get("current_period_start") + end = sub_obj.get("current_period_end") or item.get("current_period_end") + return start, end + + +async def _upsert_subscription(sub_obj: dict, event_created: datetime): + price_id = _sub_price_id(sub_obj) + info = plan_info_for_price(price_id) + if info is None: + await get_catalog(force=True) + info = plan_info_for_price(price_id) + if info is None: + return # unknown price — ignore + plan = info["plan"] + interval = info["interval"] + minutes = PLAN_MINUTES[plan] + + async with database.session() as s: + async with s.begin(): + user_id = await _user_id_for_customer(s, sub_obj.get("customer")) + if not user_id: + return + row = (await s.execute( + select(Subscription).where(Subscription.user_id == user_id).with_for_update() + )).scalar_one_or_none() + # Order guard: ignore events older than what we've already applied. + if row and row.last_event_at and event_created < row.last_event_at: + return + start, end = _sub_period(sub_obj) + values = dict( + stripe_subscription_id=sub_obj["id"], + stripe_price_id=price_id, + plan=plan, interval=interval, status=sub_obj["status"], + minutes_per_period=minutes, + current_period_start=_ts(start), + current_period_end=_ts(end), + cancel_at_period_end=bool(sub_obj.get("cancel_at_period_end")), + last_event_at=event_created, + ) + if row is None: + s.add(Subscription(user_id=user_id, **values)) + else: + for k, v in values.items(): + setattr(row, k, v) + + +async def _set_subscription_status(sub_obj: dict, status: str, event_created: datetime): + async with database.session() as s: + async with s.begin(): + row = (await s.execute( + select(Subscription).where( + Subscription.stripe_subscription_id == sub_obj["id"] + ).with_for_update() + )).scalar_one_or_none() + if row is None: + return + if row.last_event_at and event_created < row.last_event_at: + return + row.status = status + row.last_event_at = event_created + + +async def _set_subscription_status_by_invoice(invoice_obj: dict, status: str, event_created: datetime): + sub_id = invoice_obj.get("subscription") + if not sub_id: + return + await _set_subscription_status({"id": sub_id}, status, event_created) diff --git a/cloud/config.py b/cloud/config.py new file mode 100644 index 0000000..fadbcdb --- /dev/null +++ b/cloud/config.py @@ -0,0 +1,151 @@ +"""Central configuration for the optional cloud (paid / managed-keys) mode. + +Everything here is read lazily from environment variables so that importing the +`cloud` package never has side effects. Nothing in this module is loaded unless +``BILLING_ENABLED`` is truthy (see ``cloud.is_enabled``). +""" +import os +from functools import lru_cache + + +def _flag(name: str, default: str = "") -> bool: + return os.environ.get(name, default).lower() in ("1", "true", "yes") + + +def is_enabled() -> bool: + """Master switch. When False the whole cloud package stays dormant.""" + return _flag("BILLING_ENABLED") + + +# --- Plan catalog ----------------------------------------------------------- +# minutes granted per billing period, keyed by internal plan name. This is the +# AUTHORITATIVE quota source (not Stripe price metadata, which a dashboard edit +# could change). Plan name is resolved from the Stripe price; minutes from here. +PLAN_MINUTES = { + "starter": 100, + "creator": 300, + "pro": 750, +} + +# Free trial length (days) for new subscriptions. Card required; auto-charges at +# the end. No minute cap during the trial — the card + Stripe Radar deter abuse. +TRIAL_DAYS = 3 + +# Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call +# (~$0.04/image, batch of ~3). It isn't naturally minute-metered, so each +# thumbnail generation batch consumes this many minutes from the plan quota — +# roughly matching its cost to the per-minute economics. Text (titles/desc) is free. +THUMBNAIL_MINUTES = 3 + +# Stripe prices are resolved at runtime by these stable lookup_keys, so no price +# IDs need to be copied into env vars (they differ between test and live anyway). +SUBSCRIPTION_LOOKUP_KEYS = [ + "starter_monthly", "starter_yearly", + "creator_monthly", "creator_yearly", + "pro_monthly", "pro_yearly", +] +TOPUP_LOOKUP_KEYS = ["topup_60", "topup_200"] + +# Queue priority per plan (lower dispatches first). BYOK / anonymous = 2. +PLAN_PRIORITY = { + "pro": 0, + "creator": 1, + "starter": 1, +} + +# Max simultaneous managed jobs per user, by plan. +PLAN_JOB_LIMIT = { + "pro": 3, + "creator": 2, + "starter": 2, +} + + +class Settings: + """Lazily-evaluated env-backed settings. Access attributes, not the class.""" + + # Core + @property + def database_url(self) -> str: + return os.environ.get("DATABASE_URL", "") + + @property + def jwt_secret(self) -> str: + return os.environ.get("JWT_SECRET", "") + + @property + def frontend_url(self) -> str: + return os.environ.get("FRONTEND_URL", "https://openshorts.app").rstrip("/") + + @property + def allowed_origins(self) -> list: + raw = os.environ.get("ALLOWED_ORIGINS", "") + origins = [o.strip() for o in raw.split(",") if o.strip()] + return origins or [self.frontend_url] + + # Email (Resend) + @property + def resend_api_key(self) -> str: + return os.environ.get("RESEND_API_KEY", "") + + @property + def email_from(self) -> str: + return os.environ.get("EMAIL_FROM", "OpenShorts ") + + # Google OAuth + @property + def google_client_id(self) -> str: + return os.environ.get("GOOGLE_CLIENT_ID", "") + + @property + def google_client_secret(self) -> str: + return os.environ.get("GOOGLE_CLIENT_SECRET", "") + + @property + def google_auth_enabled(self) -> bool: + return bool(self.google_client_id and self.google_client_secret) + + # Stripe + @property + def stripe_secret_key(self) -> str: + return os.environ.get("STRIPE_SECRET_KEY", "") + + @property + def stripe_webhook_secret(self) -> str: + return os.environ.get("STRIPE_WEBHOOK_SECRET", "") + + # Managed provider keys (server-owned, only handed to entitled users) + @property + def managed_gemini_key(self) -> str: + return os.environ.get("MANAGED_GEMINI_API_KEY", "") + + @property + def managed_upload_post_key(self) -> str: + return os.environ.get("MANAGED_UPLOAD_POST_API_KEY", "") + + @property + def openshorts_logo_url(self) -> str: + return os.environ.get("OPENSHORTS_LOGO_URL", "https://openshorts.app/logo.png") + + +settings = Settings() + + +def validate_required(): + """Raise a clear error if mandatory cloud settings are missing. + + Called from ``cloud.setup`` at startup so a misconfigured deploy fails fast + instead of erroring on the first paid request. + """ + missing = [] + if not settings.database_url: + missing.append("DATABASE_URL") + if not settings.jwt_secret: + missing.append("JWT_SECRET") + if missing: + raise RuntimeError( + "BILLING_ENABLED is set but required settings are missing: " + + ", ".join(missing) + + ". Set them (see docker-compose.cloud.yml) or unset BILLING_ENABLED " + "to run in self-hosted BYOK mode." + ) diff --git a/cloud/database.py b/cloud/database.py new file mode 100644 index 0000000..f3f7bc2 --- /dev/null +++ b/cloud/database.py @@ -0,0 +1,49 @@ +"""Async SQLAlchemy engine + session management for cloud mode.""" +from sqlalchemy import text +from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession +from sqlalchemy.orm import declarative_base + +from .config import settings + +Base = declarative_base() + +_engine = None +_sessionmaker = None + + +async def init_engine(): + """Create the async engine + sessionmaker and ensure the schema exists. + + Uses ``create_all`` for zero-friction boot (additive-only schema in v1). + Alembic (see ``alembic/``) is available for controlled migrations later. + """ + global _engine, _sessionmaker + if _engine is not None: + return + # Import models so their tables register on Base.metadata before create_all. + from . import models # noqa: F401 + + _engine = create_async_engine(settings.database_url, pool_pre_ping=True) + _sessionmaker = async_sessionmaker(_engine, expire_on_commit=False, class_=AsyncSession) + + async with _engine.begin() as conn: + # Case-insensitive email uniqueness. + await conn.execute(text("CREATE EXTENSION IF NOT EXISTS citext")) + await conn.run_sync(Base.metadata.create_all) + + +def get_sessionmaker(): + if _sessionmaker is None: + raise RuntimeError("Cloud DB engine not initialized — call init_engine() first.") + return _sessionmaker + + +def session(): + """Return a new AsyncSession context manager (for use outside FastAPI deps).""" + return get_sessionmaker()() + + +async def get_db(): + """FastAPI dependency yielding an AsyncSession.""" + async with get_sessionmaker()() as s: + yield s diff --git a/cloud/emails.py b/cloud/emails.py new file mode 100644 index 0000000..32f8c2f --- /dev/null +++ b/cloud/emails.py @@ -0,0 +1,36 @@ +"""Transactional email via Resend (magic-link login). + +If RESEND_API_KEY is unset (e.g. local dev), the link is printed to the server +log instead of sent, so the login flow is still testable without a real inbox. +""" +import httpx + +from .config import settings + + +async def send_magic_link_email(email: str, link: str): + if not settings.resend_api_key: + print(f"✉️ [DEV magic link] {email} -> {link}") + return + + html = f""" +
+

Sign in to OpenShorts

+

Click the button below to sign in. This link expires in 15 minutes.

+

Sign in

+

If you didn't request this, ignore this email.

+
+ """ + async with httpx.AsyncClient(timeout=15) as client: + resp = await client.post( + "https://api.resend.com/emails", + headers={"Authorization": f"Bearer {settings.resend_api_key}"}, + json={ + "from": settings.email_from, + "to": [email], + "subject": "Your OpenShorts sign-in link", + "html": html, + }, + ) + resp.raise_for_status() diff --git a/cloud/managed_keys.py b/cloud/managed_keys.py new file mode 100644 index 0000000..f61bf86 --- /dev/null +++ b/cloud/managed_keys.py @@ -0,0 +1,25 @@ +"""Resolution of server-owned (managed) provider keys for entitled users. + +Only Gemini and Upload-Post are managed in v1. ElevenLabs and fal stay BYOK. +The functions here are sync and read from the ``CurrentUser`` snapshot so they +can be called inline from ``app.py``'s resolve helpers without awaiting. +""" +from typing import Optional +from .config import settings + + +def has_active_entitlement(user) -> bool: + """True if this user may consume managed keys (active plan or top-up credit). + + The ``entitled`` flag is computed once in Fase 2/3 when the user is loaded + (active subscription OR remaining top-up minutes). + """ + return bool(user is not None and getattr(user, "entitled", False)) + + +def gemini_key() -> Optional[str]: + return settings.managed_gemini_key or None + + +def upload_post_key() -> Optional[str]: + return settings.managed_upload_post_key or None diff --git a/cloud/metering.py b/cloud/metering.py new file mode 100644 index 0000000..6238b40 --- /dev/null +++ b/cloud/metering.py @@ -0,0 +1,271 @@ +"""Minute metering: quota reservation, commit and release — atomic and restart-safe. + +Accounting model (all serialized by a per-user ``SELECT ... FOR UPDATE`` lock): + +* A subscription grants ``minutes_per_period`` for the window + ``[current_period_start, current_period_end)``. Usage against the plan is the + sum of ledger rows tagged with the current ``period_end`` and status + reserved|committed. Rows from previous periods carry a different ``period_end`` + and stop counting automatically → renewal needs no cron. +* Top-ups form a FIFO pool (``minutes_total - minutes_consumed``) that persists + across periods and survives cancellation. +* A reservation consumes IMMEDIATELY (not at commit): plan first, then top-ups + FIFO. Because the whole split happens while holding the user lock, concurrent + reservations can never oversell. ``commit`` just flips the row to committed; + ``release`` refunds the exact top-up allocation recorded on the row. + +Probing input duration (ffprobe / yt-dlp metadata) lives here too. +""" +import asyncio +import json +import math +import os +import subprocess +from datetime import datetime, timezone, timedelta +from decimal import Decimal + +from sqlalchemy import select, update, func, and_ + +from . import database +from .models import User, Subscription, CreditTopup, UsageLedger + + +SWEEP_INTERVAL_SECONDS = 15 * 60 +STUCK_RESERVATION_HOURS = 3 + + +class QuotaExceeded(Exception): + def __init__(self, remaining: float, required: float): + self.remaining = remaining + self.required = required + super().__init__(f"Quota exceeded: need {required} min, {remaining} remaining") + + +def _now(): + return datetime.now(timezone.utc) + + +def _D(x) -> Decimal: + return Decimal(str(x)) + + +# --------------------------------------------------------------------------- # +# Duration probing +# --------------------------------------------------------------------------- # +def probe_file_minutes(path: str) -> float: + """Return the media duration in minutes via ffprobe. Raises on failure.""" + out = subprocess.check_output( + ["ffprobe", "-v", "error", "-show_entries", "format=duration", + "-of", "default=noprint_wrappers=1:nokey=1", path], + stderr=subprocess.STDOUT, + ) + seconds = float(out.decode().strip()) + return seconds / 60.0 + + +def probe_url_minutes(url: str) -> float: + """Return the video duration in minutes from yt-dlp metadata (no download). + + Raises ValueError if the duration is unknown (e.g. live streams) — the caller + turns that into a 400 for managed users. + """ + import yt_dlp + with yt_dlp.YoutubeDL({"skip_download": True, "quiet": True, "no_warnings": True}) as ydl: + info = ydl.extract_info(url, download=False) + duration = info.get("duration") + if not duration: + raise ValueError("Could not determine video duration") + return float(duration) / 60.0 + + +# --------------------------------------------------------------------------- # +# Balance computation (assumes caller holds the user lock when mutating) +# --------------------------------------------------------------------------- # +async def _active_subscription(session, user_id): + row = (await session.execute( + select(Subscription).where(Subscription.user_id == user_id) + )).scalar_one_or_none() + if row and row.status in ("active", "trialing") and row.current_period_end > _now(): + return row + return None + + +async def _plan_used_this_period(session, user_id, period_end) -> Decimal: + total = (await session.execute( + select(func.coalesce(func.sum(UsageLedger.minutes_from_plan), 0)).where(and_( + UsageLedger.user_id == user_id, + UsageLedger.period_end == period_end, + UsageLedger.status.in_(("reserved", "committed")), + )) + )).scalar_one() + return _D(total) + + +async def _topups_fifo(session, user_id): + return list((await session.execute( + select(CreditTopup).where(CreditTopup.user_id == user_id) + .order_by(CreditTopup.created_at.asc()) + )).scalars()) + + +async def _balance(session, user_id): + """Return a dict of the user's current minute balance (read-only).""" + sub = await _active_subscription(session, user_id) + plan_allowance = _D(sub.minutes_per_period) if sub else _D(0) + period_end = sub.current_period_end if sub else None + plan_used = await _plan_used_this_period(session, user_id, period_end) if sub else _D(0) + plan_remaining = max(_D(0), plan_allowance - plan_used) + + topups = await _topups_fifo(session, user_id) + topup_remaining = sum((_D(t.minutes_total) - _D(t.minutes_consumed) for t in topups), _D(0)) + + return { + "plan": sub.plan if sub else None, + "plan_allowance": float(plan_allowance), + "plan_used": float(plan_used), + "plan_remaining": float(plan_remaining), + "topup_remaining": float(topup_remaining), + "remaining": float(plan_remaining + topup_remaining), + "period_end": period_end, + "_sub": sub, + "_plan_remaining_d": plan_remaining, + "_topups": topups, + } + + +async def get_balance(user_id) -> dict: + """Public read-only balance for /api/me.""" + async with database.session() as session: + b = await _balance(session, user_id) + return {k: v for k, v in b.items() if not k.startswith("_")} + + +def has_topup_credit_sync(remaining: float) -> bool: + return remaining > 0 + + +# --------------------------------------------------------------------------- # +# Reserve / commit / release +# --------------------------------------------------------------------------- # +async def reserve_minutes(user_id, minutes: float, job_id: str, job_type: str = "process"): + """Atomically reserve ``minutes``. Returns the ledger row id. + + Raises ``QuotaExceeded`` if the user lacks the minutes. Consumes plan first, + then top-ups FIFO, all under the per-user lock. + """ + minutes = _D(minutes) + async with database.session() as session: + async with session.begin(): + # Serialize all of this user's reservations. + await session.execute( + select(User.id).where(User.id == user_id).with_for_update() + ) + b = await _balance(session, user_id) + plan_remaining = b["_plan_remaining_d"] + remaining_total = _D(b["remaining"]) + if minutes > remaining_total: + raise QuotaExceeded(remaining=float(remaining_total), required=float(minutes)) + + from_plan = min(minutes, plan_remaining) + from_topup = minutes - from_plan + + allocations = [] + need = from_topup + if need > 0: + for t in b["_topups"]: + if need <= 0: + break + avail = _D(t.minutes_total) - _D(t.minutes_consumed) + if avail <= 0: + continue + take = min(avail, need) + t.minutes_consumed = _D(t.minutes_consumed) + take + allocations.append({"topup_id": str(t.id), "minutes": float(take)}) + need -= take + + row = UsageLedger( + user_id=user_id, + job_id=job_id, + job_type=job_type, + minutes=minutes, + minutes_from_plan=from_plan, + minutes_from_topup=from_topup, + topup_allocations=allocations or None, + status="reserved", + period_end=b["period_end"], + ) + session.add(row) + await session.flush() + return str(row.id) + + +async def commit_reservation(ledger_id: str): + """Flip a reservation to committed. Consumption already happened at reserve.""" + async with database.session() as session: + async with session.begin(): + row = await session.get(UsageLedger, ledger_id) + if row and row.status == "reserved": + row.status = "committed" + + +async def release_reservation(ledger_id: str): + """Release a reservation and refund its exact top-up allocation.""" + async with database.session() as session: + async with session.begin(): + row = await session.get(UsageLedger, ledger_id) + if not row or row.status != "reserved": + return + await session.execute( + select(User.id).where(User.id == row.user_id).with_for_update() + ) + for alloc in (row.topup_allocations or []): + t = await session.get(CreditTopup, alloc["topup_id"]) + if t is not None: + t.minutes_consumed = max(_D(0), _D(t.minutes_consumed) - _D(alloc["minutes"])) + row.status = "released" + + +async def release_orphaned_reservations(): + """At startup, release every still-``reserved`` row. + + Jobs live only in memory, so a restart loses all in-flight jobs; their + reservations must be refunded or they would leak quota forever. + """ + async with database.session() as session: + ids = list((await session.execute( + select(UsageLedger.id).where(UsageLedger.status == "reserved") + )).scalars()) + for lid in ids: + await release_reservation(str(lid)) + if ids: + print(f"☁️ Released {len(ids)} orphaned reservation(s) at startup.") + + +async def _sweep_once(): + cutoff = _now() - timedelta(hours=STUCK_RESERVATION_HOURS) + async with database.session() as session: + ids = list((await session.execute( + select(UsageLedger.id).where(and_( + UsageLedger.status == "reserved", + UsageLedger.created_at < cutoff, + )) + )).scalars()) + for lid in ids: + await release_reservation(str(lid)) + if ids: + print(f"☁️ Swept {len(ids)} stuck reservation(s).") + + +async def _sweeper_loop(): + while True: + try: + await asyncio.sleep(SWEEP_INTERVAL_SECONDS) + await _sweep_once() + except asyncio.CancelledError: + break + except Exception as e: # never let the sweeper die + print(f"⚠️ Metering sweeper error: {e}") + + +def start_sweeper(): + asyncio.create_task(_sweeper_loop()) diff --git a/cloud/models.py b/cloud/models.py new file mode 100644 index 0000000..d265243 --- /dev/null +++ b/cloud/models.py @@ -0,0 +1,105 @@ +"""SQLAlchemy models for cloud mode. + +Money and quota live here, so the accounting tables (subscriptions, credit_topups, +usage_ledger) are designed for atomic, restart-safe metering — see cloud/metering.py. +""" +import uuid +from sqlalchemy import ( + Column, String, Integer, Numeric, Boolean, DateTime, ForeignKey, Text, func, Index, +) +from sqlalchemy.dialects.postgresql import UUID, CITEXT, JSONB + +from .database import Base + + +def _uuid(): + return uuid.uuid4() + + +class User(Base): + __tablename__ = "users" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + email = Column(CITEXT, unique=True, nullable=False) + google_sub = Column(Text, unique=True, nullable=True) + stripe_customer_id = Column(Text, unique=True, nullable=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + last_login_at = Column(DateTime(timezone=True), nullable=True) + + +class MagicLinkToken(Base): + __tablename__ = "magic_link_tokens" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + email = Column(CITEXT, nullable=False) + token_hash = Column(Text, unique=True, nullable=False) # sha256 of the raw token + expires_at = Column(DateTime(timezone=True), nullable=False) + used_at = Column(DateTime(timezone=True), nullable=True) + request_ip = Column(Text, nullable=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + __table_args__ = (Index("ix_magic_email_created", "email", "created_at"),) + + +class Subscription(Base): + __tablename__ = "subscriptions" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), + unique=True, nullable=False) # one active sub per user + stripe_subscription_id = Column(Text, unique=True, nullable=False) + stripe_price_id = Column(Text, nullable=True) + plan = Column(String(20), nullable=False) # starter | creator | pro + interval = Column(String(10), nullable=False) # month | year + status = Column(String(20), nullable=False) # active | trialing | past_due | canceled | incomplete + minutes_per_period = Column(Integer, nullable=False) + current_period_start = Column(DateTime(timezone=True), nullable=False) + current_period_end = Column(DateTime(timezone=True), nullable=False) + cancel_at_period_end = Column(Boolean, nullable=False, default=False) + last_event_at = Column(DateTime(timezone=True), nullable=True) # ordering guard for webhooks + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) + + +class CreditTopup(Base): + __tablename__ = "credit_topups" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), + nullable=False, index=True) + stripe_session_id = Column(Text, unique=True, nullable=True) # idempotency for the webhook + minutes_total = Column(Integer, nullable=False) + minutes_consumed = Column(Numeric(10, 2), nullable=False, default=0) # FIFO drain target + created_at = Column(DateTime(timezone=True), server_default=func.now()) + + +class UsageLedger(Base): + __tablename__ = "usage_ledger" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), nullable=False) + job_id = Column(Text, nullable=False) + job_type = Column(String(20), nullable=False, default="process") + minutes = Column(Numeric(10, 2), nullable=False) # total reserved + minutes_from_plan = Column(Numeric(10, 2), nullable=False, default=0) + minutes_from_topup = Column(Numeric(10, 2), nullable=False, default=0) + # [{topup_id, minutes}] — exact FIFO allocation, so release can refund precisely. + topup_allocations = Column(JSONB, nullable=True) + status = Column(String(12), nullable=False, default="reserved") # reserved | committed | released + period_end = Column(DateTime(timezone=True), nullable=True) # sub period this counts against + created_at = Column(DateTime(timezone=True), server_default=func.now()) + updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now()) + __table_args__ = ( + Index("ix_usage_user_status", "user_id", "status"), + Index("ix_usage_user_period_status", "user_id", "period_end", "status"), + ) + + +class UploadPostProfile(Base): + __tablename__ = "upload_post_profiles" + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), + primary_key=True) + profile_username = Column(Text, unique=True, nullable=False) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + + +class StripeEvent(Base): + __tablename__ = "stripe_events" + id = Column(Text, primary_key=True) # Stripe event.id — dedupe key + type = Column(Text, nullable=True) + created = Column(DateTime(timezone=True), nullable=True) + processed_at = Column(DateTime(timezone=True), server_default=func.now()) diff --git a/cloud/oauth.py b/cloud/oauth.py new file mode 100644 index 0000000..0b30f06 --- /dev/null +++ b/cloud/oauth.py @@ -0,0 +1,93 @@ +"""Google OAuth (redirect flow) for cloud mode. + +GET /api/auth/google -> redirect to Google consent +GET /api/auth/google/callback -> exchange code, upsert user, redirect to the + frontend with the JWT in the URL hash (never + reaches server logs). + +Registration happens in ``register()`` (called from setup_sync) only when Google +credentials are configured; otherwise the endpoints 404. +""" +from datetime import datetime, timezone + +from fastapi import APIRouter, Request, HTTPException +from starlette.responses import RedirectResponse +from sqlalchemy import select + +from .config import settings +from . import database +from .models import User +from .auth import issue_jwt + +router = APIRouter() +oauth = None + + +def register(): + """Register the Google OAuth client if credentials are present.""" + global oauth + if not settings.google_auth_enabled: + return + from authlib.integrations.starlette_client import OAuth + oauth = OAuth() + oauth.register( + name="google", + client_id=settings.google_client_id, + client_secret=settings.google_client_secret, + server_metadata_url="https://accounts.google.com/.well-known/openid-configuration", + client_kwargs={"scope": "openid email profile"}, + ) + + +def _now(): + return datetime.now(timezone.utc) + + +@router.get("/api/auth/google") +async def google_login(request: Request): + if oauth is None: + raise HTTPException(status_code=404, detail="Google login not configured") + redirect_uri = str(request.url_for("google_callback")) + return await oauth.google.authorize_redirect(request, redirect_uri) + + +@router.get("/api/auth/google/callback", name="google_callback") +async def google_callback(request: Request): + if oauth is None: + raise HTTPException(status_code=404, detail="Google login not configured") + try: + token = await oauth.google.authorize_access_token(request) + except Exception: + return RedirectResponse(f"{settings.frontend_url}/#/auth/callback?error=oauth") + + userinfo = token.get("userinfo") + if not userinfo: + userinfo = await oauth.google.userinfo(token=token) + email = (userinfo.get("email") or "").lower() + google_sub = userinfo.get("sub") + if not email: + return RedirectResponse(f"{settings.frontend_url}/#/auth/callback?error=noemail") + + async with database.session() as session: + async with session.begin(): + user = (await session.execute( + select(User).where(User.google_sub == google_sub) + )).scalar_one_or_none() + if user is None: + # Merge with an existing magic-link account of the same email. + user = (await session.execute( + select(User).where(User.email == email) + )).scalar_one_or_none() + if user is None: + user = User(email=email, google_sub=google_sub, last_login_at=_now()) + session.add(user) + await session.flush() + else: + user.google_sub = google_sub + user.last_login_at = _now() + else: + user.last_login_at = _now() + user_id, user_email = user.id, user.email + + jwt_token = issue_jwt(user_id, user_email) + return RedirectResponse(f"{settings.frontend_url}/#/auth/callback?token={jwt_token}") diff --git a/cloud/social_profiles.py b/cloud/social_profiles.py new file mode 100644 index 0000000..e7fe0c9 --- /dev/null +++ b/cloud/social_profiles.py @@ -0,0 +1,102 @@ +"""Upload-Post white-label profiles for managed users. + +Each OpenShorts user maps to one Upload-Post profile (a container for their +connected socials). We create it lazily and generate branded connection links so +the user connects TikTok/IG/YouTube on a page that looks like OpenShorts. + +Docs: https://docs.upload-post.com/guides/user-profile-integration +""" +import httpx +from fastapi import APIRouter, Request, HTTPException + +from .config import settings +from . import database +from .models import UploadPostProfile + +router = APIRouter() + +API_BASE = "https://api.upload-post.com/api" +CONNECT_PLATFORMS = ["tiktok", "instagram", "youtube"] + + +def _auth_headers(): + return {"Authorization": f"Apikey {settings.managed_upload_post_key}"} + + +def profile_username_for(user_id) -> str: + return f"os_{user_id.hex[:12]}" + + +async def _create_remote_profile(username: str): + """Create the profile in Upload-Post. Treat 'already exists' as success.""" + async with httpx.AsyncClient(timeout=20) as client: + resp = await client.post( + f"{API_BASE}/uploadposts/users", + headers=_auth_headers(), + json={"username": username}, + ) + if resp.status_code in (200, 201): + return + text = resp.text.lower() + # Idempotency: if it already exists, that's fine. + if resp.status_code == 400 and ("exist" in text or "already" in text): + return + # Upload-Post plan cap reached — surface a clean, actionable error, not a 500. + if "profile_limit_reached" in text or "limit of" in text: + raise HTTPException( + status_code=503, + detail="Social posting is temporarily unavailable (provider profile limit). " + "Please try again later.", + ) + resp.raise_for_status() + + +async def ensure_profile(user) -> str: + """Return the user's Upload-Post profile username, creating it if needed.""" + async with database.session() as s: + prof = await s.get(UploadPostProfile, user.id) + if prof: + return prof.profile_username + + username = profile_username_for(user.id) + await _create_remote_profile(username) + + async with database.session() as s: + async with s.begin(): + prof = await s.get(UploadPostProfile, user.id) # re-check under txn + if prof: + return prof.profile_username + s.add(UploadPostProfile(user_id=user.id, profile_username=username)) + return username + + +async def get_connect_url(username: str) -> str: + """Generate a branded, single-use connection URL (~1h) for the user's socials.""" + payload = { + "username": username, + "logoImage": settings.openshorts_logo_url, + "connectTitle": "Connect your social accounts", + "connectDescription": "Link TikTok, Instagram and YouTube to post your shorts directly from OpenShorts.", + "redirectUrl": f"{settings.frontend_url}/#/account?connected=1", + "redirectButtonText": "Back to OpenShorts", + "platforms": CONNECT_PLATFORMS, + } + async with httpx.AsyncClient(timeout=20) as client: + resp = await client.post( + f"{API_BASE}/uploadposts/users/generate-jwt", + headers=_auth_headers(), + json=payload, + ) + resp.raise_for_status() + data = resp.json() + return data.get("access_url") or data.get("url") + + +@router.post("/api/social/connect") +async def social_connect(request: Request): + """Return a branded Upload-Post connection URL for the signed-in managed user.""" + from .auth import get_current_user_required + user = await get_current_user_required(request) + username = await ensure_profile(user) + access_url = await get_connect_url(username) + return {"access_url": access_url} diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index fb0e912..d992ffc 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -9,6 +9,13 @@ import ThumbnailStudio from './components/ThumbnailStudio'; import SaaShortsTab from './components/SaaShortsTab'; import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; +import UsageMeter from './components/UsageMeter'; +import TopUpModal from './components/TopUpModal'; +import LoginModal from './components/LoginModal'; +import TrialGate from './components/TrialGate'; +import AdvancedBanner from './components/AdvancedBanner'; +import { useAuth } from './contexts/AuthContext'; +import { apiFetch, apiJson, QuotaError } from './lib/api'; import { getApiUrl } from './config'; // Enhanced "Encryption" using XOR + Base64 with a Salt @@ -134,6 +141,12 @@ const pollJob = async (jobId) => { }; function App() { + // Cloud auth/billing session (inert when billing is disabled). + const { billingEnabled, isManaged, isSignedIn, signingIn } = useAuth(); + const [showLogin, setShowLogin] = useState(false); + const [showTopUp, setShowTopUp] = useState(false); + const [topUpInfo, setTopUpInfo] = useState({}); + const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || ''); // Social API State - Load encrypted or plain const [uploadPostKey, setUploadPostKey] = useState(() => { @@ -320,8 +333,34 @@ function App() { } }; + // Hosted is paid-only (no BYOK core). Self-host uses BYOK keys. + // `keysMissing` now means "self-host BYOK keys missing" — it never fires on hosted. + const keysMissing = !billingEnabled && (!apiKey || !uploadPostKey); + const needsPlan = billingEnabled && !isManaged; // hosted, signed-out or no active plan/trial + // Included in the plan (fully managed, no keys): Clip Generator + YouTube Studio. + // Advanced (bring your own fal.ai + ElevenLabs keys): AI Shorts + AI Agent. + const INCLUDED_TOOL_TABS = ['dashboard', 'thumbnails']; + const ADVANCED_TOOL_TABS = ['saasshorts', 'ai-agent']; + const TOOL_NAMES = { dashboard: 'the Clip Generator', thumbnails: 'the YouTube Studio' }; + const gateThisTab = needsPlan && INCLUDED_TOOL_TABS.includes(activeTab); // included tool, no plan yet + const advancedThisTab = billingEnabled && ADVANCED_TOOL_TABS.includes(activeTab); // BYOK-notice tools + + // Managed users connect their socials via Upload-Post's branded hosted page. + const handleConnectSocials = async () => { + try { + const { access_url } = await apiJson('/api/social/connect', { method: 'POST' }); + if (access_url) window.open(access_url, '_blank', 'noopener'); + } catch (e) { + alert('Could not open the connection page. Please try again.'); + } + }; + const handleProcess = async (data) => { - if (!apiKey || !uploadPostKey) { + // Hosted: must be signed in AND on an active plan/trial. Self-host: BYOK keys. + if (billingEnabled) { + if (!isSignedIn) { setShowLogin(true); return; } + if (!isManaged) { window.location.hash = '#/pricing'; return; } + } else if (keysMissing) { setShowKeyModal(true); return; } @@ -332,7 +371,9 @@ function App() { try { let body; - const headers = { 'X-Gemini-Key': apiKey }; + // BYOK sends the Gemini header; managed users rely on the bearer token + // that apiFetch attaches automatically. + const headers = apiKey ? { 'X-Gemini-Key': apiKey } : {}; if (data.type === 'url') { headers['Content-Type'] = 'application/json'; @@ -344,17 +385,19 @@ function App() { body = formData; } - const res = await fetch(getApiUrl('/api/process'), { - method: 'POST', - headers: data.type === 'url' ? headers : { 'X-Gemini-Key': apiKey }, - body - }); + const res = await apiFetch('/api/process', { method: 'POST', headers, body }); if (!res.ok) throw new Error(await res.text()); const resData = await res.json(); setJobId(resData.job_id); } catch (e) { + if (e instanceof QuotaError) { + setStatus('idle'); + setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining }); + setShowTopUp(true); + return; + } setStatus('error'); setLogs(l => [...l, `Error starting job: ${e.message}`]); } @@ -503,11 +546,28 @@ function App() { /> )} - {(!apiKey || !uploadPostKey) && ( + {/* Cloud: minutes meter + account/sign-in */} + {billingEnabled && isManaged && ( + { window.location.hash = '#/account'; }} /> + )} + {billingEnabled && isSignedIn && !isManaged && ( + + )} + {billingEnabled && !isSignedIn && ( + + )} + + {keysMissing && ( + + ) : billingEnabled ? ( +
+
+

Start your free trial

+ 3 days free +
+

+ Generate shorts with zero setup — no API keys needed. 3 days free, then from $12/mo. Cancel anytime. +

+ +
+ ) : ( + <>
@@ -620,14 +716,17 @@ function App() {
+ + )} +

Video Translation

- Optional + Your own key

- Translate your clips to different languages using ElevenLabs AI dubbing. - Automatically translates speech while preserving the original voice characteristics. + For AI Shorts & dubbing — bring your own key. Translate your clips to different + languages using ElevenLabs AI dubbing (billed by ElevenLabs). Not covered by your plan.

@@ -674,11 +773,12 @@ function App() {

AI Shorts (UGC Videos)

- New + Your own key

Generate UGC-style videos with AI actors for any product or business using fal.ai. - Just describe your product or paste a URL. Requires fal.ai + ElevenLabs API keys. + Not covered by your plan — bring your own fal.ai + ElevenLabs keys (billed by those + providers, ~$0.65-2 per video). Your plan still covers the AI script & orchestration.

@@ -726,7 +826,7 @@ function App() { {/* View: SaaS Shorts */} {activeTab === 'saasshorts' && ( - + )} {/* View: AI Agent */} @@ -852,7 +952,7 @@ function App() { {/* View: Thumbnails */} {activeTab === 'thumbnails' && ( - + )} {/* View: Gallery */} @@ -1106,6 +1206,15 @@ function App() { uploadPostKey={uploadPostKey} uploadUserId={uploadUserId} /> + + {showLogin && setShowLogin(false)} />} + {showTopUp && ( + setShowTopUp(false)} + required={topUpInfo.required} + remaining={topUpInfo.remaining} + /> + )}
); } diff --git a/dashboard/src/Landing.jsx b/dashboard/src/Landing.jsx index 5f3e124..0789c94 100644 --- a/dashboard/src/Landing.jsx +++ b/dashboard/src/Landing.jsx @@ -136,7 +136,7 @@ export default function Landing({ onLaunchApp }) { }, { question: "Is OpenShorts really free? What's the catch?", - answer: "OpenShorts is 100% free and open source. You self-host it using Docker on your own machine or server. It uses three external APIs — all with free tiers. Google Gemini API (required) powers the AI analysis, viral moment detection, and thumbnail generation — its free tier includes 1,500 requests per day. ElevenLabs API (optional) enables AI voice dubbing in 30+ languages — free tier included. Upload-Post API (optional) is a social media API that allows direct publishing to YouTube, TikTok, and Instagram — 10 free uploads/month, no credit card required. There are no watermarks, no usage limits, no monthly subscriptions, and no per-video fees — unlike Opus Clip ($15-228/month) or Kapwing ($24-79/month)." + answer: "There are two ways to use OpenShorts. (1) Self-hosted is 100% free and open source: you run it with Docker on your own machine, bring your own API keys, and there are no watermarks, no usage limits, and no subscription. Google Gemini API (required) powers the AI analysis — its free tier includes 1,500 requests/day. ElevenLabs (optional) enables AI dubbing in 30+ languages. Upload-Post (optional) publishes to YouTube, TikTok, and Instagram. (2) Hosted at openshorts.app is the no-setup option: we run all the AI and compute for you and you don't need any API keys — it's a paid service with a 3-day free trial, then plans from $12/mo for 100 minutes of video. So: free if you self-host, paid if you want us to host it for you. Both are far cheaper than Opus Clip ($15-228/month) or Kapwing ($24-79/month)." }, { question: "How does OpenShorts compare to Opus Clip?", @@ -259,6 +259,11 @@ export default function Landing({ onLaunchApp }) {
+

+ Free to self-host with Docker (bring your own keys) · + or use it here with no setup — 3-day free trial, then from $12/mo +

+ {/* Platform Icons */}
Export to: @@ -302,6 +307,46 @@ export default function Landing({ onLaunchApp }) {
+ {/* Two ways to use it: free self-host vs paid hosted */} +
+
+

Two ways to use OpenShorts

+

Run it yourself for free, or let us run everything for you.

+
+
+
+
+ +

Self-hosted

+ Free +
+

+ 100% free and open source. Run it with Docker on your own machine, bring your own API keys, + no limits, no subscription. Best if you're technical and want full control. +

+ + Get it on GitHub + +
+
+
+ +

Hosted on openshorts.app

+ From $12/mo +
+

+ Zero setup, no API keys, we run all the AI and compute for you. 3-day free trial, then a plan + from $12/mo (100 min). Best if you just want to make clips without any technical hassle. +

+ +
+
+
+ {/* 3 Tools in 1 Section */}
diff --git a/dashboard/src/components/AccountPage.jsx b/dashboard/src/components/AccountPage.jsx new file mode 100644 index 0000000..cae7fef --- /dev/null +++ b/dashboard/src/components/AccountPage.jsx @@ -0,0 +1,135 @@ +import React, { useState, useEffect, useCallback } from 'react'; +import { Loader2, CreditCard, LogOut, Zap, Plus } from 'lucide-react'; +import { useAuth } from '../contexts/AuthContext'; +import { apiJson } from '../lib/api'; + +const fmt1 = (n) => Math.round((n || 0) * 10) / 10; + +// Account/billing page: plan, usage meter, top-ups, manage billing, logout. +export default function AccountPage() { + const { me, refreshMe, logout, plan, minutes } = useAuth(); + const [busy, setBusy] = useState(false); + const [topups, setTopups] = useState([]); + const [activating, setActivating] = useState(false); + + // After returning from Checkout the webhook may lag — poll /api/me briefly. + useEffect(() => { + const hash = window.location.hash || ''; + if (!hash.includes('checkout=success')) return; + setActivating(true); + let tries = 0; + const t = setInterval(async () => { + tries += 1; + const data = await refreshMe(); + if ((data && data.plan) || tries > 15) { + clearInterval(t); + setActivating(false); + window.location.hash = '#/account'; + } + }, 2000); + return () => clearInterval(t); + }, [refreshMe]); + + useEffect(() => { + apiJson('/api/billing/plans').then((d) => setTopups(d.topups || [])).catch(() => {}); + }, []); + + const openPortal = useCallback(async () => { + setBusy(true); + try { + const { url } = await apiJson('/api/billing/portal', { method: 'POST' }); + window.location.href = url; + } catch (e) { setBusy(false); alert('Could not open billing portal.'); } + }, []); + + const buyTopup = useCallback(async (price_id) => { + setBusy(true); + 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(false); alert('Could not start checkout.'); } + }, []); + + if (!me) return
; + + const m = minutes || {}; + const total = (m.plan_allowance || 0) + (m.topup_remaining || 0) + (m.plan_used || 0); + const usedPct = total > 0 ? Math.min(100, ((m.plan_used || 0) / (m.plan_allowance || 1)) * 100) : 0; + + return ( +
+
+
+

Your account

+

{me.user?.email}

+
+ +
+ + {activating && ( +
+ Activating your plan… +
+ )} + +
+
+
+ {plan ? `${plan} plan` : 'No active plan'} + {me.status && me.status !== 'active' && ( + {me.status} + )} + {me.cancel_at_period_end && ( + cancels at period end + )} +
+ +
+ +
+
+ Plan minutes + {fmt1(m.plan_used)} / {fmt1(m.plan_allowance)} used +
+
+
+
+
+ Top-up minutes + {fmt1(m.topup_remaining)} remaining +
+
+ Total remaining + {fmt1(m.remaining)} min +
+
+
+ + {topups.length > 0 && ( +
+

Buy more minutes

+

Top-ups never expire while your plan is active.

+
+ {topups.map((t) => ( + + ))} +
+
+ )} +
+ ); +} diff --git a/dashboard/src/components/AdvancedBanner.jsx b/dashboard/src/components/AdvancedBanner.jsx new file mode 100644 index 0000000..5887271 --- /dev/null +++ b/dashboard/src/components/AdvancedBanner.jsx @@ -0,0 +1,27 @@ +import React from 'react'; +import { KeyRound, ArrowRight } from 'lucide-react'; + +// Banner for advanced tools (AI Shorts, AI Agent) that use fal.ai + ElevenLabs. +// These are BYOK: the plan covers the script/orchestration, the user brings their +// own keys for the premium generation. If they have no plan yet, also nudge trial. +export default function AdvancedBanner({ needsPlan, onKeys }) { + return ( +
+
+ +
+ Advanced tool.{' '} + {needsPlan + ? <>Start your 3-day free trial to unlock. This tool also uses your own fal.ai + ElevenLabs keys (you pay those providers). + : <>AI video & voice generation use your own fal.ai + ElevenLabs keys — add them in Settings. Script & orchestration are included in your plan.} +
+
+ +
+ ); +} diff --git a/dashboard/src/components/LoginModal.jsx b/dashboard/src/components/LoginModal.jsx new file mode 100644 index 0000000..83cbd86 --- /dev/null +++ b/dashboard/src/components/LoginModal.jsx @@ -0,0 +1,91 @@ +import React, { useState } from 'react'; +import { X, Mail, Check, Loader2 } from 'lucide-react'; +import { useAuth } from '../contexts/AuthContext'; + +// Sign-in modal: magic link (email) + Google OAuth. +export default function LoginModal({ onClose }) { + const { requestMagicLink, loginWithGoogle, googleAuthEnabled } = useAuth(); + const [email, setEmail] = useState(''); + const [sent, setSent] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + + const submit = async (e) => { + e.preventDefault(); + if (!email.trim()) return; + setBusy(true); + setError(''); + try { + await requestMagicLink(email.trim()); + setSent(true); + } catch (err) { + setError(err.message || 'Something went wrong.'); + } finally { + setBusy(false); + } + }; + + return ( +
+
+ + +

Sign in to OpenShorts

+

Access your plan and generate shorts with no API keys.

+ + {sent ? ( +
+
+ +
+

Check your inbox

+

We sent a sign-in link to {email}. It expires in 15 minutes.

+
+ ) : ( + <> +
+
+ + setEmail(e.target.value)} + placeholder="you@email.com" + className="input-field pl-10" + autoFocus + /> +
+ {error &&

{error}

} + +
+ + {googleAuthEnabled && ( + <> +
+
+ or +
+
+ + + )} + + )} +
+
+ ); +} diff --git a/dashboard/src/components/PricingSection.jsx b/dashboard/src/components/PricingSection.jsx new file mode 100644 index 0000000..529b612 --- /dev/null +++ b/dashboard/src/components/PricingSection.jsx @@ -0,0 +1,171 @@ +import React, { useState, useEffect } from 'react'; +import { Check, Loader2, Zap, Github, Server } from 'lucide-react'; +import { useAuth } from '../contexts/AuthContext'; +import { apiJson } from '../lib/api'; + +const PLAN_ORDER = ['starter', 'creator', 'pro']; +const PLAN_BLURB = { + starter: 'For getting started', + creator: 'For regular creators', + pro: 'For power users & teams', +}; +const HIGHLIGHT = 'creator'; + +const fmt = (amount, currency) => + new Intl.NumberFormat('en-US', { style: 'currency', currency: (currency || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((amount || 0) / 100); + +// 3-tier pricing with monthly/annual toggle. Checkout requires sign-in. +export default function PricingSection({ onRequireLogin }) { + const { isSignedIn } = useAuth(); + const [plans, setPlans] = useState([]); + const [interval, setInterval] = useState('month'); + const [loading, setLoading] = useState(true); + const [busyPrice, setBusyPrice] = useState(null); + + useEffect(() => { + apiJson('/api/billing/plans') + .then((d) => setPlans(d.plans || [])) + .catch(() => setPlans([])) + .finally(() => setLoading(false)); + }, []); + + const checkout = async (price_id) => { + if (!isSignedIn) { onRequireLogin?.(price_id); return; } + setBusyPrice(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) { + setBusyPrice(null); + alert('Could not start checkout. Please try again.'); + } + }; + + if (loading) { + return
; + } + + const byPlan = (plan) => plans.find((p) => p.plan === plan && p.interval === interval); + + return ( +
+
+ Monthly + + + Yearly · 2 months free + +
+ +
+ {PLAN_ORDER.map((plan) => { + const entry = byPlan(plan); + if (!entry) return null; + const highlight = plan === HIGHLIGHT; + return ( +
+ {highlight && ( + + Most popular + + )} +

{plan}

+

{PLAN_BLURB[plan]}

+
+ {fmt(entry.amount, entry.currency)} + /{interval === 'month' ? 'mo' : 'yr'} +
+
    +
  • {entry.minutes} min of video / month
  • +
  • No API keys needed
  • +
  • Gemini + auto-posting included
  • + {plan === 'pro' &&
  • Priority processing queue
  • } +
+ +

3 days free, then billed monthly. Cancel anytime.

+
+ ); + })} +
+ + {/* What every plan includes vs what's bring-your-own-key */} +
+
+

+ Included in every plan +

+
    +
  • Clip Generator — fully managed, no API keys
  • +
  • YouTube Studio — titles, thumbnails, descriptions
  • +
  • Auto-posting to TikTok, Reels & Shorts
  • +
  • All the AI & compute run on our servers
  • +
+

+ Your monthly minutes cover video processing. Titles & descriptions are free; + AI thumbnail image generation uses ~3 min of your quota per batch. +

+
+
+

+ Bring your own key +

+

+ AI Shorts (AI-actor UGC videos) and voice dubbing use premium generation from + fal.ai and ElevenLabs. Connect your own keys for those — you're billed by those + providers directly (typically ~$0.65-2 per video). Your plan still covers the script & orchestration. +

+

Managed credits for these are coming later — no keys needed.

+
+
+ + {/* Free self-hosted path — the honest "free" option */} +
+
+
+
+
+

+ Free forever — self-hosted + $0 +

+

+ OpenShorts is open source. Run it on your own machine with Docker and use it completely free — + you just bring your own API keys and your own hardware. The plans above are for the + hosted version on this site: zero setup, no keys, we run everything for you. +

+
+
+ + Self-host free + +
+
+ +

+ Use it free on your own computer, or skip the setup and use it here — 3 days free, then a plan. +

+
+ ); +} diff --git a/dashboard/src/components/SaaShortsTab.jsx b/dashboard/src/components/SaaShortsTab.jsx index 6ffadbb..e905c19 100644 --- a/dashboard/src/components/SaaShortsTab.jsx +++ b/dashboard/src/components/SaaShortsTab.jsx @@ -1,6 +1,7 @@ import React, { useState, useEffect } from 'react'; import { Globe, Sparkles, Download, Copy, Check, ChevronRight, ChevronLeft, Loader2, AlertCircle, Volume2, User, Film, Terminal, ChevronDown, RefreshCw, Zap, Target, TrendingUp, MessageSquare, Eye, Share2, Calendar, Upload } from 'lucide-react'; import { getApiUrl } from '../config'; +import { apiFetch } from '../lib/api'; const STYLE_OPTIONS = [ { id: 'ugc', label: 'UGC Natural', desc: 'Authentic, talking to camera' }, @@ -34,7 +35,11 @@ function saveCache(url, analysis, webResearch, scripts) { } catch { /* localStorage full */ } } -export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uploadPostKey, uploadUserId }) { +export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uploadPostKey, uploadUserId, managed = false }) { + // Managed (hosted plan): Gemini (script) + Upload-Post run server-side via the + // bearer token — no BYOK Gemini key needed. fal.ai + ElevenLabs stay BYOK. + const geminiHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {}; + const needsGeminiKey = !geminiApiKey && !managed; // Wizard state const [step, setStep] = useState(() => { const cache = loadCache(); @@ -186,7 +191,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo const handleAnalyze = async () => { if (!url.trim() && !description.trim()) return; - if (!geminiApiKey) { + if (needsGeminiKey) { setAnalyzeError('Gemini API key required. Set it in Settings.'); return; } @@ -195,11 +200,11 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo setAnalyzeError(''); try { - const res = await fetch(getApiUrl('/api/saasshorts/analyze'), { + const res = await apiFetch('/api/saasshorts/analyze', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey, + ...geminiHeader, }, body: JSON.stringify({ url: url.trim() || undefined, @@ -274,7 +279,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo scriptToSend.full_narration = editedNarration; } - const res = await fetch(getApiUrl('/api/saasshorts/generate'), { + const res = await apiFetch('/api/saasshorts/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -320,7 +325,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo scriptToSend.full_narration = editedNarration; } - const res = await fetch(getApiUrl('/api/saasshorts/generate'), { + const res = await apiFetch('/api/saasshorts/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -1467,7 +1472,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo payload.scheduled_date = new Date(scheduleDate).toISOString(); payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; } - const res = await fetch(getApiUrl('/api/saasshorts/post'), { + const res = await apiFetch('/api/saasshorts/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), diff --git a/dashboard/src/components/ThumbnailStudio.jsx b/dashboard/src/components/ThumbnailStudio.jsx index 5663972..3b4b7b3 100644 --- a/dashboard/src/components/ThumbnailStudio.jsx +++ b/dashboard/src/components/ThumbnailStudio.jsx @@ -1,6 +1,7 @@ import React, { useState, useRef, useCallback } from 'react'; import { Upload, Image, Loader2, Send, Check, Download, ArrowRight, ArrowLeft, Sparkles, Video, Type, X, Plus, MessageSquare, FileText, Youtube, AlertCircle, CheckCircle2, Settings } from 'lucide-react'; import { getApiUrl } from '../config'; +import { apiFetch } from '../lib/api'; const STEPS = ['Input', 'Titles', 'Generate', 'Description', 'Publish']; @@ -92,7 +93,11 @@ function DragDropZone({ label, accept, onFile, file, onClear, icon: Icon }) { ); } -export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId }) { +export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUserId, managed = false }) { + // Managed (hosted plan): Gemini runs server-side via the bearer token, no BYOK key. + // Only send X-Gemini-Key for self-host BYOK. apiFetch attaches the bearer token. + const keyHeader = geminiApiKey ? { 'X-Gemini-Key': geminiApiKey } : {}; + const needsKey = !geminiApiKey && !managed; // Step management const [step, setStep] = useState(0); const [mode, setMode] = useState(null); // 'video' or 'manual' @@ -165,7 +170,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Step 1: Analyze Video --- const handleAnalyze = async () => { - if (!geminiApiKey) return alert('Please set your Gemini API key in Settings first.'); + if (needsKey) return alert('Please set your Gemini API key in Settings first.'); setIsAnalyzing(true); try { @@ -180,9 +185,9 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse return alert('Please upload a video file.'); } - const res = await fetch(getApiUrl('/api/thumbnail/analyze'), { + const res = await apiFetch('/api/thumbnail/analyze', { method: 'POST', - headers: { 'X-Gemini-Key': geminiApiKey }, + headers: keyHeader, body: formData }); @@ -223,11 +228,11 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // Create session for manual mode const newSessionId = sessionId || crypto.randomUUID(); setSessionId(newSessionId); - fetch(getApiUrl('/api/thumbnail/titles'), { + apiFetch('/api/thumbnail/titles', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey + ...keyHeader }, body: JSON.stringify({ title: manualTitle, session_id: newSessionId }) }).catch(() => { }); @@ -246,11 +251,11 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse setChatHistory(prev => [...prev, { role: 'user', content: userMsg }]); try { - const res = await fetch(getApiUrl('/api/thumbnail/titles'), { + const res = await apiFetch('/api/thumbnail/titles', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey + ...keyHeader }, body: JSON.stringify({ session_id: sessionId, message: userMsg }) }); @@ -275,7 +280,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Step 3: Generate Thumbnails --- const handleGenerate = async () => { - if (!geminiApiKey) return alert('Please set your Gemini API key in Settings first.'); + if (needsKey) return alert('Please set your Gemini API key in Settings first.'); const finalTitle = selectedTitle || manualTitle; if (!finalTitle) return alert('Please select or enter a title first.'); @@ -291,9 +296,9 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse if (faceImage) formData.append('face', faceImage); if (bgImage) formData.append('background', bgImage); - const res = await fetch(getApiUrl('/api/thumbnail/generate'), { + const res = await apiFetch('/api/thumbnail/generate', { method: 'POST', - headers: { 'X-Gemini-Key': geminiApiKey }, + headers: keyHeader, body: formData }); @@ -334,18 +339,18 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Description Generation --- const handleGenerateDescription = async () => { - if (!geminiApiKey) return alert('Please set your Gemini API key in Settings first.'); + if (needsKey) return alert('Please set your Gemini API key in Settings first.'); const finalTitle = selectedTitle || manualTitle; if (!finalTitle) return alert('Please select a title first.'); if (!sessionId) return alert('No session available.'); setIsDescribing(true); try { - const res = await fetch(getApiUrl('/api/thumbnail/describe'), { + const res = await apiFetch('/api/thumbnail/describe', { method: 'POST', headers: { 'Content-Type': 'application/json', - 'X-Gemini-Key': geminiApiKey + ...keyHeader }, body: JSON.stringify({ session_id: sessionId, title: finalTitle }) }); @@ -366,7 +371,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse // --- Publish to YouTube --- const handlePublish = async () => { - if (!uploadPostKey || !uploadUserId) return alert('Please configure your Upload-Post API key and user in Settings first.'); + if (!managed && (!uploadPostKey || !uploadUserId)) return alert('Please configure your Upload-Post API key and user in Settings first.'); const finalTitle = selectedTitle || manualTitle; if (!finalTitle) return alert('No title selected.'); if (!selectedThumbnail) return alert('Please select a thumbnail first.'); @@ -384,7 +389,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse formData.append('user_id', uploadUserId); // Submit the publish job — returns immediately with a publish_id - const res = await fetch(getApiUrl('/api/thumbnail/publish'), { + const res = await apiFetch('/api/thumbnail/publish', { method: 'POST', body: formData }); @@ -472,8 +477,8 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse - {/* Gemini API Key Warning */} - {!geminiApiKey && ( + {/* Gemini API Key Warning (self-host BYOK only; managed uses server key) */} + {needsKey && (
@@ -485,7 +490,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse {/* ===== STEP 0: Input Mode Selection ===== */} {step === 0 && ( -
+
{/* Mode A: Video Analysis */}
@@ -1058,7 +1063,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse
{/* Publish Button */} - {(!uploadPostKey || !uploadUserId) ? ( + {(!managed && (!uploadPostKey || !uploadUserId)) ? (
diff --git a/dashboard/src/components/TopUpModal.jsx b/dashboard/src/components/TopUpModal.jsx new file mode 100644 index 0000000..b863911 --- /dev/null +++ b/dashboard/src/components/TopUpModal.jsx @@ -0,0 +1,52 @@ +import React, { useState, useEffect } from 'react'; +import { X, Loader2, Zap } from 'lucide-react'; +import { apiJson } from '../lib/api'; + +// Opens when a job hits a 402 (quota exceeded). Lets the user buy more minutes. +export default function TopUpModal({ onClose, required, remaining }) { + const [topups, setTopups] = useState([]); + const [busy, setBusy] = useState(false); + + useEffect(() => { + apiJson('/api/billing/plans').then((d) => setTopups(d.topups || [])).catch(() => {}); + }, []); + + const buy = async (price_id) => { + setBusy(true); + 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(false); alert('Could not start checkout.'); } + }; + + const fmt = (a, c) => new Intl.NumberFormat('en-US', { style: 'currency', currency: (c || 'usd').toUpperCase(), maximumFractionDigits: 0 }).format((a || 0) / 100); + + return ( +
+
+ +
+

You're out of minutes

+

+ {typeof required === 'number' + ? <>This video needs {required} min but you have {Math.round((remaining || 0) * 10) / 10} min left. + : 'Add more minutes to keep generating.'} +

+
+ {topups.map((t) => ( + + ))} + {topups.length === 0 &&
} +
+

Or upgrade your plan for more monthly minutes.

+
+
+ ); +} diff --git a/dashboard/src/components/TrialGate.jsx b/dashboard/src/components/TrialGate.jsx new file mode 100644 index 0000000..774abd0 --- /dev/null +++ b/dashboard/src/components/TrialGate.jsx @@ -0,0 +1,25 @@ +import React from 'react'; +import { Sparkles, ArrowRight } from 'lucide-react'; + +// Slim, non-blocking banner shown above a tool when a hosted user has no active +// plan/trial. The tool stays visible below; actions still route to pricing. +export default function TrialGate({ toolName = 'this' }) { + return ( +
+
+ +
+ Preview mode.{' '} + Start your 3-day free trial to generate with {toolName} — + no API keys, from $12/mo. Or run it free by self-hosting. +
+
+ +
+ ); +} diff --git a/dashboard/src/components/UsageMeter.jsx b/dashboard/src/components/UsageMeter.jsx new file mode 100644 index 0000000..6f417a0 --- /dev/null +++ b/dashboard/src/components/UsageMeter.jsx @@ -0,0 +1,28 @@ +import React from 'react'; +import { Zap } from 'lucide-react'; +import { useAuth } from '../contexts/AuthContext'; + +// Compact minutes-remaining pill for the header (managed users only). +export default function UsageMeter({ onClick }) { + const { isManaged, minutes } = useAuth(); + if (!isManaged || !minutes) return null; + + const remaining = Math.round((minutes.remaining || 0) * 10) / 10; + const allowance = (minutes.plan_allowance || 0) + (minutes.topup_remaining || 0) + (minutes.plan_used || 0); + const pct = allowance > 0 ? Math.max(4, Math.min(100, (remaining / allowance) * 100)) : 0; + const low = remaining <= (allowance * 0.2); + + return ( + + ); +} diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx new file mode 100644 index 0000000..db95819 --- /dev/null +++ b/dashboard/src/contexts/AuthContext.jsx @@ -0,0 +1,123 @@ +// Auth + billing session state for cloud mode. +// - Reads /api/config to learn whether billing is enabled at all. +// - Handles the magic-link and Google OAuth redirect hashes. +// - Exposes the current user, plan and minute balance to the app. +// When billingEnabled is false the provider is inert and the app behaves as the +// classic BYOK dashboard. +import { createContext, useContext, useState, useEffect, useCallback } from 'react'; +import { getApiUrl } from '../config'; +import { apiFetch, apiJson, getToken, setToken, clearToken } from '../lib/api'; + +const AuthContext = createContext(null); +export const useAuth = () => useContext(AuthContext); + +export function AuthProvider({ children }) { + const [config, setConfig] = useState({ billingEnabled: false, googleAuthEnabled: false }); + const [me, setMe] = useState(null); // /api/me payload, or null when signed out + const [loading, setLoading] = useState(true); + const [signingIn, setSigningIn] = useState(false); + + const refreshMe = useCallback(async () => { + if (!getToken()) { setMe(null); return null; } + try { + const data = await apiJson('/api/me'); + setMe(data); + return data; + } catch (e) { + // Stale/invalid token: drop it and fall back to anonymous BYOK. + clearToken(); + setMe(null); + return null; + } + }, []); + + // Handle auth redirect hashes: #/auth/verify?ml=... and #/auth/callback?token=... + const handleAuthHash = useCallback(async () => { + const hash = window.location.hash || ''; + const match = hash.match(/^#\/auth\/(verify|callback)\??(.*)$/); + if (!match) return false; + const [, kind, query] = match; + const params = new URLSearchParams(query); + + setSigningIn(true); + try { + if (kind === 'callback') { + const token = params.get('token'); + if (token) setToken(token); + } else if (kind === 'verify') { + const ml = params.get('ml'); + if (ml) { + const data = await apiJson('/api/auth/magic-link/verify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ token: ml }), + }); + if (data.token) setToken(data.token); + } + } + await refreshMe(); + } catch (e) { + // fall through — user lands signed-out + } finally { + setSigningIn(false); + // Clear the sensitive hash, land in the app. + window.location.hash = '#app'; + } + return true; + }, [refreshMe]); + + useEffect(() => { + (async () => { + try { + const cfg = await (await fetch(getApiUrl('/api/config'))).json(); + setConfig(cfg); + if (cfg.billingEnabled) { + const handled = await handleAuthHash(); + if (!handled) await refreshMe(); + } + } catch (_) { /* config fetch failed — stay in BYOK */ } + setLoading(false); + })(); + }, [handleAuthHash, refreshMe]); + + const requestMagicLink = useCallback(async (email) => { + const res = await apiFetch('/api/auth/magic-link', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ email }), + }); + if (res.status === 429) throw new Error('Too many attempts. Try again in a few minutes.'); + if (!res.ok) throw new Error('Could not send sign-in link.'); + return true; + }, []); + + const loginWithGoogle = useCallback(() => { + window.location.href = getApiUrl('/api/auth/google'); + }, []); + + const logout = useCallback(() => { + clearToken(); + setMe(null); + }, []); + + const value = { + billingEnabled: config.billingEnabled, + googleAuthEnabled: config.googleAuthEnabled, + loading, + signingIn, + user: me?.user || null, + me, + plan: me?.plan || null, + entitled: !!me?.entitled, + minutes: me?.minutes || null, + isSignedIn: !!me?.user, + // Managed = signed-in AND entitled (active plan or top-up credit). + isManaged: !!(config.billingEnabled && me?.entitled), + refreshMe, + requestMagicLink, + loginWithGoogle, + logout, + }; + + return {children}; +} diff --git a/dashboard/src/lib/api.js b/dashboard/src/lib/api.js new file mode 100644 index 0000000..0819d45 --- /dev/null +++ b/dashboard/src/lib/api.js @@ -0,0 +1,48 @@ +// Centralized API client for cloud mode. +// Adds the Authorization: Bearer header from the stored session token, and turns +// a 402 (quota exceeded) into a typed QuotaError the UI can catch to prompt a top-up. +import { getApiUrl } from '../config'; + +export const AUTH_TOKEN_KEY = 'openshorts_auth'; + +export const getToken = () => localStorage.getItem(AUTH_TOKEN_KEY) || ''; +export const setToken = (t) => localStorage.setItem(AUTH_TOKEN_KEY, t); +export const clearToken = () => localStorage.removeItem(AUTH_TOKEN_KEY); + +export class QuotaError extends Error { + constructor(detail) { + super('quota_exceeded'); + this.name = 'QuotaError'; + this.minutesRequired = detail?.minutes_required; + this.minutesRemaining = detail?.minutes_remaining; + } +} + +// Drop-in fetch wrapper. Always attaches the bearer token when present. +export async function apiFetch(path, options = {}) { + const headers = new Headers(options.headers || {}); + const token = getToken(); + if (token) headers.set('Authorization', `Bearer ${token}`); + + const res = await fetch(getApiUrl(path), { ...options, headers }); + + if (res.status === 402) { + let detail = {}; + try { + const body = await res.clone().json(); + detail = body.detail || body; + } catch (_) { /* ignore */ } + throw new QuotaError(detail); + } + return res; +} + +// Convenience JSON helper. +export async function apiJson(path, options = {}) { + const res = await apiFetch(path, options); + if (!res.ok) { + const text = await res.text().catch(() => ''); + throw new Error(`${res.status}: ${text}`); + } + return res.json(); +} diff --git a/dashboard/src/main.jsx b/dashboard/src/main.jsx index 7bd9579..5c51ae6 100644 --- a/dashboard/src/main.jsx +++ b/dashboard/src/main.jsx @@ -4,10 +4,50 @@ import './index.css' import App from './App.jsx' import Landing from './Landing.jsx' import Legal from './Legal.jsx' +import { AuthProvider, useAuth } from './contexts/AuthContext' +import PricingSection from './components/PricingSection' +import AccountPage from './components/AccountPage' +import LoginModal from './components/LoginModal' + +function PageShell({ title, children }) { + return ( +
+
+ OpenShorts + ← Back to app +
+
+ {title &&

{title}

} + {children} +
+
+ ); +} + +function PricingView() { + const [showLogin, setShowLogin] = useState(false); + return ( + + setShowLogin(true)} /> + {showLogin && setShowLogin(false)} />} + + ); +} + +function AccountView() { + const { isSignedIn, loading } = useAuth(); + useEffect(() => { + if (!loading && !isSignedIn) window.location.hash = '#/pricing'; + }, [loading, isSignedIn]); + return ; +} function Root() { const resolveView = () => { - const hash = window.location.hash; + const hash = window.location.hash || ''; + if (hash.startsWith('#/auth/')) return 'auth'; // AuthContext consumes then redirects + if (hash.startsWith('#/account')) return 'account'; + if (hash.startsWith('#/pricing')) return 'pricing'; if (hash === '#legal') return 'legal'; if (hash === '#app' || localStorage.getItem('openshorts_skip_landing') === '1') return 'app'; return 'landing'; @@ -28,12 +68,19 @@ function Root() { }; if (view === 'legal') return ; + if (view === 'pricing') return ; + if (view === 'account') return ; + if (view === 'auth') { + return
Signing you in…
; + } if (view === 'app') return ; return ; } createRoot(document.getElementById('root')).render( - + + + , ) diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml new file mode 100644 index 0000000..662c547 --- /dev/null +++ b/docker-compose.cloud.yml @@ -0,0 +1,52 @@ +# Cloud (paid / managed-keys) mode override for openshorts.app. +# Usage: +# docker compose -f docker-compose.yml -f docker-compose.cloud.yml up --build +# +# The base docker-compose.yml is untouched and keeps working as pure BYOK for +# self-hosters. This file only adds the Postgres service and the cloud env. +services: + db: + image: postgres:16-alpine + container_name: openshorts-db + environment: + - POSTGRES_USER=openshorts + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-openshorts} + - POSTGRES_DB=openshorts + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U openshorts"] + interval: 5s + timeout: 3s + retries: 10 + restart: unless-stopped + + backend: + depends_on: + db: + condition: service_healthy + environment: + - BILLING_ENABLED=true + - DATABASE_URL=postgresql+asyncpg://openshorts:${POSTGRES_PASSWORD:-openshorts}@db:5432/openshorts + - JWT_SECRET=${JWT_SECRET} + - FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app} + - ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app} + # Email (magic link) — Resend + - RESEND_API_KEY=${RESEND_API_KEY} + - EMAIL_FROM=${EMAIL_FROM:-OpenShorts } + # Google OAuth + - GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID} + - GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET} + # Stripe (prices are resolved by lookup_key at runtime — no price IDs needed) + - STRIPE_SECRET_KEY=${STRIPE_SECRET_KEY} + - STRIPE_WEBHOOK_SECRET=${STRIPE_WEBHOOK_SECRET} + # Managed provider keys (server-owned) + - MANAGED_GEMINI_API_KEY=${MANAGED_GEMINI_API_KEY} + - MANAGED_UPLOAD_POST_API_KEY=${MANAGED_UPLOAD_POST_API_KEY} + - OPENSHORTS_LOGO_URL=${OPENSHORTS_LOGO_URL:-https://openshorts.app/logo.png} + # Residential proxy for YouTube downloads (avoids datacenter-IP bans). + # e.g. http://user:pass@gate.dataimpulse.com:823 — leave empty to go direct. + - PROXY_URL=${PROXY_URL:-} + +volumes: + pgdata: diff --git a/docker-compose.e2e.local.yml b/docker-compose.e2e.local.yml new file mode 100644 index 0000000..4dd4570 --- /dev/null +++ b/docker-compose.e2e.local.yml @@ -0,0 +1,10 @@ +# Local-only override: remap host ports to avoid clashes with other running +# projects (e.g. another backend on :8000). Not for production. +# `!override` REPLACES the base ports list instead of appending to it. +services: + backend: + ports: !override + - "8001:8000" + frontend: + ports: !override + - "5176:5173" diff --git a/main.py b/main.py index 0e26f8c..f8fa0f9 100644 --- a/main.py +++ b/main.py @@ -474,6 +474,13 @@ def download_youtube_video(url, output_dir="."): cookies_path = None print("⚠️ YOUTUBE_COOKIES env var not found.") + # Optional residential proxy for YouTube (avoids datacenter-IP bans on hosted + # servers). Set PROXY_URL (e.g. http://user:pass@gate.provider.com:port). + # When unset (self-host), downloads go direct as before. + _proxy = os.environ.get("PROXY_URL", "").strip() or None + if _proxy: + print("🌐 Using residential proxy for download.") + # Common yt-dlp options to work around YouTube bot detection. # extractor_args tries multiple player clients in order; tv_embed / android # avoid the OAuth/PO-token checks that block server IPs. @@ -482,6 +489,7 @@ def download_youtube_video(url, output_dir="."): 'verbose': True, 'no_warnings': False, 'cookiefile': cookies_path if cookies_path else None, + 'proxy': _proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10, @@ -551,9 +559,17 @@ Technical Details: {str(e)} os.remove(expected_file) print(f"🗑️ Removed existing file to re-download with H.264 codec") + # When downloading through a paid proxy, cap at 720p to control bandwidth + # cost (a 720p source is plenty for 9:16 clips). Direct downloads keep best. + if _proxy: + _fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/' + 'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best') + else: + _fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best' + ydl_opts = { **_COMMON_YDL_OPTS, - 'format': 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best', + 'format': _fmt, 'outtmpl': output_template, 'merge_output_format': 'mp4', 'overwrites': True, diff --git a/requirements-billing.txt b/requirements-billing.txt new file mode 100644 index 0000000..cfd8b08 --- /dev/null +++ b/requirements-billing.txt @@ -0,0 +1,11 @@ +# Extra dependencies for cloud (paid / managed-keys) mode ONLY. +# Self-hosters running BYOK do NOT need these — see requirements.txt. +# Installed on top of requirements.txt when BILLING_ENABLED is used. +sqlalchemy[asyncio]==2.0.36 +asyncpg==0.30.0 +alembic==1.14.0 +stripe==11.3.0 +authlib==1.3.2 +itsdangerous==2.2.0 +PyJWT==2.10.1 +email-validator==2.2.0 From c15f26b31c3a2e1ab3907f7955b8638386fe6a98 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 14 Jul 2026 13:17:53 +0200 Subject: [PATCH 02/12] fix: use residential proxy for the yt-dlp duration probe too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The metering duration probe (probe_url_minutes) ran yt-dlp without the proxy or anti-bot extractor args, so it got IP-blocked on the server before the download step. Now it mirrors main.py: PROXY_URL + player_client fallbacks. Verified E2E — YouTube download completes through the DataImpulse residential proxy. --- cloud/metering.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/cloud/metering.py b/cloud/metering.py index 6238b40..965336a 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -66,11 +66,25 @@ def probe_file_minutes(path: str) -> float: def probe_url_minutes(url: str) -> float: """Return the video duration in minutes from yt-dlp metadata (no download). - Raises ValueError if the duration is unknown (e.g. live streams) — the caller - turns that into a 400 for managed users. + Uses the same residential proxy + anti-bot extractor args as the actual + download (main.py), so the metadata probe doesn't get IP-blocked on the + server before we even reach the download step. Metadata only — negligible + bandwidth. Raises ValueError if the duration is unknown (e.g. live streams). """ import yt_dlp - with yt_dlp.YoutubeDL({"skip_download": True, "quiet": True, "no_warnings": True}) as ydl: + opts = { + "skip_download": True, "quiet": True, "no_warnings": True, + "extractor_args": { + "youtube": { + "player_client": ["tv_embed", "android", "mweb", "web"], + "player_skip": ["webpage", "configs"], + } + }, + } + proxy = os.environ.get("PROXY_URL", "").strip() + if proxy: + opts["proxy"] = proxy + with yt_dlp.YoutubeDL(opts) as ydl: info = ydl.extract_info(url, download=False) duration = info.get("duration") if not duration: From ebe876c4979ba9fff484e43dab8d83a1e3855d49 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 14 Jul 2026 13:42:07 +0200 Subject: [PATCH 03/12] feat: unlock 720p/1080p YouTube downloads (Deno + bgutil PO tokens) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit YouTube now forces SABR streaming, capping downloads at 360p without a GVS PO token. Adds the full recipe (cloud mode only): - Dockerfile: Deno JS runtime (nsig challenge) + latest yt-dlp[default] nightly + bgutil-ytdlp-pot-provider plugin - docker-compose.cloud.yml: bgutil PO-token sidecar + BGUTIL_BASE_URL - main.py / metering.py: when BGUTIL_BASE_URL is set, use yt-dlp default clients + the bgutil HTTP provider (→ 720p); self-host keeps the conservative fallback Verified E2E through the container: managed user -> YouTube -> DataImpulse residential proxy + Deno + bgutil -> real 720p (format 136) download, no 403. --- .env.cloud.example | 4 ++++ Dockerfile | 9 +++++++-- cloud/metering.py | 13 +++++++++---- docker-compose.cloud.yml | 11 +++++++++++ main.py | 28 +++++++++++++++++++--------- 5 files changed, 50 insertions(+), 15 deletions(-) diff --git a/.env.cloud.example b/.env.cloud.example index b5f42e2..a065a57 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -36,3 +36,7 @@ OPENSHORTS_LOGO_URL=https://openshorts.app/logo.png # hosted server). Recommended: DataImpulse (~$1/GB PAYG). Downloads are capped # to 720p when this is set, to control bandwidth cost. Empty = direct download. PROXY_URL= + +# PO-token provider for 720p/1080p YouTube (bgutil sidecar in docker-compose.cloud.yml). +# Defaults to the sidecar; only override if you run bgutil elsewhere. +BGUTIL_BASE_URL=http://bgutil:4416 diff --git a/Dockerfile b/Dockerfile index 31895e2..56f2486 100644 --- a/Dockerfile +++ b/Dockerfile @@ -35,13 +35,18 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ nodejs \ && rm -rf /var/lib/apt/lists/* +# Deno JS runtime — yt-dlp needs it to solve YouTube's nsig challenge for 720p+ +# (used together with the bgutil PO-token sidecar in cloud mode). +COPY --from=denoland/deno:bin /deno /usr/local/bin/deno + # Copy virtual env from builder COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" ENV PYTHONUNBUFFERED=1 -# Always upgrade yt-dlp to latest (YouTube bot-detection changes frequently) -RUN pip install --upgrade --no-cache-dir yt-dlp +# Latest yt-dlp (nightly, YouTube changes constantly) + the bgutil PO-token +# provider plugin. Together with Deno + the bgutil sidecar this unlocks 720p/1080p. +RUN pip install --upgrade --pre --no-cache-dir "yt-dlp[default]" bgutil-ytdlp-pot-provider # Copy application code COPY . . diff --git a/cloud/metering.py b/cloud/metering.py index 965336a..43e4465 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -72,14 +72,19 @@ def probe_url_minutes(url: str) -> float: bandwidth. Raises ValueError if the duration is unknown (e.g. live streams). """ import yt_dlp - opts = { - "skip_download": True, "quiet": True, "no_warnings": True, - "extractor_args": { + bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip() + if bgutil: + extractor_args = {"youtubepot-bgutilhttp": {"base_url": [bgutil]}} + else: + extractor_args = { "youtube": { "player_client": ["tv_embed", "android", "mweb", "web"], "player_skip": ["webpage", "configs"], } - }, + } + opts = { + "skip_download": True, "quiet": True, "no_warnings": True, + "extractor_args": extractor_args, } proxy = os.environ.get("PROXY_URL", "").strip() if proxy: diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml index 662c547..1659913 100644 --- a/docker-compose.cloud.yml +++ b/docker-compose.cloud.yml @@ -21,10 +21,19 @@ services: retries: 10 restart: unless-stopped + # PO-token provider — lets yt-dlp fetch YouTube's GVS PO tokens so 720p/1080p + # formats are available (with Deno + a recent yt-dlp in the backend image). + bgutil: + image: brainicism/bgutil-ytdlp-pot-provider + container_name: openshorts-bgutil + restart: unless-stopped + backend: depends_on: db: condition: service_healthy + bgutil: + condition: service_started environment: - BILLING_ENABLED=true - DATABASE_URL=postgresql+asyncpg://openshorts:${POSTGRES_PASSWORD:-openshorts}@db:5432/openshorts @@ -47,6 +56,8 @@ services: # Residential proxy for YouTube downloads (avoids datacenter-IP bans). # e.g. http://user:pass@gate.dataimpulse.com:823 — leave empty to go direct. - PROXY_URL=${PROXY_URL:-} + # PO-token provider (bgutil sidecar) → unlocks 720p/1080p downloads. + - BGUTIL_BASE_URL=${BGUTIL_BASE_URL:-http://bgutil:4416} volumes: pgdata: diff --git a/main.py b/main.py index f8fa0f9..b0a1824 100644 --- a/main.py +++ b/main.py @@ -481,9 +481,24 @@ def download_youtube_video(url, output_dir="."): if _proxy: print("🌐 Using residential proxy for download.") - # Common yt-dlp options to work around YouTube bot detection. - # extractor_args tries multiple player clients in order; tv_embed / android - # avoid the OAuth/PO-token checks that block server IPs. + # YouTube client strategy: + # - Hosted (BGUTIL_BASE_URL set): use yt-dlp's default clients + the bgutil + # PO-token provider → unlocks 720p/1080p (needs the bgutil sidecar + a Deno + # JS runtime + a recent yt-dlp, all baked into the cloud image). + # - Self-host (no bgutil): fall back to the conservative tv_embed/android + # clients that work without a PO-token provider (caps around 360p, but no + # extra infra required). + _bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip() + if _bgutil: + _extractor_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}} + else: + _extractor_args = { + 'youtube': { + 'player_client': ['tv_embed', 'android', 'mweb', 'web'], + 'player_skip': ['webpage', 'configs'], + } + } + _COMMON_YDL_OPTS = { 'quiet': False, 'verbose': True, @@ -495,12 +510,7 @@ def download_youtube_video(url, output_dir="."): 'fragment_retries': 10, 'nocheckcertificate': True, 'cachedir': False, - 'extractor_args': { - 'youtube': { - 'player_client': ['tv_embed', 'android', 'mweb', 'web'], - 'player_skip': ['webpage', 'configs'], - } - }, + 'extractor_args': _extractor_args, 'http_headers': { 'User-Agent': ( 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' From 12d423d739a0751d950da23222b5ce35d1ff0367 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 14 Jul 2026 14:00:02 +0200 Subject: [PATCH 04/12] feat: 720p->360p download fallback + SMTP email alerts - main.py / metering.py: try the HD (bgutil/720p) strategy first, fall back to the conservative (360p) clients on any failure, so a YouTube/yt-dlp change degrades gracefully instead of failing the whole job. - cloud/alerts.py: in-memory tracking of managed-job outcomes; emails the admin (ADMIN_EMAIL) when a proxy/credit error appears or when many jobs fail in a row, with a 1h per-alert cooldown. Wired into run_job_wrapper. - Email switched from Resend to SMTP (cloud/emails.py) for magic link + alerts (Namecheap Private Email). Config via SMTP_* / EMAIL_FROM / ADMIN_EMAIL in the mounted .env (kept out of compose so the password's $/* aren't mangled). SMTP send verified from host and from the backend container. --- .env.cloud.example | 12 ++- app.py | 19 +++- cloud/alerts.py | 72 ++++++++++++++++ cloud/config.py | 30 ++++++- cloud/emails.py | 58 +++++++++---- cloud/metering.py | 43 +++++----- docker-compose.cloud.yml | 7 +- main.py | 181 +++++++++++++++++---------------------- 8 files changed, 269 insertions(+), 153 deletions(-) create mode 100644 cloud/alerts.py diff --git a/.env.cloud.example b/.env.cloud.example index a065a57..ae5c54c 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -13,9 +13,15 @@ JWT_SECRET=generate-a-long-random-string FRONTEND_URL=https://openshorts.app ALLOWED_ORIGINS=https://openshorts.app -# Email — magic link (Resend) -RESEND_API_KEY=re_... -EMAIL_FROM=OpenShorts +# Email — magic link + admin alerts, via SMTP (e.g. Namecheap Private Email). +# Quote the password if it contains $ or * so dotenv keeps it literal. +SMTP_HOST=mail.privateemail.com +SMTP_PORT=465 +SMTP_USER=info@yourdomain.com +SMTP_PASSWORD='your-mailbox-password' +EMAIL_FROM=OpenShorts +# Operational alerts (proxy out of credits / high failure rate) are emailed here. +ADMIN_EMAIL=you@example.com # Google OAuth (optional; magic link works without it) GOOGLE_CLIENT_ID= diff --git a/app.py b/app.py index 6dcde0e..3a62e1d 100644 --- a/app.py +++ b/app.py @@ -42,13 +42,14 @@ BILLING_ENABLED = os.environ.get("BILLING_ENABLED", "").lower() in ("1", "true", if BILLING_ENABLED: import cloud - from cloud import managed_keys, metering as _metering, config as _cloud_config + from cloud import managed_keys, metering as _metering, config as _cloud_config, alerts as _alerts from cloud.auth import get_current_user_optional else: cloud = None managed_keys = None _metering = None _cloud_config = None + _alerts = None async def get_current_user_optional(request: Request): # No-op dependency in self-host mode: every request is anonymous / BYOK. @@ -313,12 +314,28 @@ async def run_job_wrapper(job_id): # Settle the minute reservation (managed jobs only): commit on success, # release otherwise so the minutes go back to the user. await _settle_reservation(job_id) + # Operational alerting for managed jobs (proxy out of credits / failures). + await _record_job_alert(job_id) # Always release semaphore and mark queue task done concurrency_semaphore.release() job_queue.task_done() print(f"✅ Released slot for job: {job_id}") +async def _record_job_alert(job_id): + if not BILLING_ENABLED: + return + job = jobs.get(job_id) or {} + if not job.get('user_id'): + return # only track managed jobs + ok = job.get('status') == 'completed' + err = "" if ok else " ".join(job.get('logs', [])[-10:]) + try: + await _alerts.record_job_outcome(ok, err) + except Exception as e: + print(f"⚠️ Alert recording error for {job_id}: {e}") + + async def _settle_reservation(job_id): if not BILLING_ENABLED: return diff --git a/cloud/alerts.py b/cloud/alerts.py new file mode 100644 index 0000000..7d40cfb --- /dev/null +++ b/cloud/alerts.py @@ -0,0 +1,72 @@ +"""Operational email alerts for the admin (proxy out of credits, high failure rate). + +Tracks recent managed-job outcomes in memory and emails ADMIN_EMAIL (via Resend) +when something looks broken, with a per-alert cooldown so it never spams. +""" +import time +from collections import deque + +from .config import settings +from .emails import send_email + +_recent = deque(maxlen=12) # rolling window of recent job outcomes (ok bool) +_last_alert = {} # alert kind -> last-sent epoch +_ALERT_COOLDOWN = 3600 # 1 hour between repeats of the same alert +_FAIL_WINDOW_MIN = 6 # need at least this many recent jobs to judge a rate +_FAIL_THRESHOLD = 5 # ...and this many failures among them + +# Substrings that suggest the proxy itself failed (auth / balance / tunnel). +_PROXY_HINTS = ("proxy", "407", "proxyauthentication", "tunnel connection", + "credit", "balance", "insufficient", "payment required") + + +def _looks_like_proxy_error(err: str) -> bool: + e = (err or "").lower() + return any(k in e for k in _PROXY_HINTS) + + +def _cooldown_ok(kind: str) -> bool: + now = time.time() + if now - _last_alert.get(kind, 0) < _ALERT_COOLDOWN: + return False + _last_alert[kind] = now + return True + + +async def send_admin_alert(subject: str, body: str): + to = settings.admin_email + if not to or not settings.smtp_configured: + print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}" + + ("" if to else " (set ADMIN_EMAIL + SMTP_* to email these)")) + return + html = f"
{body}
" + await send_email(to, f"[OpenShorts] {subject}", html) + + +async def record_job_outcome(ok: bool, error_text: str = ""): + """Record a managed job's result and fire an alert if the picture looks bad.""" + _recent.append(bool(ok)) + if ok: + return + + # 1) Proxy / credits problem — most urgent, alert immediately. + if _looks_like_proxy_error(error_text) and _cooldown_ok("proxy"): + await send_admin_alert( + "⚠️ Proxy error — DataImpulse may be out of credits", + "A managed job failed with a proxy-related error. Check your residential " + "proxy balance (DataImpulse) — downloads will keep failing until it's topped up.\n\n" + f"Error:\n{error_text[:1200]}", + ) + return + + # 2) High failure rate — the YouTube download path may be broken (arms race). + recent = list(_recent) + fails = recent.count(False) + if len(recent) >= _FAIL_WINDOW_MIN and fails >= _FAIL_THRESHOLD and _cooldown_ok("failrate"): + await send_admin_alert( + "⚠️ High download failure rate", + f"{fails} of the last {len(recent)} managed jobs failed. The YouTube " + "download path may be broken (yt-dlp / PO-token change). A backend image " + "rebuild usually pulls the yt-dlp fix.\n\n" + f"Last error:\n{error_text[:1200]}", + ) diff --git a/cloud/config.py b/cloud/config.py index fadbcdb..23e6112 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -83,14 +83,36 @@ class Settings: origins = [o.strip() for o in raw.split(",") if o.strip()] return origins or [self.frontend_url] - # Email (Resend) + # Email (SMTP — e.g. Namecheap Private Email) @property - def resend_api_key(self) -> str: - return os.environ.get("RESEND_API_KEY", "") + def smtp_host(self) -> str: + return os.environ.get("SMTP_HOST", "mail.privateemail.com") + + @property + def smtp_port(self) -> int: + return int(os.environ.get("SMTP_PORT", "465")) + + @property + def smtp_user(self) -> str: + return os.environ.get("SMTP_USER", "") + + @property + def smtp_password(self) -> str: + return os.environ.get("SMTP_PASSWORD", "") + + @property + def smtp_configured(self) -> bool: + return bool(self.smtp_user and self.smtp_password) @property def email_from(self) -> str: - return os.environ.get("EMAIL_FROM", "OpenShorts ") + # Namecheap requires the From to be the authenticated mailbox. + return os.environ.get("EMAIL_FROM") or (f"OpenShorts <{self.smtp_user}>" if self.smtp_user else "OpenShorts") + + @property + def admin_email(self) -> str: + # Where operational alerts (proxy out of credits, high failure rate) go. + return os.environ.get("ADMIN_EMAIL", "") # Google OAuth @property diff --git a/cloud/emails.py b/cloud/emails.py index 32f8c2f..133944d 100644 --- a/cloud/emails.py +++ b/cloud/emails.py @@ -1,18 +1,51 @@ -"""Transactional email via Resend (magic-link login). +"""Transactional + operational email via SMTP (e.g. Namecheap Private Email). -If RESEND_API_KEY is unset (e.g. local dev), the link is printed to the server -log instead of sent, so the login flow is still testable without a real inbox. +If SMTP isn't configured (local dev), messages are printed to the server log so +the magic-link flow and alerts still work without a real mailbox. """ -import httpx +import asyncio +import smtplib +import ssl +from email.message import EmailMessage from .config import settings +def _send_sync(to: str, subject: str, html: str): + msg = EmailMessage() + msg["From"] = settings.email_from + msg["To"] = to + msg["Subject"] = subject + msg.set_content("This message requires an HTML-capable email client.") + msg.add_alternative(html, subtype="html") + + if settings.smtp_port == 465: + with smtplib.SMTP_SSL(settings.smtp_host, settings.smtp_port, + context=ssl.create_default_context(), timeout=20) as s: + s.login(settings.smtp_user, settings.smtp_password) + s.send_message(msg) + else: + with smtplib.SMTP(settings.smtp_host, settings.smtp_port, timeout=20) as s: + s.starttls(context=ssl.create_default_context()) + s.login(settings.smtp_user, settings.smtp_password) + s.send_message(msg) + + +async def send_email(to: str, subject: str, html: str): + """Send an email (async wrapper). Logs instead of sending if SMTP is unset.""" + if not settings.smtp_configured: + print(f"✉️ [DEV email → {to}] {subject}") + return + try: + await asyncio.to_thread(_send_sync, to, subject, html) + except Exception as e: + print(f"⚠️ Failed to send email to {to}: {e}") + + async def send_magic_link_email(email: str, link: str): - if not settings.resend_api_key: + if not settings.smtp_configured: print(f"✉️ [DEV magic link] {email} -> {link}") return - html = f"""

Sign in to OpenShorts

@@ -22,15 +55,4 @@ async def send_magic_link_email(email: str, link: str):

If you didn't request this, ignore this email.

""" - async with httpx.AsyncClient(timeout=15) as client: - resp = await client.post( - "https://api.resend.com/emails", - headers={"Authorization": f"Bearer {settings.resend_api_key}"}, - json={ - "from": settings.email_from, - "to": [email], - "subject": "Your OpenShorts sign-in link", - "html": html, - }, - ) - resp.raise_for_status() + await send_email(email, "Your OpenShorts sign-in link", html) diff --git a/cloud/metering.py b/cloud/metering.py index 43e4465..6e71779 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -73,28 +73,29 @@ def probe_url_minutes(url: str) -> float: """ import yt_dlp bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip() - if bgutil: - extractor_args = {"youtubepot-bgutilhttp": {"base_url": [bgutil]}} - else: - extractor_args = { - "youtube": { - "player_client": ["tv_embed", "android", "mweb", "web"], - "player_skip": ["webpage", "configs"], - } - } - opts = { - "skip_download": True, "quiet": True, "no_warnings": True, - "extractor_args": extractor_args, - } proxy = os.environ.get("PROXY_URL", "").strip() - if proxy: - opts["proxy"] = proxy - with yt_dlp.YoutubeDL(opts) as ydl: - info = ydl.extract_info(url, download=False) - duration = info.get("duration") - if not duration: - raise ValueError("Could not determine video duration") - return float(duration) / 60.0 + conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"], + "player_skip": ["webpage", "configs"]}} + # Try the bgutil/HD extractor first, then the conservative one — mirrors the + # download's HD→fallback logic so the probe never fails alone. + strategies = ([{"youtubepot-bgutilhttp": {"base_url": [bgutil]}}] if bgutil else []) + [conservative] + + last_err = None + for extractor_args in strategies: + opts = {"skip_download": True, "quiet": True, "no_warnings": True, + "extractor_args": extractor_args} + if proxy: + opts["proxy"] = proxy + try: + with yt_dlp.YoutubeDL(opts) as ydl: + info = ydl.extract_info(url, download=False) + duration = info.get("duration") + if duration: + return float(duration) / 60.0 + last_err = ValueError("no duration in metadata") + except Exception as e: + last_err = e + raise ValueError(f"Could not determine video duration ({last_err})") # --------------------------------------------------------------------------- # diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml index 1659913..ff1a4af 100644 --- a/docker-compose.cloud.yml +++ b/docker-compose.cloud.yml @@ -40,9 +40,10 @@ services: - JWT_SECRET=${JWT_SECRET} - FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app} - ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app} - # Email (magic link) — Resend - - RESEND_API_KEY=${RESEND_API_KEY} - - EMAIL_FROM=${EMAIL_FROM:-OpenShorts } + # Email (magic link + admin alerts) is via SMTP and read from the mounted + # .env (SMTP_HOST/PORT/USER/PASSWORD, EMAIL_FROM, ADMIN_EMAIL). It's kept + # out of this list on purpose so the SMTP password's $/* aren't mangled by + # compose/shell variable substitution. # Google OAuth - GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID} - GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET} diff --git a/main.py b/main.py index b0a1824..17919a4 100644 --- a/main.py +++ b/main.py @@ -481,124 +481,99 @@ def download_youtube_video(url, output_dir="."): if _proxy: print("🌐 Using residential proxy for download.") - # YouTube client strategy: - # - Hosted (BGUTIL_BASE_URL set): use yt-dlp's default clients + the bgutil - # PO-token provider → unlocks 720p/1080p (needs the bgutil sidecar + a Deno - # JS runtime + a recent yt-dlp, all baked into the cloud image). - # - Self-host (no bgutil): fall back to the conservative tv_embed/android - # clients that work without a PO-token provider (caps around 360p, but no - # extra infra required). + # Two download strategies, tried in order so a break in the HD path degrades + # gracefully instead of failing the whole job: + # 1) HD — yt-dlp default clients + the bgutil PO-token provider + # (BGUTIL_BASE_URL, needs the sidecar + Deno + recent yt-dlp) → 720p/1080p. + # 2) Fallback — conservative tv_embed/android clients, no PO provider (~360p), + # which is also the ONLY strategy for self-host (no bgutil configured). _bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip() - if _bgutil: - _extractor_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}} + hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}} if _bgutil else None + fallback_args = { + 'youtube': { + 'player_client': ['tv_embed', 'android', 'mweb', 'web'], + 'player_skip': ['webpage', 'configs'], + } + } + + # Cap at 720p when using a paid proxy (bandwidth cost); direct keeps best. + if _proxy: + hd_fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/' + 'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best') else: - _extractor_args = { - 'youtube': { - 'player_client': ['tv_embed', 'android', 'mweb', 'web'], - 'player_skip': ['webpage', 'configs'], - } + hd_fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best' + fallback_fmt = 'best[ext=mp4]/best' + + def _base_opts(extractor_args): + return { + 'quiet': False, 'verbose': True, 'no_warnings': False, + 'cookiefile': cookies_path if cookies_path else None, + 'proxy': _proxy, 'socket_timeout': 30, 'retries': 10, 'fragment_retries': 10, + 'nocheckcertificate': True, 'cachedir': False, + 'extractor_args': extractor_args, + 'http_headers': { + 'User-Agent': ( + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' + 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' + ), + }, } - _COMMON_YDL_OPTS = { - 'quiet': False, - 'verbose': True, - 'no_warnings': False, - 'cookiefile': cookies_path if cookies_path else None, - 'proxy': _proxy, - 'socket_timeout': 30, - 'retries': 10, - 'fragment_retries': 10, - 'nocheckcertificate': True, - 'cachedir': False, - 'extractor_args': _extractor_args, - 'http_headers': { - 'User-Agent': ( - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' - 'AppleWebKit/537.36 (KHTML, like Gecko) ' - 'Chrome/120.0.0.0 Safari/537.36' - ), - }, - } - - with yt_dlp.YoutubeDL(_COMMON_YDL_OPTS) as ydl: - try: + def _attempt(extractor_args, fmt): + with yt_dlp.YoutubeDL(_base_opts(extractor_args)) as ydl: info = ydl.extract_info(url, download=False) - video_title = info.get('title', 'youtube_video') - sanitized_title = sanitize_filename(video_title) + sanitized = sanitize_filename(info.get('title', 'youtube_video')) + expected = os.path.join(output_dir, f'{sanitized}.mp4') + if os.path.exists(expected): + os.remove(expected) + dl_opts = { + **_base_opts(extractor_args), + 'format': fmt, + 'outtmpl': os.path.join(output_dir, f'{sanitized}.%(ext)s'), + 'merge_output_format': 'mp4', 'overwrites': True, + } + with yt_dlp.YoutubeDL(dl_opts) as ydl: + ydl.download([url]) + return sanitized + + attempts = ([('HD', hd_args, hd_fmt)] if hd_args else []) + [('fallback', fallback_args, fallback_fmt)] + + sanitized_title = None + last_err = None + for label, ea, fmt in attempts: + try: + print(f"📥 Download attempt: {label}") + sanitized_title = _attempt(ea, fmt) + print(f"✅ Download succeeded ({label}).") + break except Exception as e: - # Force print to stderr/stdout immediately so it's captured before crash - import sys - import traceback - - # Print minimal error first to ensure something gets out - print("🚨 YOUTUBE DOWNLOAD ERROR 🚨", file=sys.stderr) - - error_msg = f""" - + last_err = e + print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}") + + if sanitized_title is None: + import sys + error_msg = f""" ❌ ================================================================= ❌ -❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED +❌ FATAL ERROR: YOUTUBE DOWNLOAD FAILED (all strategies) ❌ ================================================================= ❌ - -REASON: YouTube has blocked the download request (Error 429/Unavailable). - This is likely a temporary IP ban on this server. +REASON: YouTube blocked the request or the download tooling is out of date. +👇 SOLUTION FOR USER: download the video manually and use the 'Upload Video' tab. +Technical Details: {str(last_err)} +""" + print(error_msg, file=sys.stdout) + print(error_msg, file=sys.stderr) + sys.stdout.flush(); sys.stderr.flush() + time.sleep(0.5) + raise last_err -👇 SOLUTION FOR USER 👇 ---------------------------------------------------------------------- -1. Download the video manually to your computer. -2. Use the 'Upload Video' tab in this app to process it. ---------------------------------------------------------------------- - -Technical Details: {str(e)} - """ - # Print to both streams to ensure capture - print(error_msg, file=sys.stdout) - print(error_msg, file=sys.stderr) - - # Force flush - sys.stdout.flush() - sys.stderr.flush() - - # Wait a split second to allow buffer to drain before raising - time.sleep(0.5) - - raise e - - output_template = os.path.join(output_dir, f'{sanitized_title}.%(ext)s') - expected_file = os.path.join(output_dir, f'{sanitized_title}.mp4') - if os.path.exists(expected_file): - os.remove(expected_file) - print(f"🗑️ Removed existing file to re-download with H.264 codec") - - # When downloading through a paid proxy, cap at 720p to control bandwidth - # cost (a 720p source is plenty for 9:16 clips). Direct downloads keep best. - if _proxy: - _fmt = ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/' - 'bestvideo[vcodec^=avc1][height<=720]+bestaudio/best[height<=720][ext=mp4]/best[height<=720]/best') - else: - _fmt = 'bestvideo[vcodec^=avc1][ext=mp4]+bestaudio[ext=m4a]/bestvideo[vcodec^=avc1]+bestaudio/best[ext=mp4]/best' - - ydl_opts = { - **_COMMON_YDL_OPTS, - 'format': _fmt, - 'outtmpl': output_template, - 'merge_output_format': 'mp4', - 'overwrites': True, - } - - with yt_dlp.YoutubeDL(ydl_opts) as ydl: - ydl.download([url]) - downloaded_file = os.path.join(output_dir, f'{sanitized_title}.mp4') - if not os.path.exists(downloaded_file): for f in os.listdir(output_dir): if f.startswith(sanitized_title) and f.endswith('.mp4'): downloaded_file = os.path.join(output_dir, f) break - - step_end_time = time.time() - print(f"✅ Video downloaded in {step_end_time - step_start_time:.2f}s: {downloaded_file}") - + + print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}") return downloaded_file, sanitized_title def process_video_to_vertical(input_video, final_output_video): From 0ba4fac47b40646d5970de640cf6a40b77d90dd2 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 14 Jul 2026 14:56:40 +0200 Subject: [PATCH 05/12] feat: durable video library on Cloudflare R2 (history + retention) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - cloud/storage.py: R2 (S3-compatible) client — upload, presigned view/download URLs, delete-by-prefix. - cloud/videos.py: archive a completed managed job's clips to R2 under users///, GET /api/history (private signed links), and a retention sweeper that deletes a user's videos 7 days after their subscription ends. - models.py: user_videos table (created via create_all). - app.py: archive clips to R2 on managed-job completion. - billing.py: email the admin the moment a subscriber hits cancel. - Frontend: History tab (library grid with per-video view + download). R2 bucket 'openshorts-videos' + scoped API token created; end-to-end verified: archive -> presigned GET (200) -> purge after grace -> object 404. --- .env.cloud.example | 7 ++ app.py | 17 ++++ cloud/__init__.py | 6 +- cloud/billing.py | 20 +++- cloud/config.py | 26 +++++ cloud/models.py | 13 +++ cloud/storage.py | 66 +++++++++++++ cloud/videos.py | 121 ++++++++++++++++++++++++ dashboard/src/App.jsx | 13 +++ dashboard/src/components/HistoryTab.jsx | 61 ++++++++++++ 10 files changed, 346 insertions(+), 4 deletions(-) create mode 100644 cloud/storage.py create mode 100644 cloud/videos.py create mode 100644 dashboard/src/components/HistoryTab.jsx diff --git a/.env.cloud.example b/.env.cloud.example index ae5c54c..93fc84d 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -43,6 +43,13 @@ OPENSHORTS_LOGO_URL=https://openshorts.app/logo.png # to 720p when this is set, to control bandwidth cost. Empty = direct download. PROXY_URL= +# Cloudflare R2 (S3-compatible) — durable storage for users' generated videos. +# Create an R2 bucket + an "Object Read & Write" API token scoped to it. +R2_ENDPOINT=https://.r2.cloudflarestorage.com +R2_BUCKET=openshorts-videos +R2_ACCESS_KEY_ID= +R2_SECRET_ACCESS_KEY= + # PO-token provider for 720p/1080p YouTube (bgutil sidecar in docker-compose.cloud.yml). # Defaults to the sidecar; only override if you run bgutil elsewhere. BGUTIL_BASE_URL=http://bgutil:4416 diff --git a/app.py b/app.py index 3a62e1d..a42207e 100644 --- a/app.py +++ b/app.py @@ -314,6 +314,8 @@ async def run_job_wrapper(job_id): # Settle the minute reservation (managed jobs only): commit on success, # release otherwise so the minutes go back to the user. await _settle_reservation(job_id) + # Archive the completed clips to the user's durable R2 library (history). + await _archive_managed_job(job_id) # Operational alerting for managed jobs (proxy out of credits / failures). await _record_job_alert(job_id) # Always release semaphore and mark queue task done @@ -322,6 +324,21 @@ async def run_job_wrapper(job_id): print(f"✅ Released slot for job: {job_id}") +async def _archive_managed_job(job_id): + if not BILLING_ENABLED: + return + job = jobs.get(job_id) or {} + if not job.get('user_id') or job.get('status') != 'completed': + return + clips = (job.get('result') or {}).get('clips') or [] + if not clips: + return + try: + await cloud.videos.archive_job(job['user_id'], job_id, clips, job['output_dir']) + except Exception as e: + print(f"⚠️ R2 archive error for {job_id}: {e}") + + async def _record_job_alert(job_id): if not BILLING_ENABLED: return diff --git a/cloud/__init__.py b/cloud/__init__.py index 13b8227..f424d9d 100644 --- a/cloud/__init__.py +++ b/cloud/__init__.py @@ -26,13 +26,14 @@ def setup_sync(app): from starlette.middleware.sessions import SessionMiddleware app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret) - from . import auth, oauth, billing, social_profiles + from . import auth, oauth, billing, social_profiles, videos oauth.register() billing._init_stripe() app.include_router(auth.router) app.include_router(oauth.router) app.include_router(billing.router) app.include_router(social_profiles.router) + app.include_router(videos.router) async def setup_async(app): @@ -40,8 +41,9 @@ async def setup_async(app): DB engine, orphaned-reservation cleanup and the metering sweeper live here. """ - from . import database, metering + from . import database, metering, videos await database.init_engine() await metering.release_orphaned_reservations() metering.start_sweeper() + videos.start_sweeper() print("☁️ Cloud billing mode ENABLED (DB ready, metering active).") diff --git a/cloud/billing.py b/cloud/billing.py index 1c81aed..3c87403 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -289,14 +289,19 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): if row and row.last_event_at and event_created < row.last_event_at: return start, end = _sub_period(sub_obj) + now_canceling = bool(sub_obj.get("cancel_at_period_end")) + # Detect the moment the user hits "cancel" (False -> True). + was_canceling = bool(row.cancel_at_period_end) if row else False + just_canceled = now_canceling and not was_canceling + end_dt = _ts(end) values = dict( stripe_subscription_id=sub_obj["id"], stripe_price_id=price_id, plan=plan, interval=interval, status=sub_obj["status"], minutes_per_period=minutes, current_period_start=_ts(start), - current_period_end=_ts(end), - cancel_at_period_end=bool(sub_obj.get("cancel_at_period_end")), + current_period_end=end_dt, + cancel_at_period_end=now_canceling, last_event_at=event_created, ) if row is None: @@ -305,6 +310,17 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): for k, v in values.items(): setattr(row, k, v) + # Churn alert to the admin the moment a subscription is set to cancel. + if just_canceled: + from .alerts import send_admin_alert + from .config import VIDEO_RETENTION_GRACE_DAYS + await send_admin_alert( + "🔻 Subscription canceled", + f"A {plan} subscriber just canceled.\n" + f"Access continues until {end_dt:%Y-%m-%d}; their videos are then kept " + f"{VIDEO_RETENTION_GRACE_DAYS} more days before deletion.", + ) + async def _set_subscription_status(sub_obj: dict, status: str, event_created: datetime): async with database.session() as s: diff --git a/cloud/config.py b/cloud/config.py index 23e6112..38d8edc 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -149,6 +149,32 @@ class Settings: def openshorts_logo_url(self) -> str: return os.environ.get("OPENSHORTS_LOGO_URL", "https://openshorts.app/logo.png") + # Cloudflare R2 (S3-compatible) — durable video library storage + @property + def r2_endpoint(self) -> str: + return os.environ.get("R2_ENDPOINT", "") + + @property + def r2_bucket(self) -> str: + return os.environ.get("R2_BUCKET", "") + + @property + def r2_access_key_id(self) -> str: + return os.environ.get("R2_ACCESS_KEY_ID", "") + + @property + def r2_secret_access_key(self) -> str: + return os.environ.get("R2_SECRET_ACCESS_KEY", "") + + @property + def r2_configured(self) -> bool: + return bool(self.r2_endpoint and self.r2_bucket and self.r2_access_key_id + and self.r2_secret_access_key) + + +# Days a user's videos survive after their subscription ends (grace period). +VIDEO_RETENTION_GRACE_DAYS = 7 + settings = Settings() diff --git a/cloud/models.py b/cloud/models.py index d265243..620d048 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -97,6 +97,19 @@ class UploadPostProfile(Base): created_at = Column(DateTime(timezone=True), server_default=func.now()) +class UserVideo(Base): + __tablename__ = "user_videos" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + user_id = Column(UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), + nullable=False, index=True) + job_id = Column(Text, nullable=False) + clip_index = Column(Integer, nullable=True) + r2_key = Column(Text, nullable=False) + title = Column(Text, nullable=True) + size_bytes = Column(Integer, nullable=True) + created_at = Column(DateTime(timezone=True), server_default=func.now()) + + class StripeEvent(Base): __tablename__ = "stripe_events" id = Column(Text, primary_key=True) # Stripe event.id — dedupe key diff --git a/cloud/storage.py b/cloud/storage.py new file mode 100644 index 0000000..9f9536c --- /dev/null +++ b/cloud/storage.py @@ -0,0 +1,66 @@ +"""Cloudflare R2 (S3-compatible) storage for the users' durable video library. + +Layout: users///. Presigned URLs give private, +time-limited view/download links. Delete-by-prefix wipes a user's whole library +when their subscription's grace period ends. +""" +import boto3 +from botocore.config import Config + +from .config import settings + +_client = None + + +def client(): + global _client + if _client is None: + _client = boto3.client( + "s3", + endpoint_url=settings.r2_endpoint, + aws_access_key_id=settings.r2_access_key_id, + aws_secret_access_key=settings.r2_secret_access_key, + region_name="auto", + config=Config(signature_version="s3v4", retries={"max_attempts": 3}), + ) + return _client + + +def user_prefix(user_id) -> str: + return f"users/{user_id}/" + + +def job_key(user_id, job_id, filename) -> str: + return f"users/{user_id}/{job_id}/{filename}" + + +def upload_file(local_path, key, content_type="video/mp4"): + client().upload_file(local_path, settings.r2_bucket, key, + ExtraArgs={"ContentType": content_type}) + + +def presigned_get(key, expires=3600, download_name=None) -> str: + params = {"Bucket": settings.r2_bucket, "Key": key} + if download_name: + params["ResponseContentDisposition"] = f'attachment; filename="{download_name}"' + return client().generate_presigned_url("get_object", Params=params, ExpiresIn=expires) + + +def delete_prefix(prefix) -> int: + """Delete every object under a prefix. Returns the count deleted.""" + c = client() + deleted = 0 + token = None + while True: + kw = {"Bucket": settings.r2_bucket, "Prefix": prefix, "MaxKeys": 1000} + if token: + kw["ContinuationToken"] = token + resp = c.list_objects_v2(**kw) + objs = [{"Key": o["Key"]} for o in resp.get("Contents", [])] + if objs: + c.delete_objects(Bucket=settings.r2_bucket, Delete={"Objects": objs}) + deleted += len(objs) + if not resp.get("IsTruncated"): + break + token = resp.get("NextContinuationToken") + return deleted diff --git a/cloud/videos.py b/cloud/videos.py new file mode 100644 index 0000000..45e81fd --- /dev/null +++ b/cloud/videos.py @@ -0,0 +1,121 @@ +"""Users' durable video library on R2: archive on completion, list for history, +purge after the subscription grace period. +""" +import asyncio +import os +from datetime import timedelta + +from fastapi import APIRouter, Request +from sqlalchemy import select, delete + +from .config import settings, VIDEO_RETENTION_GRACE_DAYS +from . import database, storage +from .models import UserVideo, Subscription +from .auth import get_current_user_required + +router = APIRouter() + + +async def archive_job(user_id, job_id, clips, output_dir): + """Upload a completed managed job's clips to R2 and record them for history.""" + if not settings.r2_configured or not clips: + return + rows = [] + for i, clip in enumerate(clips): + video_url = clip.get("video_url") or "" + filename = video_url.split("/")[-1] + if not filename: + continue + local_path = os.path.join(output_dir, filename) + if not os.path.exists(local_path): + continue + key = storage.job_key(user_id, job_id, filename) + try: + await asyncio.to_thread(storage.upload_file, local_path, key) + except Exception as e: + print(f"⚠️ R2 upload failed for {key}: {e}") + continue + rows.append(UserVideo( + user_id=user_id, job_id=job_id, clip_index=i, r2_key=key, + title=clip.get("title") or "Short", + size_bytes=os.path.getsize(local_path), + )) + if rows: + async with database.session() as s: + async with s.begin(): + s.add_all(rows) + print(f"☁️ Archived {len(rows)} clip(s) to R2 for user {user_id}.") + + +@router.get("/api/history") +async def history(request: Request): + """List the signed-in user's saved videos with private, time-limited links.""" + user = await get_current_user_required(request) + async with database.session() as s: + vids = list((await s.execute( + select(UserVideo).where(UserVideo.user_id == user.id) + .order_by(UserVideo.created_at.desc()).limit(500) + )).scalars()) + items = [] + for v in vids: + safe_name = (v.title or "short").strip().replace("/", "-")[:60] + ".mp4" + items.append({ + "id": str(v.id), + "job_id": v.job_id, + "title": v.title, + "created_at": v.created_at.isoformat() if v.created_at else None, + "size_bytes": v.size_bytes, + "view_url": storage.presigned_get(v.r2_key, expires=3600), + "download_url": storage.presigned_get(v.r2_key, expires=3600, download_name=safe_name), + }) + return {"videos": items} + + +async def purge_expired(): + """Delete R2 videos for users whose subscription ended > grace-period days ago.""" + async with database.session() as s: + # Users with a canceled subscription past the grace period, who still have videos. + canceled = list((await s.execute( + select(Subscription.user_id, Subscription.last_event_at) + .where(Subscription.status == "canceled") + )).all()) + from datetime import datetime, timezone + now = datetime.now(timezone.utc) + for user_id, last_event_at in canceled: + if not last_event_at: + continue + if last_event_at + timedelta(days=VIDEO_RETENTION_GRACE_DAYS) > now: + continue + # Any videos left? + async with database.session() as s: + has = (await s.execute( + select(UserVideo.id).where(UserVideo.user_id == user_id).limit(1) + )).first() + if not has: + continue + try: + n = await asyncio.to_thread(storage.delete_prefix, storage.user_prefix(user_id)) + async with database.session() as s: + async with s.begin(): + await s.execute(delete(UserVideo).where(UserVideo.user_id == user_id)) + print(f"🗑️ Purged {n} R2 object(s) for lapsed user {user_id}.") + except Exception as e: + print(f"⚠️ Video purge failed for {user_id}: {e}") + + +_SWEEP_INTERVAL = 6 * 3600 # every 6 hours + + +async def _sweeper_loop(): + while True: + try: + await asyncio.sleep(_SWEEP_INTERVAL) + await purge_expired() + except asyncio.CancelledError: + break + except Exception as e: + print(f"⚠️ Video retention sweeper error: {e}") + + +def start_sweeper(): + asyncio.create_task(_sweeper_loop()) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index d992ffc..c736243 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -14,6 +14,7 @@ import TopUpModal from './components/TopUpModal'; import LoginModal from './components/LoginModal'; import TrialGate from './components/TrialGate'; import AdvancedBanner from './components/AdvancedBanner'; +import HistoryTab from './components/HistoryTab'; import { useAuth } from './contexts/AuthContext'; import { apiFetch, apiJson, QuotaError } from './lib/api'; import { getApiUrl } from './config'; @@ -464,6 +465,16 @@ function App() { YouTube Studio + {billingEnabled && isSignedIn && ( + + )} + {/*
From d298f69f1206ed901e3931afd68d6d3d46597896 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 16 Jul 2026 02:07:53 +0200 Subject: [PATCH 08/12] =?UTF-8?q?feat(cloud):=20bake=20bgutil=20720p=20int?= =?UTF-8?q?o=20image,=20profile=20menu,=20video-URL=20info,=20trial?= =?UTF-8?q?=E2=86=92pricing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Dockerfile: bake bgutil PO-token provider in script mode (no sidecar); 720p verified - main.py / cloud/metering.py: support BGUTIL_SCRIPT_PATH (script mode) alongside HTTP - docker-compose.cloud.yml: drop bgutil sidecar; .env.cloud.example documents script mode - docker-compose.e2e.local.yml: local FRONTEND_URL/ALLOWED_ORIGINS/VITE_API_URL for testing - AuthContext: new/non-entitled sign-ins land on pricing to start the trial - ProfileMenu: header account dropdown (email, account & billing, sign out) - MediaInput: "YouTube URL" → "Video URL" + supported-platforms info popover --- .dockerignore | 9 ++ .env.cloud.example | 8 +- Dockerfile | 18 ++- app.py | 115 ++++++++++++++++--- cloud/config.py | 6 + cloud/metering.py | 19 ++- dashboard/src/App.jsx | 2 + dashboard/src/components/MediaInput.jsx | 68 +++++++++-- dashboard/src/components/ProfileMenu.jsx | 62 ++++++++++ dashboard/src/components/ResultCard.jsx | 5 +- dashboard/src/components/ThumbnailStudio.jsx | 2 +- dashboard/src/contexts/AuthContext.jsx | 20 +++- docker-compose.cloud.yml | 18 +-- docker-compose.e2e.local.yml | 9 ++ main.py | 17 ++- saasshorts.py | 14 ++- security_utils.py | 76 ++++++++++++ subtitles.py | 7 ++ 18 files changed, 413 insertions(+), 62 deletions(-) create mode 100644 dashboard/src/components/ProfileMenu.jsx create mode 100644 security_utils.py diff --git a/.dockerignore b/.dockerignore index 5fd8d63..429d7df 100644 --- a/.dockerignore +++ b/.dockerignore @@ -38,6 +38,15 @@ videos/ # Model files (downloaded at build time) *.pt +# Secrets — never bake real credentials into the image (repo is public, +# image may be pushed to a registry). Runtime env comes via compose env_file. +.env +.env.* +!.env.example +!.env.cloud.example +*.pem +*.key + # Docker Dockerfile docker-compose.yml diff --git a/.env.cloud.example b/.env.cloud.example index 93fc84d..e26b537 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -50,6 +50,8 @@ R2_BUCKET=openshorts-videos R2_ACCESS_KEY_ID= R2_SECRET_ACCESS_KEY= -# PO-token provider for 720p/1080p YouTube (bgutil sidecar in docker-compose.cloud.yml). -# Defaults to the sidecar; only override if you run bgutil elsewhere. -BGUTIL_BASE_URL=http://bgutil:4416 +# PO-token provider for 720p/1080p YouTube downloads. +# The bgutil provider is baked into the backend image in *script mode* +# (BGUTIL_SCRIPT_PATH is set inside the Dockerfile) — no sidecar, nothing to set here. +# Only if you run bgutil as an external HTTP service, point at it instead: +# BGUTIL_BASE_URL=http://bgutil:4416 diff --git a/Dockerfile b/Dockerfile index 56f2486..f50bcf1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -24,7 +24,7 @@ FROM python:3.11-slim WORKDIR /app -# Install FFmpeg, OpenCV dependencies, and Node.js (for yt-dlp JS challenges) +# Install FFmpeg, OpenCV deps, Node.js + npm + git (for yt-dlp JS + bgutil build) RUN apt-get update && apt-get install -y --no-install-recommends \ ffmpeg \ libgl1 \ @@ -33,19 +33,29 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ libxext6 \ libxrender1 \ nodejs \ + npm \ + git \ && rm -rf /var/lib/apt/lists/* -# Deno JS runtime — yt-dlp needs it to solve YouTube's nsig challenge for 720p+ -# (used together with the bgutil PO-token sidecar in cloud mode). +# Deno JS runtime — yt-dlp needs it to solve YouTube's nsig challenge for 720p+. COPY --from=denoland/deno:bin /deno /usr/local/bin/deno +# bgutil PO-token provider, baked in as a local Node script (script mode) — no +# separate service/sidecar needed. Unlocks 720p/1080p together with Deno. +RUN git clone --depth 1 https://github.com/Brainicism/bgutil-ytdlp-pot-provider /opt/bgutil-provider \ + && cd /opt/bgutil-provider/server \ + && npm install --no-audit --no-fund \ + && npx tsc \ + && npm cache clean --force +ENV BGUTIL_SCRIPT_PATH=/opt/bgutil-provider/server/build/generate_once.js + # Copy virtual env from builder COPY --from=builder /opt/venv /opt/venv ENV PATH="/opt/venv/bin:$PATH" ENV PYTHONUNBUFFERED=1 # Latest yt-dlp (nightly, YouTube changes constantly) + the bgutil PO-token -# provider plugin. Together with Deno + the bgutil sidecar this unlocks 720p/1080p. +# provider plugin. Together with Deno + the baked-in bgutil script this unlocks 720p. RUN pip install --upgrade --pre --no-cache-dir "yt-dlp[default]" bgutil-ytdlp-pot-provider # Copy application code diff --git a/app.py b/app.py index dfe8ca3..a65b968 100644 --- a/app.py +++ b/app.py @@ -120,8 +120,13 @@ async def reserve_process_minutes(request, url, input_path, job_id): For a managed (entitled, no BYOK header) request this probes the input duration, enforces the per-user concurrent-job limit, and reserves minutes — raising 402 (quota) or 429 (too many jobs) as needed. + + NOTE: in cloud mode ``resolve_gemini`` ignores ``X-Gemini-Key`` (paid-only, + no BYOK), so we must NOT skip metering just because that header is present — + otherwise a client could send a dummy header and run unlimited managed jobs + on the operator's key for free. Only skip metering when billing is off. """ - if not BILLING_ENABLED or request.headers.get("X-Gemini-Key"): + if not BILLING_ENABLED: return None, 2, None user = await _user_from_request(request) if not managed_keys.has_active_entitlement(user): @@ -180,6 +185,23 @@ async def reserve_managed_action(request, minutes, job_id, job_type): "minutes_remaining": e.remaining, }) + +async def require_managed_entitlement(request): + """Gate a managed compute endpoint that doesn't resolve a Gemini key itself. + + Some endpoints (subtitle/hook FFmpeg re-encodes, render proxy, the thumbnail + upload that kicks off a YouTube download + Whisper) do expensive server work + without ever calling ``resolve_gemini``, so nothing was stopping an anonymous + or non-entitled caller from driving unbounded compute in cloud mode. In cloud + mode this rejects them with 402; it's a no-op for self-host (BILLING off). + """ + if not BILLING_ENABLED: + return None + user = await _user_from_request(request) + if not managed_keys.has_active_entitlement(user): + raise gemini_missing_error() + return user + # Application State # PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first: # pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps @@ -402,6 +424,20 @@ THUMBNAILS_DIR = os.path.join(OUTPUT_DIR, "thumbnails") os.makedirs(THUMBNAILS_DIR, exist_ok=True) app.mount("/thumbnails", StaticFiles(directory=THUMBNAILS_DIR), name="thumbnails") + +def _safe_under(base_dir: str, user_rel_path: str) -> Optional[str]: + """Resolve ``user_rel_path`` under ``base_dir`` and reject path traversal. + + Returns the absolute path only if it stays inside ``base_dir`` (after + following ``..``); otherwise None. Used to sanitize client-supplied file + references so ``../../.env`` can't escape the output directories. + """ + base = os.path.realpath(base_dir) + target = os.path.realpath(os.path.join(base, user_rel_path)) + if target == base or target.startswith(base + os.sep): + return target + return None + class ProcessRequest(BaseModel): url: str @@ -674,11 +710,17 @@ async def edit_clip( if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") - + job = jobs[req.job_id] if 'result' not in job or 'clips' not in job['result']: raise HTTPException(status_code=400, detail="Job result not available") - + + # Meter the managed Gemini call so it can't be looped for free. Skip when the + # caller supplied their own key (BYOK body) or self-host (reserve is a no-op). + edit_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0 + reservation_id = None if req.api_key else await reserve_managed_action( + request, edit_minutes, req.job_id, "edit") + try: # Resolve Input Path: Prefer explict input_filename from frontend (chaining edits) if req.input_filename: @@ -769,18 +811,22 @@ async def edit_clip( # Updating job result allows persistence if page refreshes. new_video_url = f"/videos/{req.job_id}/{edited_filename}" - + # Start a new "edited" clip entry or just update the current one? # Let's update the current one's video_url but keep backup? # Or return the new URL to the frontend to display. - + + if reservation_id: + await _metering.commit_reservation(reservation_id) return { - "success": True, + "success": True, "new_video_url": new_video_url, "edit_plan": plan } except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) print(f"❌ Edit Error: {e}") raise HTTPException(status_code=500, detail=str(e)) @@ -851,6 +897,7 @@ RENDER_SERVICE_URL = os.getenv("RENDER_SERVICE_URL", "http://renderer:3100") @app.post("/api/render") async def proxy_render(request: Request): """Proxy render requests to the Node.js Remotion render service.""" + await require_managed_entitlement(request) import httpx body = await request.json() try: @@ -895,6 +942,10 @@ async def generate_effects_config( if 'result' not in job or 'clips' not in job['result']: raise HTTPException(status_code=400, detail="Job result not available") + # Meter the managed Gemini call (no-op for self-host). + fx_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action(request, fx_minutes, req.job_id, "effects") + try: # Resolve input path if req.input_filename: @@ -973,17 +1024,24 @@ async def generate_effects_config( if effects_config is None: raise HTTPException(status_code=500, detail="Failed to generate effects config from Gemini") + if reservation_id: + await _metering.commit_reservation(reservation_id) return {"effects": effects_config} except HTTPException: + if reservation_id: + await _metering.release_reservation(reservation_id) raise except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) print(f"❌ Effects Generation Error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.post("/api/subtitle") -async def add_subtitles(req: SubtitleRequest): +async def add_subtitles(req: SubtitleRequest, request: Request): + await require_managed_entitlement(request) if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") @@ -1104,7 +1162,8 @@ class HookRequest(BaseModel): size: Optional[str] = "M" # S, M, L @app.post("/api/hook") -async def add_hook(req: HookRequest): +async def add_hook(req: HookRequest, request: Request): + await require_managed_entitlement(request) if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") @@ -1450,10 +1509,12 @@ async def get_social_user(request: Request): @app.post("/api/thumbnail/upload") async def thumbnail_upload( + request: Request, file: Optional[UploadFile] = File(None), url: Optional[str] = Form(None), ): """Upload video and start background Whisper transcription immediately.""" + await require_managed_entitlement(request) if not url and not file: raise HTTPException(status_code=400, detail="Must provide URL or File") @@ -1568,6 +1629,10 @@ async def thumbnail_analyze( content = await file.read() buffer.write(content) + # Meter the managed Gemini analysis (no-op for self-host). + analyze_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action(request, analyze_minutes, session_id, "thumbnail_analyze") + try: # Run analysis in thread pool (skips Whisper if pre_transcript is available) loop = asyncio.get_event_loop() @@ -1587,6 +1652,8 @@ async def thumbnail_analyze( "video_duration": result.get("video_duration", 0) }) + if reservation_id: + await _metering.commit_reservation(reservation_id) return { "session_id": session_id, "titles": result.get("titles", []), @@ -1596,6 +1663,8 @@ async def thumbnail_analyze( } except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) print(f"❌ Thumbnail Analyze Error: {e}") raise HTTPException(status_code=500, detail=str(e)) @@ -1808,15 +1877,19 @@ async def thumbnail_publish( if not video_path or not os.path.exists(video_path): raise HTTPException(status_code=404, detail="Original video file not found") - # Resolve thumbnail path from URL + # Resolve thumbnail path from URL — sanitize against path traversal so a + # crafted thumbnail_url (e.g. "thumbnails/../../.env") can't read server + # files and exfiltrate them via the Upload-Post multipart body. thumb_relative = thumbnail_url.lstrip("/") if thumb_relative.startswith("thumbnails/"): - thumb_path = os.path.join(OUTPUT_DIR, thumb_relative) + thumb_path = _safe_under(OUTPUT_DIR, thumb_relative) else: - thumb_path = os.path.join(THUMBNAILS_DIR, thumb_relative) + thumb_path = _safe_under(THUMBNAILS_DIR, thumb_relative) + if not thumb_path: + raise HTTPException(status_code=400, detail="Invalid thumbnail path") if not os.path.exists(thumb_path): - raise HTTPException(status_code=404, detail=f"Thumbnail file not found: {thumb_path}") + raise HTTPException(status_code=404, detail="Thumbnail file not found") # Generate a unique ID for this publish job so the frontend can poll publish_id = str(uuid.uuid4()) @@ -1951,6 +2024,10 @@ async def saasshorts_analyze( if not req.url and not req.description: raise HTTPException(status_code=400, detail="Provide a URL or a product description") + # Meter the managed Gemini research/analysis (no-op for self-host). + saas_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action(request, saas_minutes, "saasshorts", "saasshorts_analyze") + try: loop = asyncio.get_event_loop() @@ -1982,9 +2059,13 @@ async def saasshorts_analyze( } result = await loop.run_in_executor(None, run_analysis) + if reservation_id: + await _metering.commit_reservation(reservation_id) return result except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) raise HTTPException(status_code=500, detail=str(e)) @@ -2400,10 +2481,13 @@ async def saasshorts_generate( if req.selected_actor_url.startswith("http"): # Download from S3 public URL to job output dir import httpx + from security_utils import assert_public_url try: + # SSRF guard: block private / metadata hosts before fetching. + safe_actor_url = assert_public_url(req.selected_actor_url) actor_local = os.path.join(job_output_dir, "selected_actor.png") with httpx.Client(timeout=30.0) as client: - resp = client.get(req.selected_actor_url) + resp = client.get(safe_actor_url) if resp.status_code == 200: with open(actor_local, "wb") as f: f.write(resp.content) @@ -2411,8 +2495,9 @@ async def saasshorts_generate( except Exception: pass else: - src = os.path.join(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", "")) - if os.path.exists(src): + # Sanitize against traversal — the client controls selected_actor_url. + src = _safe_under(OUTPUT_DIR, req.selected_actor_url.replace("/videos/", "").lstrip("/")) + if src and os.path.exists(src): selected_actor_path = src config = { diff --git a/cloud/config.py b/cloud/config.py index 38d8edc..c702e42 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -37,6 +37,12 @@ TRIAL_DAYS = 3 # roughly matching its cost to the per-minute economics. Text (titles/desc) is free. THUMBNAIL_MINUTES = 3 +# Other managed Gemini calls that upload a video for context (AI effect/filter +# generation, thumbnail analysis, SaaS-shorts analysis). Cheaper than image gen +# but not free — meter a small fixed cost so an entitled user can't loop them to +# burn the operator's managed Gemini budget. Pure-text calls (titles/desc) stay free. +MANAGED_ANALYSIS_MINUTES = 1 + # Stripe prices are resolved at runtime by these stable lookup_keys, so no price # IDs need to be copied into env vars (they differ between test and live anyway). SUBSCRIPTION_LOOKUP_KEYS = [ diff --git a/cloud/metering.py b/cloud/metering.py index 6e71779..c0cb4eb 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -72,13 +72,24 @@ def probe_url_minutes(url: str) -> float: bandwidth. Raises ValueError if the duration is unknown (e.g. live streams). """ import yt_dlp - bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip() + # SSRF guard: reject non-http(s) / private / metadata hosts before probing. + from security_utils import assert_public_url + assert_public_url(url) + + bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip() + bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip() proxy = os.environ.get("PROXY_URL", "").strip() conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"], "player_skip": ["webpage", "configs"]}} - # Try the bgutil/HD extractor first, then the conservative one — mirrors the - # download's HD→fallback logic so the probe never fails alone. - strategies = ([{"youtubepot-bgutilhttp": {"base_url": [bgutil]}}] if bgutil else []) + [conservative] + # Try the bgutil/HD extractor first (http or baked-in script), then the + # conservative one — mirrors the download's HD→fallback logic. + if bgutil_http: + hd = [{"youtubepot-bgutilhttp": {"base_url": [bgutil_http]}}] + elif bgutil_script: + hd = [{"youtubepot-bgutilscript": {"script_path": [bgutil_script]}}] + else: + hd = [] + strategies = hd + [conservative] last_err = None for extractor_args in strategies: diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index c736243..39e9390 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -15,6 +15,7 @@ import LoginModal from './components/LoginModal'; import TrialGate from './components/TrialGate'; import AdvancedBanner from './components/AdvancedBanner'; import HistoryTab from './components/HistoryTab'; +import ProfileMenu from './components/ProfileMenu'; import { useAuth } from './contexts/AuthContext'; import { apiFetch, apiJson, QuotaError } from './lib/api'; import { getApiUrl } from './config'; @@ -573,6 +574,7 @@ function App() { Sign in )} + {billingEnabled && isSignedIn && } {keysMissing && ( )} + {showInfo && ( +
+

Paste a link from

+
+ {SUPPORTED_PLATFORMS.map((p) => ( + + {p} + + ))} +
+

+ …and 1,000+ more sites. If a link has a public video, we can usually fetch it. +

+
+ )} +
+
) : (
{ + if (!open) return; + const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }; + document.addEventListener('mousedown', onClick); + return () => document.removeEventListener('mousedown', onClick); + }, [open]); + + if (!user) return null; + const initial = (user.email || '?').trim().charAt(0).toUpperCase(); + + return ( +
+ + + {open && ( +
+
+

Signed in as

+

{user.email}

+
+ {!isManaged && ( + + )} + + +
+ )} +
+ ); +} diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index a1ac9c4..75a4010 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -1,6 +1,7 @@ import React, { useState, useEffect } from 'react'; import { Download, Share2, Instagram, Youtube, Video, CheckCircle, AlertCircle, X, Loader2, Copy, Wand2, Type, Calendar, Clock, Languages } from 'lucide-react'; import { getApiUrl } from '../config'; +import { apiFetch } from '../lib/api'; import SubtitleModal from './SubtitleModal'; import HookModal from './HookModal'; import TranslateModal from './TranslateModal'; @@ -165,7 +166,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs } // Fallback: legacy FFmpeg - const res = await fetch(getApiUrl('/api/subtitle'), { + const res = await apiFetch('/api/subtitle', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ @@ -224,7 +225,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs ? { text: hookData, position: 'top', size: 'M' } : hookData; - const res = await fetch(getApiUrl('/api/hook'), { + const res = await apiFetch('/api/hook', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ diff --git a/dashboard/src/components/ThumbnailStudio.jsx b/dashboard/src/components/ThumbnailStudio.jsx index 3b4b7b3..04b8641 100644 --- a/dashboard/src/components/ThumbnailStudio.jsx +++ b/dashboard/src/components/ThumbnailStudio.jsx @@ -151,7 +151,7 @@ export default function ThumbnailStudio({ geminiApiKey, uploadPostKey, uploadUse const formData = new FormData(); formData.append('file', file); - const res = await fetch(getApiUrl('/api/thumbnail/upload'), { + const res = await apiFetch('/api/thumbnail/upload', { method: 'POST', body: formData }); diff --git a/dashboard/src/contexts/AuthContext.jsx b/dashboard/src/contexts/AuthContext.jsx index db95819..376e695 100644 --- a/dashboard/src/contexts/AuthContext.jsx +++ b/dashboard/src/contexts/AuthContext.jsx @@ -40,10 +40,19 @@ export function AuthProvider({ children }) { const params = new URLSearchParams(query); setSigningIn(true); + let destination = '#app'; try { if (kind === 'callback') { const token = params.get('token'); - if (token) setToken(token); + if (token) { + setToken(token); + // Scrub the token from the URL immediately (replaceState, no new + // history entry) so the bearer token isn't left reachable via Back. + try { + window.history.replaceState(null, document.title, + window.location.pathname + window.location.search); + } catch (_) { /* ignore */ } + } } else if (kind === 'verify') { const ml = params.get('ml'); if (ml) { @@ -55,13 +64,16 @@ export function AuthProvider({ children }) { if (data.token) setToken(data.token); } } - await refreshMe(); + const signedInMe = await refreshMe(); + // New sign-ups (and anyone without an active plan/trial) go straight to + // pricing so they can start their free trial; entitled users land in the app. + if (signedInMe?.user && !signedInMe?.entitled) destination = '#/pricing'; } catch (e) { // fall through — user lands signed-out } finally { setSigningIn(false); - // Clear the sensitive hash, land in the app. - window.location.hash = '#app'; + // Clear the sensitive hash, land wherever we resolved above. + window.location.hash = destination; } return true; }, [refreshMe]); diff --git a/docker-compose.cloud.yml b/docker-compose.cloud.yml index ff1a4af..876dc0d 100644 --- a/docker-compose.cloud.yml +++ b/docker-compose.cloud.yml @@ -10,7 +10,8 @@ services: container_name: openshorts-db environment: - POSTGRES_USER=openshorts - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-openshorts} + # Fail the deploy loudly if unset, rather than silently using a weak default. + - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set for cloud mode} - POSTGRES_DB=openshorts volumes: - pgdata:/var/lib/postgresql/data @@ -21,22 +22,13 @@ services: retries: 10 restart: unless-stopped - # PO-token provider — lets yt-dlp fetch YouTube's GVS PO tokens so 720p/1080p - # formats are available (with Deno + a recent yt-dlp in the backend image). - bgutil: - image: brainicism/bgutil-ytdlp-pot-provider - container_name: openshorts-bgutil - restart: unless-stopped - backend: depends_on: db: condition: service_healthy - bgutil: - condition: service_started environment: - BILLING_ENABLED=true - - DATABASE_URL=postgresql+asyncpg://openshorts:${POSTGRES_PASSWORD:-openshorts}@db:5432/openshorts + - DATABASE_URL=postgresql+asyncpg://openshorts:${POSTGRES_PASSWORD:?POSTGRES_PASSWORD must be set for cloud mode}@db:5432/openshorts - JWT_SECRET=${JWT_SECRET} - FRONTEND_URL=${FRONTEND_URL:-https://openshorts.app} - ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-https://openshorts.app} @@ -57,8 +49,8 @@ services: # Residential proxy for YouTube downloads (avoids datacenter-IP bans). # e.g. http://user:pass@gate.dataimpulse.com:823 — leave empty to go direct. - PROXY_URL=${PROXY_URL:-} - # PO-token provider (bgutil sidecar) → unlocks 720p/1080p downloads. - - BGUTIL_BASE_URL=${BGUTIL_BASE_URL:-http://bgutil:4416} + # 720p/1080p: the bgutil PO-token provider is baked into the backend image + # (script mode, BGUTIL_SCRIPT_PATH). No sidecar or BGUTIL_BASE_URL needed. volumes: pgdata: diff --git a/docker-compose.e2e.local.yml b/docker-compose.e2e.local.yml index 4dd4570..244b0e0 100644 --- a/docker-compose.e2e.local.yml +++ b/docker-compose.e2e.local.yml @@ -5,6 +5,15 @@ services: backend: ports: !override - "8001:8000" + environment: + # Point auth/magic-link/CORS at the local frontend instead of openshorts.app. + - FRONTEND_URL=http://localhost:5176 + - ALLOWED_ORIGINS=http://localhost:5176,http://localhost:5175,http://localhost:8001 frontend: ports: !override - "5176:5173" + environment: + # Call the backend directly (not via the Vite proxy) so Google OAuth builds + # a redirect_uri of http://localhost:8001/... which matches the registered + # client. Cross-origin API calls are allowed by ALLOWED_ORIGINS above. + - VITE_API_URL=http://localhost:8001 diff --git a/main.py b/main.py index 17919a4..42b413b 100644 --- a/main.py +++ b/main.py @@ -451,6 +451,11 @@ def download_youtube_video(url, output_dir="."): Downloads a YouTube video using yt-dlp. Returns the path to the downloaded video and the video title. """ + # SSRF guard: block non-http(s) schemes and private/loopback/metadata hosts + # before handing the URL to yt-dlp. + from security_utils import assert_public_url + assert_public_url(url) + print(f"🔍 Debug: yt-dlp version: {yt_dlp.version.__version__}") print("📥 Downloading video from YouTube...") step_start_time = time.time() @@ -487,8 +492,16 @@ def download_youtube_video(url, output_dir="."): # (BGUTIL_BASE_URL, needs the sidecar + Deno + recent yt-dlp) → 720p/1080p. # 2) Fallback — conservative tv_embed/android clients, no PO provider (~360p), # which is also the ONLY strategy for self-host (no bgutil configured). - _bgutil = os.environ.get("BGUTIL_BASE_URL", "").strip() - hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil]}} if _bgutil else None + # PO-token provider: HTTP mode (external BGUTIL_BASE_URL) or the baked-in + # local Node script (BGUTIL_SCRIPT_PATH, set in the image). Either enables HD. + _bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip() + _bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip() + if _bgutil_http: + hd_args = {'youtubepot-bgutilhttp': {'base_url': [_bgutil_http]}} + elif _bgutil_script: + hd_args = {'youtubepot-bgutilscript': {'script_path': [_bgutil_script]}} + else: + hd_args = None fallback_args = { 'youtube': { 'player_client': ['tv_embed', 'android', 'mweb', 'web'], diff --git a/saasshorts.py b/saasshorts.py index 2a00472..b7c2374 100644 --- a/saasshorts.py +++ b/saasshorts.py @@ -150,15 +150,25 @@ Be thorough. Use REAL data from your search results, not made-up information.""" def scrape_website(url: str) -> dict: """Scrape a SaaS website to extract key content for analysis.""" from bs4 import BeautifulSoup + from security_utils import assert_public_url + # SSRF guard: reject non-http(s) / private / metadata hosts, and re-validate + # every redirect hop so a public URL can't 30x-bounce us to an internal host. + current = assert_public_url(url) print(f"[SaaSShorts] 🌐 Scraping {url}...") headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } - with httpx.Client(timeout=30.0, follow_redirects=True) as client: - response = client.get(url, headers=headers) + with httpx.Client(timeout=30.0, follow_redirects=False) as client: + response = None + for _ in range(5): + response = client.get(current, headers=headers) + if response.has_redirect_location: + current = assert_public_url(str(response.next_request.url)) + continue + break response.raise_for_status() soup = BeautifulSoup(response.text, "html.parser") diff --git a/security_utils.py b/security_utils.py new file mode 100644 index 0000000..c4731e2 --- /dev/null +++ b/security_utils.py @@ -0,0 +1,76 @@ +"""Small, dependency-free SSRF guards shared by the download / scrape paths. + +The app fetches user-supplied URLs server-side (yt-dlp downloads, SaaS landing +page scraping, actor-image download). Without a guard, a caller can point those +at internal services or the cloud metadata endpoint (169.254.169.254) to read +instance credentials. ``assert_public_url`` rejects non-HTTP(S) schemes and any +host that resolves to a private / loopback / link-local / reserved address. +""" +from __future__ import annotations + +import ipaddress +import socket +from urllib.parse import urlparse + + +class UnsafeURLError(ValueError): + """Raised when a URL is not safe to fetch server-side.""" + + +def _ip_is_public(ip: str) -> bool: + try: + addr = ipaddress.ip_address(ip) + except ValueError: + return False + return not ( + addr.is_private + or addr.is_loopback + or addr.is_link_local + or addr.is_reserved + or addr.is_multicast + or addr.is_unspecified + ) + + +def assert_public_url(url: str) -> str: + """Return ``url`` if it is safe to fetch, else raise ``UnsafeURLError``. + + Blocks non-http(s) schemes and hosts that resolve to any non-public IP. + Resolves every A/AAAA record so a hostname that maps to a private range + (or to 169.254.169.254) is rejected rather than silently fetched. + """ + if not url or not isinstance(url, str): + raise UnsafeURLError("Empty URL") + + parsed = urlparse(url.strip()) + if parsed.scheme.lower() not in ("http", "https"): + raise UnsafeURLError(f"Unsupported URL scheme: {parsed.scheme!r}") + + host = parsed.hostname + if not host: + raise UnsafeURLError("URL has no host") + + # If the host is a literal IP, validate it directly (no DNS). + try: + ipaddress.ip_address(host) + is_ip_literal = True + except ValueError: + is_ip_literal = False + + if is_ip_literal: + if not _ip_is_public(host): + raise UnsafeURLError(f"URL host is not a public address: {host}") + return url + + try: + infos = socket.getaddrinfo(host, parsed.port or None, proto=socket.IPPROTO_TCP) + except socket.gaierror as e: + raise UnsafeURLError(f"Could not resolve host {host!r}: {e}") + + resolved = {info[4][0] for info in infos} + if not resolved: + raise UnsafeURLError(f"Host {host!r} did not resolve") + for ip in resolved: + if not _ip_is_public(ip): + raise UnsafeURLError(f"Host {host!r} resolves to a non-public address: {ip}") + return url diff --git a/subtitles.py b/subtitles.py index f961a0a..40ac111 100644 --- a/subtitles.py +++ b/subtitles.py @@ -155,6 +155,13 @@ def burn_subtitles(video_path, srt_path, output_path, alignment=2, fontsize=16, - Outline mode (bg_opacity=0): Text with colored outline/border - Box mode (bg_opacity>0): Text with semi-transparent background box """ + # Sanitize the client-supplied font name before it goes into the FFmpeg + # force_style string. A quote/comma/colon/backslash would break out of the + # quoted style and inject extra libavfilter directives (filtergraph + # injection / DoS). Keep only safe font-name characters. + import re as _re + font_name = _re.sub(r"[^A-Za-z0-9 _\-]", "", str(font_name))[:64].strip() or "Verdana" + # Position mapping ass_alignment = 2 align_lower = str(alignment).lower() From c0ad5e0de88297731e3ede7555f9f57a4bc9528d Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 16 Jul 2026 02:13:55 +0200 Subject: [PATCH 09/12] feat(billing): 20-min trial cap + activate-plan-now upgrade flow MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config: TRIAL_MINUTE_CAP=20 — trial allowance capped across all plans - metering: apply the cap in _balance while status=trialing (full minutes once active) - billing: POST /api/billing/end-trial ends the Stripe trial immediately (charge now, unlock full minutes); webhook flips status→active - frontend: hitting the cap while trialing opens TrialUpgradeModal (activate plan now) instead of the top-up modal; polls /api/me until active - Legal: disclose the 20-minute trial allowance --- cloud/billing.py | 22 +++++ cloud/config.py | 8 +- cloud/metering.py | 6 +- dashboard/src/App.jsx | 21 ++++- dashboard/src/Legal.jsx | 10 +- .../src/components/TrialUpgradeModal.jsx | 93 +++++++++++++++++++ 6 files changed, 151 insertions(+), 9 deletions(-) create mode 100644 dashboard/src/components/TrialUpgradeModal.jsx diff --git a/cloud/billing.py b/cloud/billing.py index 3c87403..b80b483 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -153,6 +153,28 @@ async def create_checkout(body: CheckoutRequest, request: Request): return {"url": session.url} +@router.post("/api/billing/end-trial") +async def end_trial(request: Request): + """End the free trial immediately: charge the card now and unlock full plan + minutes. Used when a trialing user hits the trial minute cap and chooses to + activate their plan right away. The subscription webhook flips status→active + (and thus the full ``minutes_per_period`` allowance) once Stripe confirms.""" + user = await get_current_user_required(request) + async with database.session() as session: + sub = (await session.execute( + select(Subscription).where(Subscription.user_id == user.id) + )).scalar_one_or_none() + if not sub or sub.status != "trialing": + raise HTTPException(status_code=409, detail="No active trial to convert.") + try: + updated = await asyncio.to_thread(lambda: stripe.Subscription.modify( + sub.stripe_subscription_id, trial_end="now", + )) + except Exception: + raise HTTPException(status_code=502, detail="Could not activate your plan. Try again.") + return {"status": updated.get("status", "active")} + + @router.post("/api/billing/portal") async def create_portal(request: Request): user = await get_current_user_required(request) diff --git a/cloud/config.py b/cloud/config.py index c702e42..7dd8b9c 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -28,9 +28,15 @@ PLAN_MINUTES = { } # Free trial length (days) for new subscriptions. Card required; auto-charges at -# the end. No minute cap during the trial — the card + Stripe Radar deter abuse. +# the end. TRIAL_DAYS = 3 +# Minute cap DURING the trial (across all plans). Enough to evaluate the product, +# but bounds the free managed-compute / proxy exposure per sign-up so a +# cancel-before-charge account can't burn a full plan's worth of minutes. Once the +# trial converts to an active subscription the full plan allowance applies. +TRIAL_MINUTE_CAP = 20 + # Gemini IMAGE generation (thumbnails) is the one expensive managed Gemini call # (~$0.04/image, batch of ~3). It isn't naturally minute-metered, so each # thumbnail generation batch consumes this many minutes from the plan quota — diff --git a/cloud/metering.py b/cloud/metering.py index c0cb4eb..fcd7c88 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -26,7 +26,7 @@ from decimal import Decimal from sqlalchemy import select, update, func, and_ -from . import database +from . import config, database from .models import User, Subscription, CreditTopup, UsageLedger @@ -143,6 +143,10 @@ async def _balance(session, user_id): """Return a dict of the user's current minute balance (read-only).""" sub = await _active_subscription(session, user_id) plan_allowance = _D(sub.minutes_per_period) if sub else _D(0) + # During the trial, cap the allowance so a cancel-before-charge account can't + # burn a whole plan's worth of managed minutes. Full allowance once active. + if sub and sub.status == "trialing": + plan_allowance = min(plan_allowance, _D(config.TRIAL_MINUTE_CAP)) period_end = sub.current_period_end if sub else None plan_used = await _plan_used_this_period(session, user_id, period_end) if sub else _D(0) plan_remaining = max(_D(0), plan_allowance - plan_used) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 39e9390..67e3c61 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -11,6 +11,7 @@ import UGCGallery from './components/UGCGallery'; import ScheduleWeekModal from './components/ScheduleWeekModal'; import UsageMeter from './components/UsageMeter'; import TopUpModal from './components/TopUpModal'; +import TrialUpgradeModal from './components/TrialUpgradeModal'; import LoginModal from './components/LoginModal'; import TrialGate from './components/TrialGate'; import AdvancedBanner from './components/AdvancedBanner'; @@ -144,9 +145,10 @@ const pollJob = async (jobId) => { function App() { // Cloud auth/billing session (inert when billing is disabled). - const { billingEnabled, isManaged, isSignedIn, signingIn } = useAuth(); + const { billingEnabled, isManaged, isSignedIn, signingIn, me, plan, refreshMe } = useAuth(); const [showLogin, setShowLogin] = useState(false); const [showTopUp, setShowTopUp] = useState(false); + const [showTrialUpgrade, setShowTrialUpgrade] = useState(false); const [topUpInfo, setTopUpInfo] = useState({}); const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || ''); @@ -396,8 +398,14 @@ function App() { } catch (e) { if (e instanceof QuotaError) { setStatus('idle'); - setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining }); - setShowTopUp(true); + // Trial users hit the trial minute cap → prompt them to activate the plan + // now (unlocks full minutes). Active users → offer a top-up. + if (me?.status === 'trialing') { + setShowTrialUpgrade(true); + } else { + setTopUpInfo({ required: e.minutesRequired, remaining: e.minutesRemaining }); + setShowTopUp(true); + } return; } setStatus('error'); @@ -1230,6 +1238,13 @@ function App() { remaining={topUpInfo.remaining} /> )} + {showTrialUpgrade && ( + setShowTrialUpgrade(false)} + /> + )}
); } diff --git a/dashboard/src/Legal.jsx b/dashboard/src/Legal.jsx index 3bcdd35..f721a16 100644 --- a/dashboard/src/Legal.jsx +++ b/dashboard/src/Legal.jsx @@ -72,10 +72,12 @@ export default function Legal() {

Free trial: new subscriptions start with a{' '} - 3-day free trial. You provide a payment method up front - but are not charged during the trial. If you do not - cancel before the trial ends, your subscription automatically begins and your payment method is - charged the plan price. You can cancel at any time from your account. + 3-day free trial that includes up to{' '} + 20 minutes of video processing. You provide a payment + method up front but are not charged during the trial. If + you do not cancel before the trial ends, your subscription automatically begins, your full plan + minutes unlock, and your payment method is charged the plan price. You can cancel at any time from + your account.

Auto-renewal: subscriptions renew automatically each diff --git a/dashboard/src/components/TrialUpgradeModal.jsx b/dashboard/src/components/TrialUpgradeModal.jsx new file mode 100644 index 0000000..3c39460 --- /dev/null +++ b/dashboard/src/components/TrialUpgradeModal.jsx @@ -0,0 +1,93 @@ +import React, { useState, useEffect } from 'react'; +import { X, Loader2, Rocket, CheckCircle2 } from 'lucide-react'; +import { apiJson } from '../lib/api'; + +// Shown when a TRIALING user hits the trial minute cap. Lets them end the trial +// and activate the paid plan right away (charges the card now, unlocks the full +// monthly minutes). The subscription webhook flips status→active server-side. +export default function TrialUpgradeModal({ plan, onActivated, onClose }) { + const [busy, setBusy] = useState(false); + const [done, setDone] = useState(false); + const [error, setError] = useState(''); + const [planMinutes, setPlanMinutes] = useState(null); + + // Look up the full monthly minutes for the current plan (to show what unlocks). + useEffect(() => { + apiJson('/api/billing/plans') + .then((d) => { + const match = (d.plans || []).find((p) => p.plan === plan && p.interval === 'month'); + if (match) setPlanMinutes(match.minutes); + }) + .catch(() => {}); + }, [plan]); + + const activate = async () => { + setBusy(true); + setError(''); + try { + const res = await apiJson('/api/billing/end-trial', { method: 'POST' }); + // Poll /api/me until the webhook flips the subscription to active. + let ok = res?.status === 'active'; + for (let i = 0; i < 10 && !ok; i++) { + await new Promise((r) => setTimeout(r, 1500)); + const me = await onActivated(); + ok = me?.status === 'active'; + } + if (ok) { + setDone(true); + setTimeout(onClose, 1800); + } else { + // Charge is processing (or card needs attention) — let them proceed anyway. + await onActivated(); + setError('Almost there — your plan is activating. If it doesn\'t unlock in a minute, check your billing details.'); + } + } catch (e) { + setError('Could not activate your plan. Please try again or manage billing from your account.'); + } finally { + setBusy(false); + } + }; + + return ( +

+
+ + + {done ? ( +
+
+

You're all set 🎉

+

Your plan is active{planMinutes ? ` with ${planMinutes} minutes` : ''}. Go ahead and generate your clips.

+
+ ) : ( + <> +
+

You've used your free trial minutes

+

+ Activate your{plan ? <> {plan} : ''} plan now to unlock{' '} + {planMinutes ? <>{planMinutes} minutes every month : 'your full monthly minutes'} and keep creating. + Your card is charged today and your 3-day trial ends now. +

+ + {error &&

{error}

} + + + + + )} +
+
+ ); +} From 6ec6935532b083b75d1d83bdf2bef8ebf10525af Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 16 Jul 2026 17:30:12 +0200 Subject: [PATCH 10/12] fix(cloud): harden paid-mode surface + source-available license for cloud/ Security fixes on the hosted/paid surface (all no-op in self-host / BYOK): - upload path traversal: basename() client filenames in /api/process, /api/thumbnail/upload, /api/thumbnail/analyze fallback, /api/thumbnail/generate (face/bg + session_id) so "../" can't escape UPLOAD_DIR - SSRF: saasshorts subpage scraper now follow_redirects=False + assert_public_url per hop (was open to 302 -> 169.254.169.254 metadata) - metering: reserve+commit/release on /api/render, /api/subtitle, /api/hook and a fixed guard cost on /api/thumbnail/upload transcription (were entitlement-gated but unmetered -> unlimited off-quota compute) - entitlement: SaaSShorts generate/actor-options/actor-upload now require a plan in cloud; /api/edit ignores body api_key in cloud (no gate/meter bypass) - multi-tenant IDOR: stamp user_id on thumbnail_sessions/saas_jobs and reject non-owners (404) across status/mutation/publish/post endpoints - DoS: bounded/streamed reads on actor-upload and thumbnail uploads - retry_job_id routed through _safe_under Frontend: raw fetch -> apiFetch on the now-gated/owner-checked endpoints so the bearer token attaches. License: cloud/ is now source-available under the OpenShorts Commercial License (self-host/personal use allowed; no competing hosted service). Core stays MIT. --- LICENSE | 4 + README.md | 4 +- app.py | 204 ++++++++++++++---- cloud/LICENSE | 66 ++++++ cloud/config.py | 12 ++ dashboard/src/App.jsx | 2 +- dashboard/src/components/ResultCard.jsx | 10 +- dashboard/src/components/SaaShortsTab.jsx | 6 +- .../src/components/ScheduleWeekModal.jsx | 3 +- dashboard/src/components/SubtitleModal.jsx | 3 +- saasshorts.py | 16 +- 11 files changed, 278 insertions(+), 52 deletions(-) create mode 100644 cloud/LICENSE diff --git a/LICENSE b/LICENSE index a5ad963..1d5dbfc 100644 --- a/LICENSE +++ b/LICENSE @@ -2,6 +2,10 @@ MIT License Copyright (c) 2024 OpenShorts +EXCEPTION: All content that resides under the "cloud/" directory of this +repository is licensed under the license defined in "cloud/LICENSE" +(the OpenShorts Commercial License), not under the MIT License below. + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights diff --git a/README.md b/README.md index 6b14e2a..25afdf0 100644 --- a/README.md +++ b/README.md @@ -294,4 +294,6 @@ Contributions are welcome! Whether it's adding new AI models, improving the lip- ## License -MIT License. OpenShorts is yours to use, modify, and scale. +MIT License for the core application — OpenShorts is yours to use, modify, and scale. + +**Exception:** the [`cloud/`](cloud/LICENSE) directory (billing, managed keys, and the hosted-service infrastructure behind the optional `BILLING_ENABLED` flag) is source-available under the OpenShorts Commercial License. You can read it, modify it, and self-host it for personal or internal use, but you can't offer it to third parties as a paid/hosted service. Self-hosting the core app never requires this directory. diff --git a/app.py b/app.py index a65b968..daeb77d 100644 --- a/app.py +++ b/app.py @@ -202,6 +202,34 @@ async def require_managed_entitlement(request): raise gemini_missing_error() return user + +async def _owner_id(request): + """The authenticated cloud user's id to stamp on a new job/session, or None + for self-host / BYOK / anonymous (BILLING off → nothing to scope).""" + if not BILLING_ENABLED: + return None + user = await _user_from_request(request) + return user.id if user else None + + +async def _assert_job_owner(request, record): + """Cloud multi-tenant guard: reject unless the caller owns this in-memory + job/session record. + + No-op for self-host (BILLING off) and for records with no owner stamped + (BYOK / self-host jobs never set ``user_id``). Returns 404 rather than 403 so + a non-owner can't even confirm the id exists. UUID ids already make these + stores hard to enumerate; this closes the gap for a shared/leaked id. + """ + if not BILLING_ENABLED: + return + owner = record.get("user_id") if isinstance(record, dict) else None + if owner is None: + return + user = await _user_from_request(request) + if user is None or user.id != owner: + raise HTTPException(status_code=404, detail="Not found") + # Application State # PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first: # pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps @@ -632,8 +660,11 @@ async def process_endpoint( if url: cmd.extend(["-u", url]) else: - # Save uploaded file with size limit check - input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{file.filename}") + # Save uploaded file with size limit check. + # basename() strips any path components from the client-supplied + # filename so a name like "../../main.py" can't escape UPLOAD_DIR. + safe_name = os.path.basename(file.filename or "upload") or "upload" + input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{safe_name}") # Read file in chunks to check size size = 0 @@ -674,11 +705,12 @@ async def process_endpoint( return {"job_id": job_id, "status": "queued"} @app.get("/api/status/{job_id}") -async def get_status(job_id: str): +async def get_status(job_id: str, request: Request): if job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") - + job = jobs[job_id] + await _assert_job_owner(request, job) return { "status": job['status'], "logs": job['logs'], @@ -702,8 +734,11 @@ async def edit_clip( req: EditRequest, request: Request, ): - # BYOK body key wins; otherwise resolve header / managed / self-host env. - final_api_key = req.api_key or await resolve_gemini(request) + # Cloud (paid) mode disables BYOK: ignore any body api_key so it can't skip + # the entitlement gate or metering (mirrors resolve_gemini ignoring the + # header). Self-host keeps BYOK — the body key wins there. + body_key = None if BILLING_ENABLED else req.api_key + final_api_key = body_key or await resolve_gemini(request) if not final_api_key: raise gemini_missing_error() @@ -712,13 +747,14 @@ async def edit_clip( raise HTTPException(status_code=404, detail="Job not found") job = jobs[req.job_id] + await _assert_job_owner(request, job) if 'result' not in job or 'clips' not in job['result']: raise HTTPException(status_code=400, detail="Job result not available") - # Meter the managed Gemini call so it can't be looped for free. Skip when the - # caller supplied their own key (BYOK body) or self-host (reserve is a no-op). + # Meter the managed Gemini call so it can't be looped for free. Skip only for + # genuine BYOK (self-host body key) — in cloud, body_key is always None. edit_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0 - reservation_id = None if req.api_key else await reserve_managed_action( + reservation_id = None if body_key else await reserve_managed_action( request, edit_minutes, req.job_id, "edit") try: @@ -845,11 +881,12 @@ class SubtitleRequest(BaseModel): @app.get("/api/clip/{job_id}/{clip_index}/transcript") -async def get_clip_transcript(job_id: str, clip_index: int): +async def get_clip_transcript(job_id: str, clip_index: int, request: Request): """Return word-level captions for a specific clip, formatted for Remotion.""" if job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") + await _assert_job_owner(request, jobs[job_id]) output_dir = os.path.join(OUTPUT_DIR, job_id) json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) @@ -900,11 +937,19 @@ async def proxy_render(request: Request): await require_managed_entitlement(request) import httpx body = await request.json() + render_minutes = _cloud_config.RENDER_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action( + request, render_minutes, str(uuid.uuid4()), "render") try: async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.post(f"{RENDER_SERVICE_URL}/render", json=body) - return resp.json() + result = resp.json() + if reservation_id: + await _metering.commit_reservation(reservation_id) + return result except Exception as e: + if reservation_id: + await _metering.release_reservation(reservation_id) raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}") @app.get("/api/render/{render_id}") @@ -939,6 +984,7 @@ async def generate_effects_config( raise HTTPException(status_code=404, detail="Job not found") job = jobs[req.job_id] + await _assert_job_owner(request, job) if 'result' not in job or 'clips' not in job['result']: raise HTTPException(status_code=400, detail="Job result not available") @@ -1047,7 +1093,8 @@ async def add_subtitles(req: SubtitleRequest, request: Request): # Reload job data from disk just in case metadata was updated job = jobs[req.job_id] - + await _assert_job_owner(request, job) + # We need to access metadata.json to get the transcript output_dir = os.path.join(OUTPUT_DIR, req.job_id) json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) @@ -1093,7 +1140,13 @@ async def add_subtitles(req: SubtitleRequest, request: Request): # We create a new file "subtitled_..." output_filename = f"subtitled_{filename}" output_path = os.path.join(output_dir, output_filename) - + + # Meter the FFmpeg re-encode (and any dubbed-video re-transcription) so it + # can't be looped for free off-quota. No-op for BYOK / self-host. + subtitle_minutes = _cloud_config.SUBTITLE_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action( + request, subtitle_minutes, req.job_id, "subtitle") + try: # 1. Generate SRT # Check if this is a dubbed video - if so, transcribe it fresh @@ -1126,8 +1179,13 @@ async def add_subtitles(req: SubtitleRequest, request: Request): except Exception as e: print(f"❌ Subtitle Error: {e}") + if reservation_id: + await _metering.release_reservation(reservation_id) raise HTTPException(status_code=500, detail=str(e)) - + + if reservation_id: + await _metering.commit_reservation(reservation_id) + # 3. Update Result and Metadata # Update InMemory Jobs if req.clip_index < len(job['result']['clips']): @@ -1166,8 +1224,9 @@ async def add_hook(req: HookRequest, request: Request): await require_managed_entitlement(request) if req.job_id not in jobs: raise HTTPException(status_code=404, detail="Job not found") - + job = jobs[req.job_id] + await _assert_job_owner(request, job) output_dir = os.path.join(OUTPUT_DIR, req.job_id) json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) @@ -1203,19 +1262,29 @@ async def add_hook(req: HookRequest, request: Request): # Map Size to Scale size_map = {"S": 0.8, "M": 1.0, "L": 1.3} font_scale = size_map.get(req.size, 1.0) - + + # Meter the FFmpeg overlay re-encode (no-op for BYOK / self-host). + hook_minutes = _cloud_config.HOOK_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action( + request, hook_minutes, req.job_id, "hook") + try: # Run in thread pool def run_hook(): add_hook_to_video(input_path, req.text, output_path, position=req.position, font_scale=font_scale) - + loop = asyncio.get_event_loop() await loop.run_in_executor(None, run_hook) - + except Exception as e: print(f"❌ Hook Error: {e}") + if reservation_id: + await _metering.release_reservation(reservation_id) raise HTTPException(status_code=500, detail=str(e)) - + + if reservation_id: + await _metering.commit_reservation(reservation_id) + # Update Persistence (Same logic as subtitles) # Update InMemory Jobs if req.clip_index < len(job['result']['clips']): @@ -1252,6 +1321,7 @@ async def get_languages(): @app.post("/api/translate") async def translate_clip( req: TranslateRequest, + request: Request, x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key") ): """Translate a video clip to a different language using ElevenLabs dubbing.""" @@ -1262,6 +1332,7 @@ async def translate_clip( raise HTTPException(status_code=404, detail="Job not found") job = jobs[req.job_id] + await _assert_job_owner(request, job) output_dir = os.path.join(OUTPUT_DIR, req.job_id) json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) @@ -1362,6 +1433,7 @@ async def post_to_socials(req: SocialPostRequest, request: Request): raise HTTPException(status_code=400, detail="Missing Upload-Post user profile") job = jobs[req.job_id] + await _assert_job_owner(request, job) if 'result' not in job or 'clips' not in job['result']: raise HTTPException(status_code=400, detail="Job result not available") @@ -1521,16 +1593,31 @@ async def thumbnail_upload( session_id = str(uuid.uuid4()) transcript_event = asyncio.Event() - # Save file if uploaded directly + # Save file if uploaded directly. basename() stops a "../../x" filename from + # escaping UPLOAD_DIR; the chunked read caps memory so a huge body can't OOM. video_path = None if file: - video_path = os.path.join(UPLOAD_DIR, f"thumb_{session_id}_{file.filename}") + safe_name = os.path.basename(file.filename or "upload") or "upload" + video_path = os.path.join(UPLOAD_DIR, f"thumb_{session_id}_{safe_name}") + size = 0 + limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024 with open(video_path, "wb") as buffer: - content = await file.read() - buffer.write(content) + while chunk := await file.read(1024 * 1024): + size += len(chunk) + if size > limit_bytes: + os.remove(video_path) + raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB") + buffer.write(chunk) + + # Meter a fixed guard cost for the background download + Whisper transcription + # so an entitled user can't loop it for free. Settled when the job finishes. + transcribe_minutes = _cloud_config.TRANSCRIBE_MINUTES if BILLING_ENABLED else 0 + reservation_id = await reserve_managed_action( + request, transcribe_minutes, session_id, "thumbnail_transcribe") # Initialize session thumbnail_sessions[session_id] = { + "user_id": await _owner_id(request), "video_path": video_path, "transcript_event": transcript_event, "transcript_ready": False, @@ -1568,9 +1655,13 @@ async def thumbnail_upload( "language": transcript.get("language", "en"), }) print(f"✅ [Thumbnail] Background Whisper complete for session {session_id}") + if reservation_id: + await _metering.commit_reservation(reservation_id) except Exception as e: print(f"❌ [Thumbnail] Background Whisper failed: {e}") thumbnail_sessions[session_id]["transcript_error"] = str(e) + if reservation_id: + await _metering.release_reservation(reservation_id) finally: transcript_event.set() @@ -1597,6 +1688,7 @@ async def thumbnail_analyze( # Check for pre-existing session with background Whisper if session_id and session_id in thumbnail_sessions: session = thumbnail_sessions[session_id] + await _assert_job_owner(request, session) # Wait for background Whisper to complete transcript_event = session.get("transcript_event") @@ -1624,10 +1716,17 @@ async def thumbnail_analyze( from main import download_youtube_video video_path, _ = download_youtube_video(url, UPLOAD_DIR) else: - video_path = os.path.join(UPLOAD_DIR, f"thumb_{session_id}_{file.filename}") + safe_name = os.path.basename(file.filename or "upload") or "upload" + video_path = os.path.join(UPLOAD_DIR, f"thumb_{session_id}_{safe_name}") + size = 0 + limit_bytes = MAX_FILE_SIZE_MB * 1024 * 1024 with open(video_path, "wb") as buffer: - content = await file.read() - buffer.write(content) + while chunk := await file.read(1024 * 1024): + size += len(chunk) + if size > limit_bytes: + os.remove(video_path) + raise HTTPException(status_code=413, detail=f"File too large. Max size {MAX_FILE_SIZE_MB}MB") + buffer.write(chunk) # Meter the managed Gemini analysis (no-op for self-host). analyze_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0 @@ -1640,7 +1739,7 @@ async def thumbnail_analyze( # Store/update session context if session_id not in thumbnail_sessions: - thumbnail_sessions[session_id] = {} + thumbnail_sessions[session_id] = {"user_id": await _owner_id(request)} thumbnail_sessions[session_id].update({ "context": result.get("transcript_summary", ""), @@ -1689,11 +1788,14 @@ async def thumbnail_titles( session_id = req.session_id or str(uuid.uuid4()) if session_id not in thumbnail_sessions: thumbnail_sessions[session_id] = { + "user_id": await _owner_id(request), "context": "", "titles": [req.title], "language": "en", "conversation": [] } + else: + await _assert_job_owner(request, thumbnail_sessions[session_id]) return {"session_id": session_id, "titles": [req.title]} # Refinement mode @@ -1704,6 +1806,7 @@ async def thumbnail_titles( raise HTTPException(status_code=400, detail="Must provide message or title") session = thumbnail_sessions[req.session_id] + await _assert_job_owner(request, session) # Add user message to conversation history session["conversation"].append({"role": "user", "content": req.message}) @@ -1753,20 +1856,24 @@ async def thumbnail_generate( thumb_minutes = _cloud_config.THUMBNAIL_MINUTES if BILLING_ENABLED else 0 reservation_id = await reserve_managed_action(request, thumb_minutes, session_id, "thumbnail") - # Save optional uploaded images + # Save optional uploaded images. basename() on the session id and filenames + # keeps everything inside UPLOAD_DIR (no "../" escape from client input). face_path = None bg_path = None - thumb_upload_dir = os.path.join(UPLOAD_DIR, f"thumb_{session_id}") + safe_session = os.path.basename(session_id) or "session" + thumb_upload_dir = os.path.join(UPLOAD_DIR, f"thumb_{safe_session}") os.makedirs(thumb_upload_dir, exist_ok=True) try: if face and face.filename: - face_path = os.path.join(thumb_upload_dir, f"face_{face.filename}") + face_name = os.path.basename(face.filename) + face_path = os.path.join(thumb_upload_dir, f"face_{face_name}") with open(face_path, "wb") as f: f.write(await face.read()) if background and background.filename: - bg_path = os.path.join(thumb_upload_dir, f"bg_{background.filename}") + bg_name = os.path.basename(background.filename) + bg_path = os.path.join(thumb_upload_dir, f"bg_{bg_name}") with open(bg_path, "wb") as f: f.write(await background.read()) @@ -1827,6 +1934,7 @@ async def thumbnail_describe( raise HTTPException(status_code=404, detail="Session not found") session = thumbnail_sessions[req.session_id] + await _assert_job_owner(request, session) segments = session.get("transcript_segments", []) if not segments: raise HTTPException(status_code=400, detail="No transcript segments available. Please analyze a video first.") @@ -1873,6 +1981,7 @@ async def thumbnail_publish( raise HTTPException(status_code=400, detail="Missing Upload-Post user profile") session = thumbnail_sessions[session_id] + await _assert_job_owner(request, session) video_path = session.get("video_path") if not video_path or not os.path.exists(video_path): raise HTTPException(status_code=404, detail="Original video file not found") @@ -2076,13 +2185,21 @@ class SaaSActorRequest(BaseModel): @app.post("/api/saasshorts/actor-upload") -async def saasshorts_actor_upload(file: UploadFile = File(...)): +async def saasshorts_actor_upload(request: Request, file: UploadFile = File(...)): """Upload a custom actor image (stored locally only, not S3).""" + # SaaSShorts is part of the paid product — require entitlement in cloud mode + # (no-op for self-host) so anonymous callers can't drive server work. + await require_managed_entitlement(request) if not file.content_type or not file.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="File must be an image") try: - content = await file.read() + # Bounded read: an actor image has no business being large. Cap it so an + # anonymous caller can't stream a multi-GB body into RAM (OOM DoS). + ACTOR_IMAGE_MAX_BYTES = 25 * 1024 * 1024 # 25 MB + content = await file.read(ACTOR_IMAGE_MAX_BYTES + 1) + if len(content) > ACTOR_IMAGE_MAX_BYTES: + raise HTTPException(status_code=413, detail="Image too large (max 25 MB)") # Validate minimum size if len(content) < 1000: @@ -2108,9 +2225,11 @@ async def saasshorts_actor_upload(file: UploadFile = File(...)): @app.post("/api/saasshorts/actor-options") async def saasshorts_actor_options( req: SaaSActorRequest, + request: Request, x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"), ): """Generate multiple actor image options for the user to choose from.""" + await require_managed_entitlement(request) fal_key = x_fal_key if not fal_key: raise HTTPException(status_code=400, detail="Missing fal.ai API Key") @@ -2186,6 +2305,7 @@ async def saasshorts_post_to_socials(req: SaaSPostRequest, request: Request): raise HTTPException(status_code=400, detail="Missing Upload-Post user profile") job = saas_jobs[req.job_id] + await _assert_job_owner(request, job) result = job.get("result") if not result or not result.get("video_url"): raise HTTPException(status_code=400, detail="No video available for this job") @@ -2428,10 +2548,12 @@ class SaaSGenerateRequest(BaseModel): @app.post("/api/saasshorts/generate") async def saasshorts_generate( req: SaaSGenerateRequest, + request: Request, x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"), x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key"), ): """Generate a SaaS UGC video from a script. Returns a job_id for polling.""" + await require_managed_entitlement(request) fal_key = x_fal_key elevenlabs_key = x_elevenlabs_key @@ -2443,12 +2565,17 @@ async def saasshorts_generate( # Support retry: reuse output_dir so cached assets (image, voice, head, broll) are kept reused = False if req.retry_job_id: - # Check memory first, then disk - old_dir = os.path.join(OUTPUT_DIR, f"saas_{req.retry_job_id}") + # Check memory first, then disk. _safe_under() blocks a crafted + # retry_job_id like "../../tmp/x" from escaping OUTPUT_DIR (the listdir + # below deletes files and the pipeline writes here). A known in-memory + # job keeps its trusted stored path. if req.retry_job_id in saas_jobs: + await _assert_job_owner(request, saas_jobs[req.retry_job_id]) old_dir = saas_jobs[req.retry_job_id]["output_dir"] + else: + old_dir = _safe_under(OUTPUT_DIR, f"saas_{req.retry_job_id}") - if os.path.isdir(old_dir): + if old_dir and os.path.isdir(old_dir): job_id = req.retry_job_id job_output_dir = old_dir reused = True @@ -2458,6 +2585,7 @@ async def saasshorts_generate( if f.endswith("_final.mp4") and os.path.getsize(fp) == 0: os.remove(fp) saas_jobs[job_id] = { + "user_id": await _owner_id(request), "status": "processing", "logs": [f"Retrying job {job_id[:8]}... reusing cached assets from disk."], "result": None, @@ -2469,6 +2597,7 @@ async def saasshorts_generate( job_output_dir = os.path.join(OUTPUT_DIR, f"saas_{job_id}") os.makedirs(job_output_dir, exist_ok=True) saas_jobs[job_id] = { + "user_id": await _owner_id(request), "status": "processing", "logs": ["SaaSShorts job started."], "result": None, @@ -2580,12 +2709,13 @@ async def saasshorts_generate( @app.get("/api/saasshorts/status/{job_id}") -async def saasshorts_status(job_id: str): +async def saasshorts_status(job_id: str, request: Request): """Poll SaaSShorts job status.""" if job_id not in saas_jobs: raise HTTPException(status_code=404, detail="SaaSShorts job not found") job = saas_jobs[job_id] + await _assert_job_owner(request, job) return { "status": job["status"], "logs": job["logs"], diff --git a/cloud/LICENSE b/cloud/LICENSE new file mode 100644 index 0000000..d30ce46 --- /dev/null +++ b/cloud/LICENSE @@ -0,0 +1,66 @@ +The OpenShorts Commercial License (the "Commercial License") +Copyright (c) 2024-present OpenShorts (openshorts.app) + +All source code and associated documentation files contained in this +directory ("cloud/") and its subdirectories (the "Commercial Software") +are NOT covered by the MIT License that applies to the rest of this +repository. The Commercial Software is licensed under the following +terms instead. + +Permitted use +------------- + +Subject to the conditions below, you are granted a limited, non-exclusive, +non-transferable, royalty-free license to: + + 1. View, study, and modify the Commercial Software. + 2. Copy and self-host the Commercial Software for your own PERSONAL or + INTERNAL business use (i.e., use by you or within your own + organization). + 3. Contribute changes to the Commercial Software back to this + repository. + +Prohibited use +-------------- + +You may NOT, without a separate written commercial agreement with the +copyright holder: + + 1. Offer the Commercial Software, or any modified version or derivative + of it, to third parties as a hosted, managed, or paid service + (including but not limited to Software-as-a-Service, resale, + white-labeling, or any offering that competes with the hosted + service at openshorts.app). + 2. Sell, sublicense, or redistribute the Commercial Software, on its + own or as part of another product or service, for a fee or other + consideration. + 3. Remove, alter, or circumvent any license, billing, metering, + entitlement, or usage-limit functionality contained in the + Commercial Software when providing access to third parties. + +Clarifications +-------------- + + - Everything OUTSIDE the cloud/ directory remains licensed under the + MIT License (see the LICENSE file at the repository root). You can + self-host, modify, and use the core OpenShorts application freely + under that license, with or without this directory present. The + application runs fully without the Commercial Software when the + BILLING_ENABLED flag is not set. + - Contributions submitted to this directory are accepted under these + same terms, and the contributor grants the copyright holder the + right to license the contribution commercially. + +For commercial licensing inquiries, contact: jc.caverogracia@gmail.com + +Disclaimer +---------- + +THE COMMERCIAL SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +COMMERCIAL SOFTWARE OR THE USE OR OTHER DEALINGS IN THE COMMERCIAL +SOFTWARE. diff --git a/cloud/config.py b/cloud/config.py index 7dd8b9c..12645f5 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -49,6 +49,18 @@ THUMBNAIL_MINUTES = 3 # burn the operator's managed Gemini budget. Pure-text calls (titles/desc) stay free. MANAGED_ANALYSIS_MINUTES = 1 +# Post-processing FFmpeg re-encodes (subtitle burn, hook overlay) and the +# Remotion render proxy do real server compute per call. Meter a small fixed +# cost so an entitled user can't loop them for free off-quota. +SUBTITLE_MINUTES = 2 +HOOK_MINUTES = 1 +RENDER_MINUTES = 3 + +# The thumbnail-studio upload kicks off a (possibly YouTube) download + a full +# Whisper transcription in the background — expensive and proxy-bandwidth-heavy. +# Charge a fixed guard cost up front, settled when the background job finishes. +TRANSCRIBE_MINUTES = 2 + # Stripe prices are resolved at runtime by these stable lookup_keys, so no price # IDs need to be copied into env vars (they differ between test and live anyway). SUBSCRIPTION_LOOKUP_KEYS = [ diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 67e3c61..284431d 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -138,7 +138,7 @@ const SESSION_MAX_AGE = 3600000; // 1 hour (matches server job retention) // Mock polling function const pollJob = async (jobId) => { - const res = await fetch(getApiUrl(`/api/status/${jobId}`)); + const res = await apiFetch(`/api/status/${jobId}`); if (!res.ok) throw new Error('Status check failed'); return res.json(); }; diff --git a/dashboard/src/components/ResultCard.jsx b/dashboard/src/components/ResultCard.jsx index 75a4010..a314880 100644 --- a/dashboard/src/components/ResultCard.jsx +++ b/dashboard/src/components/ResultCard.jsx @@ -43,7 +43,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs // Fetch clip duration from transcript endpoint useEffect(() => { if (!jobId || index === undefined) return; - fetch(getApiUrl(`/api/clip/${jobId}/${index}/transcript`)) + apiFetch(`/api/clip/${jobId}/${index}/transcript`) .then(res => res.ok ? res.json() : null) .then(data => { if (data && data.durationSec) setClipDuration(data.durationSec); @@ -73,7 +73,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs } // Try Remotion effects endpoint first - const effectsRes = await fetch(getApiUrl('/api/effects/generate'), { + const effectsRes = await apiFetch('/api/effects/generate', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -105,7 +105,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs } // Fallback: legacy FFmpeg edit endpoint - const res = await fetch(getApiUrl('/api/edit'), { + const res = await apiFetch('/api/edit', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -274,7 +274,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs console.log('[Translate] Request body:', requestBody); console.log('[Translate] Sending request to /api/translate'); - const res = await fetch(getApiUrl('/api/translate'), { + const res = await apiFetch('/api/translate', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -354,7 +354,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; } - const res = await fetch(getApiUrl('/api/social/post'), { + const res = await apiFetch('/api/social/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) diff --git a/dashboard/src/components/SaaShortsTab.jsx b/dashboard/src/components/SaaShortsTab.jsx index e905c19..1016b3c 100644 --- a/dashboard/src/components/SaaShortsTab.jsx +++ b/dashboard/src/components/SaaShortsTab.jsx @@ -144,7 +144,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo if (jobId && genStatus === 'processing') { interval = setInterval(async () => { try { - const res = await fetch(getApiUrl(`/api/saasshorts/status/${jobId}`)); + const res = await apiFetch(`/api/saasshorts/status/${jobId}`); if (res.status === 404) { // Job lost (server restart) — treat as failed so Retry appears setGenStatus('failed'); @@ -1015,7 +1015,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo const formData = new FormData(); formData.append('file', file); try { - const res = await fetch(getApiUrl('/api/saasshorts/actor-upload'), { + const res = await apiFetch('/api/saasshorts/actor-upload', { method: 'POST', body: formData, }); @@ -1078,7 +1078,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo setActorOptions([]); setSelectedActor(null); try { - const res = await fetch(getApiUrl('/api/saasshorts/actor-options'), { + const res = await apiFetch('/api/saasshorts/actor-options', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Fal-Key': falKey }, body: JSON.stringify({ actor_description: actorDescription, num_options: 3 }), diff --git a/dashboard/src/components/ScheduleWeekModal.jsx b/dashboard/src/components/ScheduleWeekModal.jsx index adc54ce..780d282 100644 --- a/dashboard/src/components/ScheduleWeekModal.jsx +++ b/dashboard/src/components/ScheduleWeekModal.jsx @@ -1,6 +1,7 @@ import React, { useState, useMemo } from 'react'; import { X, Loader2, Calendar, Clock, CheckCircle, AlertCircle, Video, Instagram, Youtube, ChevronLeft, ChevronRight, Globe, ExternalLink } from 'lucide-react'; import { getApiUrl } from '../config'; +import { apiFetch } from '../lib/api'; const DAYS = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb']; const MONTHS = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']; @@ -134,7 +135,7 @@ export default function ScheduleWeekModal({ isOpen, onClose, clips, jobId, uploa }; try { - const res = await fetch(getApiUrl('/api/social/post'), { + const res = await apiFetch('/api/social/post', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) diff --git a/dashboard/src/components/SubtitleModal.jsx b/dashboard/src/components/SubtitleModal.jsx index bedc266..5a94ad2 100644 --- a/dashboard/src/components/SubtitleModal.jsx +++ b/dashboard/src/components/SubtitleModal.jsx @@ -1,6 +1,7 @@ import React, { useState, useEffect } from 'react'; import { X, Type, Loader2 } from 'lucide-react'; import { getApiUrl } from '../config'; +import { apiFetch } from '../lib/api'; import RemotionPreview from './RemotionPreview'; const FONT_OPTIONS = [ @@ -54,7 +55,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin if (!isOpen || !jobId || clipIndex === undefined) return; setCaptionsLoading(true); - fetch(getApiUrl(`/api/clip/${jobId}/${clipIndex}/transcript`)) + apiFetch(`/api/clip/${jobId}/${clipIndex}/transcript`) .then((res) => res.ok ? res.json() : null) .then((data) => { if (data && data.captions && data.captions.length > 0) { diff --git a/saasshorts.py b/saasshorts.py index b7c2374..5d2c285 100644 --- a/saasshorts.py +++ b/saasshorts.py @@ -221,9 +221,19 @@ def scrape_website(url: str) -> dict: for sub_url in list(subpages)[:3]: try: print(f"[SaaSShorts] → Subpage: {sub_url}") - with httpx.Client(timeout=20.0, follow_redirects=True) as client: - resp = client.get(sub_url, headers=headers) - if resp.status_code == 200: + # Same SSRF guard as the main page: no auto-redirects and re-validate + # every hop, so a same-host page can't 30x-bounce us onto an internal + # host (e.g. 169.254.169.254 cloud metadata). + sub_current = assert_public_url(sub_url) + with httpx.Client(timeout=20.0, follow_redirects=False) as client: + resp = None + for _ in range(5): + resp = client.get(sub_current, headers=headers) + if resp.has_redirect_location: + sub_current = assert_public_url(str(resp.next_request.url)) + continue + break + if resp is not None and resp.status_code == 200: sub_soup = BeautifulSoup(resp.text, "html.parser") for tag in sub_soup(["script", "style", "nav", "footer", "header", "noscript"]): tag.decompose() From 0f8e19f1199a7924167d7a2f70cd6c78baa506f7 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 16 Jul 2026 17:43:28 +0200 Subject: [PATCH 11/12] feat(ui): support email, in-app pricing link, landing pricing section MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - App sidebar: Support card (mailto:info@openshorts.app) + "Plans & Pricing" link (billing-gated) - Landing: embedded 3-tier pricing section (live from Stripe), Pricing nav link, hosted card mentions the saved video library — all gated on billingEnabled so self-host shows nothing broken --- dashboard/src/App.jsx | 28 +++++++++++++++++++++++++++- dashboard/src/Landing.jsx | 29 +++++++++++++++++++++++++---- 2 files changed, 52 insertions(+), 5 deletions(-) diff --git a/dashboard/src/App.jsx b/dashboard/src/App.jsx index 284431d..78df909 100644 --- a/dashboard/src/App.jsx +++ b/dashboard/src/App.jsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react'; -import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2 } from 'lucide-react'; +import { Upload, FileVideo, Sparkles, Youtube, Instagram, Share2, LogOut, ChevronDown, Check, Activity, LayoutDashboard, Settings, PlusCircle, History, Menu, X, Terminal, Shield, LayoutGrid, Image, Globe, RotateCcw, Calendar, AlertTriangle, KeyRound, Bot, Users, Smartphone, ExternalLink, Copy, CheckCircle2, Mail } from 'lucide-react'; import KeyInput from './components/KeyInput'; import MediaInput from './components/MediaInput'; import ResultCard from './components/ResultCard'; @@ -529,6 +529,32 @@ function App() {

Free & Community Driven

+ {billingEnabled && ( + +
+ +
+
+

Plans & Pricing

+

View all plans

+
+
+ )} + +
+ +
+
+

Support

+

info@openshorts.app

+
+
); diff --git a/dashboard/src/Landing.jsx b/dashboard/src/Landing.jsx index 0789c94..23f7a79 100644 --- a/dashboard/src/Landing.jsx +++ b/dashboard/src/Landing.jsx @@ -1,5 +1,7 @@ import React from 'react'; import { Sparkles, Zap, Globe, FileVideo, Subtitles, Youtube, Instagram, Shield, Github, ArrowRight, Play, Check, ChevronDown, Monitor, Cpu, Languages, Type, Upload, Scissors } from 'lucide-react'; +import PricingSection from './components/PricingSection'; +import { useAuth } from './contexts/AuthContext'; const TikTokIcon = ({ size = 16, className = "" }) => ( @@ -56,6 +58,7 @@ const FAQItem = ({ question, answer, isOpen, onClick }) => ( ); export default function Landing({ onLaunchApp }) { + const { billingEnabled } = useAuth(); const [openFaq, setOpenFaq] = React.useState(null); const features = [ @@ -199,6 +202,7 @@ export default function Landing({ onLaunchApp }) {
Features How It Works + {billingEnabled && Pricing} Comparison FAQ
@@ -336,17 +340,34 @@ export default function Landing({ onLaunchApp }) { From $12/mo

- Zero setup, no API keys, we run all the AI and compute for you. 3-day free trial, then a plan - from $12/mo (100 min). Best if you just want to make clips without any technical hassle. + Zero setup, no API keys — we run all the AI and compute for you, and every clip you make is saved + to your private library. Sign in with email or Google. 3-day free trial, then a plan from + $12/mo (100 min). Best if you just want to make clips without any technical hassle.

- +
+ {/* Pricing Section — hosted plans (self-host stays free) */} + {billingEnabled && ( +
+
+
+

Simple, transparent pricing

+

+ Same features on every plan — you only pay for volume. Start with a 3-day free trial (card required, + 20 free minutes), cancel anytime. Prefer to self-host? It stays free forever. +

+
+ { window.location.hash = '#/pricing'; }} /> +
+
+ )} + {/* 3 Tools in 1 Section */}
From 3b2221b0d2d31ea69264a3d473d6e96ffc19420d Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Thu, 16 Jul 2026 17:59:07 +0200 Subject: [PATCH 12/12] feat(alerts): Telegram admin alerts for purchases + ops issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config: TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID + telegram_configured - alerts: send_telegram(); send_admin_alert now pushes to Telegram + email (so existing proxy-out-of-credits and high-failure alerts hit Telegram too) - billing webhook: alert on new subscription, trial→paid conversion, and top-up - .env.cloud.example documents the Telegram vars Verified end-to-end: alert delivered to the admin group via the same send_admin_alert path the webhook uses. Token stays in gitignored .env. --- .env.cloud.example | 7 +++++++ cloud/alerts.py | 27 +++++++++++++++++++++++++-- cloud/billing.py | 32 ++++++++++++++++++++++++++++++++ cloud/config.py | 13 +++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) diff --git a/.env.cloud.example b/.env.cloud.example index e26b537..71fc8f0 100644 --- a/.env.cloud.example +++ b/.env.cloud.example @@ -23,6 +23,13 @@ EMAIL_FROM=OpenShorts # Operational alerts (proxy out of credits / high failure rate) are emailed here. ADMIN_EMAIL=you@example.com +# Telegram admin alerts (optional) — instant pings for purchases, cancellations, +# proxy-out-of-credits and high failure rate. Create a bot with @BotFather to get +# the token, then message your bot and read the chat id from: +# https://api.telegram.org/bot/getUpdates +TELEGRAM_BOT_TOKEN= +TELEGRAM_CHAT_ID= + # Google OAuth (optional; magic link works without it) GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= diff --git a/cloud/alerts.py b/cloud/alerts.py index 7d40cfb..be18a30 100644 --- a/cloud/alerts.py +++ b/cloud/alerts.py @@ -33,11 +33,34 @@ def _cooldown_ok(kind: str) -> bool: return True +async def send_telegram(text: str): + """Push a plain-text message to the admin's Telegram chat. No-op if unset. + + Best-effort: never raises — an alert failing must not break a webhook or job. + """ + if not settings.telegram_configured: + return + try: + import httpx + url = f"https://api.telegram.org/bot{settings.telegram_bot_token}/sendMessage" + payload = {"chat_id": settings.telegram_chat_id, "text": text, + "disable_web_page_preview": True} + async with httpx.AsyncClient(timeout=10) as client: + await client.post(url, json=payload) + except Exception as e: + print(f"⚠️ Telegram alert failed: {e}") + + async def send_admin_alert(subject: str, body: str): + """Notify the admin via every configured channel (email + Telegram).""" + # Telegram first — instant, and configured independently of email. + await send_telegram(f"{subject}\n\n{body}") + to = settings.admin_email if not to or not settings.smtp_configured: - print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}" - + ("" if to else " (set ADMIN_EMAIL + SMTP_* to email these)")) + if not settings.telegram_configured: + print(f"⚠️ [ADMIN ALERT] {subject}\n{body[:500]}" + + ("" if to else " (set ADMIN_EMAIL + SMTP_* or TELEGRAM_* to receive these)")) return html = f"
{body}
" await send_email(to, f"[OpenShorts] {subject}", html) diff --git a/cloud/billing.py b/cloud/billing.py index b80b483..17561a2 100644 --- a/cloud/billing.py +++ b/cloud/billing.py @@ -243,6 +243,7 @@ async def _apply_topup(session_obj: dict): minutes = int((session_obj.get("metadata") or {}).get("minutes") or 0) if minutes <= 0: return + buyer_email = None async with database.session() as s: async with s.begin(): existing = (await s.execute( @@ -259,6 +260,15 @@ async def _apply_topup(session_obj: dict): user_id=user_id, stripe_session_id=session_id, minutes_total=minutes, minutes_consumed=0, )) + buyer_email = (await s.execute( + select(User.email).where(User.id == user_id) + )).scalar_one_or_none() + + from .alerts import send_admin_alert + await send_admin_alert( + "💰 Top-up purchased", + f"{buyer_email or 'A user'} bought +{minutes} minutes.", + ) def _sub_item(sub_obj: dict): @@ -315,6 +325,12 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): # Detect the moment the user hits "cancel" (False -> True). was_canceling = bool(row.cancel_at_period_end) if row else False just_canceled = now_canceling and not was_canceling + # Purchase signals: brand-new subscription, and trial -> paid conversion. + is_new_sub = row is None + prev_status = row.status if row else None + buyer_email = (await s.execute( + select(User.email).where(User.id == user_id) + )).scalar_one_or_none() end_dt = _ts(end) values = dict( stripe_subscription_id=sub_obj["id"], @@ -332,6 +348,22 @@ async def _upsert_subscription(sub_obj: dict, event_created: datetime): for k, v in values.items(): setattr(row, k, v) + # Purchase alert: someone just subscribed (trial started or paid outright). + now_status = sub_obj["status"] + if is_new_sub: + from .alerts import send_admin_alert + label = "trial started — card on file" if now_status == "trialing" else now_status + await send_admin_alert( + "🎉 New subscriber", + f"{buyer_email or 'A user'} started the {plan} ({interval}) plan.\nStatus: {label}.", + ) + elif prev_status == "trialing" and now_status == "active": + from .alerts import send_admin_alert + await send_admin_alert( + "💳 Trial converted to paid", + f"{buyer_email or 'A user'} is now a paying {plan} ({interval}) subscriber. 🎉", + ) + # Churn alert to the admin the moment a subscription is set to cancel. if just_canceled: from .alerts import send_admin_alert diff --git a/cloud/config.py b/cloud/config.py index 12645f5..0e727b6 100644 --- a/cloud/config.py +++ b/cloud/config.py @@ -138,6 +138,19 @@ class Settings: # Where operational alerts (proxy out of credits, high failure rate) go. return os.environ.get("ADMIN_EMAIL", "") + # Telegram (optional) — real-time admin alerts (purchases, churn, outages) + @property + def telegram_bot_token(self) -> str: + return os.environ.get("TELEGRAM_BOT_TOKEN", "") + + @property + def telegram_chat_id(self) -> str: + return os.environ.get("TELEGRAM_CHAT_ID", "") + + @property + def telegram_configured(self) -> bool: + return bool(self.telegram_bot_token and self.telegram_chat_id) + # Google OAuth @property def google_client_id(self) -> str: