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()