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.
This commit is contained in:
juancarlos.cavero 2026-07-16 17:30:12 +02:00
parent c0ad5e0de8
commit 6ec6935532
11 changed files with 278 additions and 52 deletions

View file

@ -2,6 +2,10 @@ MIT License
Copyright (c) 2024 OpenShorts 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 Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights

View file

@ -294,4 +294,6 @@ Contributions are welcome! Whether it's adding new AI models, improving the lip-
## License ## 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.

186
app.py
View file

@ -202,6 +202,34 @@ async def require_managed_entitlement(request):
raise gemini_missing_error() raise gemini_missing_error()
return user 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 # Application State
# PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first: # PriorityQueue holds (priority, seq, job_id). Lower priority dispatches first:
# pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps # pro=0, starter/creator=1, BYOK/anonymous/self-host=2. The seq counter keeps
@ -632,8 +660,11 @@ async def process_endpoint(
if url: if url:
cmd.extend(["-u", url]) cmd.extend(["-u", url])
else: else:
# Save uploaded file with size limit check # Save uploaded file with size limit check.
input_path = os.path.join(UPLOAD_DIR, f"{job_id}_{file.filename}") # 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 # Read file in chunks to check size
size = 0 size = 0
@ -674,11 +705,12 @@ async def process_endpoint(
return {"job_id": job_id, "status": "queued"} return {"job_id": job_id, "status": "queued"}
@app.get("/api/status/{job_id}") @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: if job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
job = jobs[job_id] job = jobs[job_id]
await _assert_job_owner(request, job)
return { return {
"status": job['status'], "status": job['status'],
"logs": job['logs'], "logs": job['logs'],
@ -702,8 +734,11 @@ async def edit_clip(
req: EditRequest, req: EditRequest,
request: Request, request: Request,
): ):
# BYOK body key wins; otherwise resolve header / managed / self-host env. # Cloud (paid) mode disables BYOK: ignore any body api_key so it can't skip
final_api_key = req.api_key or await resolve_gemini(request) # 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: if not final_api_key:
raise gemini_missing_error() raise gemini_missing_error()
@ -712,13 +747,14 @@ async def edit_clip(
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
job = jobs[req.job_id] job = jobs[req.job_id]
await _assert_job_owner(request, job)
if 'result' not in job or 'clips' not in job['result']: if 'result' not in job or 'clips' not in job['result']:
raise HTTPException(status_code=400, detail="Job result not available") 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 # Meter the managed Gemini call so it can't be looped for free. Skip only for
# caller supplied their own key (BYOK body) or self-host (reserve is a no-op). # 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 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") request, edit_minutes, req.job_id, "edit")
try: try:
@ -845,11 +881,12 @@ class SubtitleRequest(BaseModel):
@app.get("/api/clip/{job_id}/{clip_index}/transcript") @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.""" """Return word-level captions for a specific clip, formatted for Remotion."""
if job_id not in jobs: if job_id not in jobs:
raise HTTPException(status_code=404, detail="Job not found") 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) output_dir = os.path.join(OUTPUT_DIR, job_id)
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) 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) await require_managed_entitlement(request)
import httpx import httpx
body = await request.json() 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: try:
async with httpx.AsyncClient(timeout=30.0) as client: async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(f"{RENDER_SERVICE_URL}/render", json=body) 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: except Exception as e:
if reservation_id:
await _metering.release_reservation(reservation_id)
raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}") raise HTTPException(status_code=502, detail=f"Render service unavailable: {e}")
@app.get("/api/render/{render_id}") @app.get("/api/render/{render_id}")
@ -939,6 +984,7 @@ async def generate_effects_config(
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
job = jobs[req.job_id] job = jobs[req.job_id]
await _assert_job_owner(request, job)
if 'result' not in job or 'clips' not in job['result']: if 'result' not in job or 'clips' not in job['result']:
raise HTTPException(status_code=400, detail="Job result not available") raise HTTPException(status_code=400, detail="Job result not available")
@ -1047,6 +1093,7 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
# Reload job data from disk just in case metadata was updated # Reload job data from disk just in case metadata was updated
job = jobs[req.job_id] job = jobs[req.job_id]
await _assert_job_owner(request, job)
# We need to access metadata.json to get the transcript # We need to access metadata.json to get the transcript
output_dir = os.path.join(OUTPUT_DIR, req.job_id) output_dir = os.path.join(OUTPUT_DIR, req.job_id)
@ -1094,6 +1141,12 @@ async def add_subtitles(req: SubtitleRequest, request: Request):
output_filename = f"subtitled_{filename}" output_filename = f"subtitled_{filename}"
output_path = os.path.join(output_dir, output_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: try:
# 1. Generate SRT # 1. Generate SRT
# Check if this is a dubbed video - if so, transcribe it fresh # 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: except Exception as e:
print(f"❌ Subtitle Error: {e}") print(f"❌ Subtitle Error: {e}")
if reservation_id:
await _metering.release_reservation(reservation_id)
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
if reservation_id:
await _metering.commit_reservation(reservation_id)
# 3. Update Result and Metadata # 3. Update Result and Metadata
# Update InMemory Jobs # Update InMemory Jobs
if req.clip_index < len(job['result']['clips']): if req.clip_index < len(job['result']['clips']):
@ -1168,6 +1226,7 @@ async def add_hook(req: HookRequest, request: Request):
raise HTTPException(status_code=404, detail="Job not found") raise HTTPException(status_code=404, detail="Job not found")
job = jobs[req.job_id] job = jobs[req.job_id]
await _assert_job_owner(request, job)
output_dir = os.path.join(OUTPUT_DIR, req.job_id) output_dir = os.path.join(OUTPUT_DIR, req.job_id)
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) json_files = glob.glob(os.path.join(output_dir, "*_metadata.json"))
@ -1204,6 +1263,11 @@ async def add_hook(req: HookRequest, request: Request):
size_map = {"S": 0.8, "M": 1.0, "L": 1.3} size_map = {"S": 0.8, "M": 1.0, "L": 1.3}
font_scale = size_map.get(req.size, 1.0) 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: try:
# Run in thread pool # Run in thread pool
def run_hook(): def run_hook():
@ -1214,8 +1278,13 @@ async def add_hook(req: HookRequest, request: Request):
except Exception as e: except Exception as e:
print(f"❌ Hook Error: {e}") print(f"❌ Hook Error: {e}")
if reservation_id:
await _metering.release_reservation(reservation_id)
raise HTTPException(status_code=500, detail=str(e)) raise HTTPException(status_code=500, detail=str(e))
if reservation_id:
await _metering.commit_reservation(reservation_id)
# Update Persistence (Same logic as subtitles) # Update Persistence (Same logic as subtitles)
# Update InMemory Jobs # Update InMemory Jobs
if req.clip_index < len(job['result']['clips']): if req.clip_index < len(job['result']['clips']):
@ -1252,6 +1321,7 @@ async def get_languages():
@app.post("/api/translate") @app.post("/api/translate")
async def translate_clip( async def translate_clip(
req: TranslateRequest, req: TranslateRequest,
request: Request,
x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key") x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-Key")
): ):
"""Translate a video clip to a different language using ElevenLabs dubbing.""" """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") raise HTTPException(status_code=404, detail="Job not found")
job = jobs[req.job_id] job = jobs[req.job_id]
await _assert_job_owner(request, job)
output_dir = os.path.join(OUTPUT_DIR, req.job_id) output_dir = os.path.join(OUTPUT_DIR, req.job_id)
json_files = glob.glob(os.path.join(output_dir, "*_metadata.json")) 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") raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
job = jobs[req.job_id] job = jobs[req.job_id]
await _assert_job_owner(request, job)
if 'result' not in job or 'clips' not in job['result']: if 'result' not in job or 'clips' not in job['result']:
raise HTTPException(status_code=400, detail="Job result not available") raise HTTPException(status_code=400, detail="Job result not available")
@ -1521,16 +1593,31 @@ async def thumbnail_upload(
session_id = str(uuid.uuid4()) session_id = str(uuid.uuid4())
transcript_event = asyncio.Event() 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 video_path = None
if file: 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: with open(video_path, "wb") as buffer:
content = await file.read() while chunk := await file.read(1024 * 1024):
buffer.write(content) 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 # Initialize session
thumbnail_sessions[session_id] = { thumbnail_sessions[session_id] = {
"user_id": await _owner_id(request),
"video_path": video_path, "video_path": video_path,
"transcript_event": transcript_event, "transcript_event": transcript_event,
"transcript_ready": False, "transcript_ready": False,
@ -1568,9 +1655,13 @@ async def thumbnail_upload(
"language": transcript.get("language", "en"), "language": transcript.get("language", "en"),
}) })
print(f"✅ [Thumbnail] Background Whisper complete for session {session_id}") print(f"✅ [Thumbnail] Background Whisper complete for session {session_id}")
if reservation_id:
await _metering.commit_reservation(reservation_id)
except Exception as e: except Exception as e:
print(f"❌ [Thumbnail] Background Whisper failed: {e}") print(f"❌ [Thumbnail] Background Whisper failed: {e}")
thumbnail_sessions[session_id]["transcript_error"] = str(e) thumbnail_sessions[session_id]["transcript_error"] = str(e)
if reservation_id:
await _metering.release_reservation(reservation_id)
finally: finally:
transcript_event.set() transcript_event.set()
@ -1597,6 +1688,7 @@ async def thumbnail_analyze(
# Check for pre-existing session with background Whisper # Check for pre-existing session with background Whisper
if session_id and session_id in thumbnail_sessions: if session_id and session_id in thumbnail_sessions:
session = thumbnail_sessions[session_id] session = thumbnail_sessions[session_id]
await _assert_job_owner(request, session)
# Wait for background Whisper to complete # Wait for background Whisper to complete
transcript_event = session.get("transcript_event") transcript_event = session.get("transcript_event")
@ -1624,10 +1716,17 @@ async def thumbnail_analyze(
from main import download_youtube_video from main import download_youtube_video
video_path, _ = download_youtube_video(url, UPLOAD_DIR) video_path, _ = download_youtube_video(url, UPLOAD_DIR)
else: 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: with open(video_path, "wb") as buffer:
content = await file.read() while chunk := await file.read(1024 * 1024):
buffer.write(content) 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). # Meter the managed Gemini analysis (no-op for self-host).
analyze_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0 analyze_minutes = _cloud_config.MANAGED_ANALYSIS_MINUTES if BILLING_ENABLED else 0
@ -1640,7 +1739,7 @@ async def thumbnail_analyze(
# Store/update session context # Store/update session context
if session_id not in thumbnail_sessions: 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({ thumbnail_sessions[session_id].update({
"context": result.get("transcript_summary", ""), "context": result.get("transcript_summary", ""),
@ -1689,11 +1788,14 @@ async def thumbnail_titles(
session_id = req.session_id or str(uuid.uuid4()) session_id = req.session_id or str(uuid.uuid4())
if session_id not in thumbnail_sessions: if session_id not in thumbnail_sessions:
thumbnail_sessions[session_id] = { thumbnail_sessions[session_id] = {
"user_id": await _owner_id(request),
"context": "", "context": "",
"titles": [req.title], "titles": [req.title],
"language": "en", "language": "en",
"conversation": [] "conversation": []
} }
else:
await _assert_job_owner(request, thumbnail_sessions[session_id])
return {"session_id": session_id, "titles": [req.title]} return {"session_id": session_id, "titles": [req.title]}
# Refinement mode # Refinement mode
@ -1704,6 +1806,7 @@ async def thumbnail_titles(
raise HTTPException(status_code=400, detail="Must provide message or title") raise HTTPException(status_code=400, detail="Must provide message or title")
session = thumbnail_sessions[req.session_id] session = thumbnail_sessions[req.session_id]
await _assert_job_owner(request, session)
# Add user message to conversation history # Add user message to conversation history
session["conversation"].append({"role": "user", "content": req.message}) 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 thumb_minutes = _cloud_config.THUMBNAIL_MINUTES if BILLING_ENABLED else 0
reservation_id = await reserve_managed_action(request, thumb_minutes, session_id, "thumbnail") 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 face_path = None
bg_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) os.makedirs(thumb_upload_dir, exist_ok=True)
try: try:
if face and face.filename: 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: with open(face_path, "wb") as f:
f.write(await face.read()) f.write(await face.read())
if background and background.filename: 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: with open(bg_path, "wb") as f:
f.write(await background.read()) f.write(await background.read())
@ -1827,6 +1934,7 @@ async def thumbnail_describe(
raise HTTPException(status_code=404, detail="Session not found") raise HTTPException(status_code=404, detail="Session not found")
session = thumbnail_sessions[req.session_id] session = thumbnail_sessions[req.session_id]
await _assert_job_owner(request, session)
segments = session.get("transcript_segments", []) segments = session.get("transcript_segments", [])
if not segments: if not segments:
raise HTTPException(status_code=400, detail="No transcript segments available. Please analyze a video first.") 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") raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
session = thumbnail_sessions[session_id] session = thumbnail_sessions[session_id]
await _assert_job_owner(request, session)
video_path = session.get("video_path") video_path = session.get("video_path")
if not video_path or not os.path.exists(video_path): if not video_path or not os.path.exists(video_path):
raise HTTPException(status_code=404, detail="Original video file not found") raise HTTPException(status_code=404, detail="Original video file not found")
@ -2076,13 +2185,21 @@ class SaaSActorRequest(BaseModel):
@app.post("/api/saasshorts/actor-upload") @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).""" """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/"): if not file.content_type or not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image") raise HTTPException(status_code=400, detail="File must be an image")
try: 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 # Validate minimum size
if len(content) < 1000: if len(content) < 1000:
@ -2108,9 +2225,11 @@ async def saasshorts_actor_upload(file: UploadFile = File(...)):
@app.post("/api/saasshorts/actor-options") @app.post("/api/saasshorts/actor-options")
async def saasshorts_actor_options( async def saasshorts_actor_options(
req: SaaSActorRequest, req: SaaSActorRequest,
request: Request,
x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"), x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"),
): ):
"""Generate multiple actor image options for the user to choose from.""" """Generate multiple actor image options for the user to choose from."""
await require_managed_entitlement(request)
fal_key = x_fal_key fal_key = x_fal_key
if not fal_key: if not fal_key:
raise HTTPException(status_code=400, detail="Missing fal.ai API 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") raise HTTPException(status_code=400, detail="Missing Upload-Post user profile")
job = saas_jobs[req.job_id] job = saas_jobs[req.job_id]
await _assert_job_owner(request, job)
result = job.get("result") result = job.get("result")
if not result or not result.get("video_url"): if not result or not result.get("video_url"):
raise HTTPException(status_code=400, detail="No video available for this job") raise HTTPException(status_code=400, detail="No video available for this job")
@ -2428,10 +2548,12 @@ class SaaSGenerateRequest(BaseModel):
@app.post("/api/saasshorts/generate") @app.post("/api/saasshorts/generate")
async def saasshorts_generate( async def saasshorts_generate(
req: SaaSGenerateRequest, req: SaaSGenerateRequest,
request: Request,
x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"), x_fal_key: Optional[str] = Header(None, alias="X-Fal-Key"),
x_elevenlabs_key: Optional[str] = Header(None, alias="X-ElevenLabs-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.""" """Generate a SaaS UGC video from a script. Returns a job_id for polling."""
await require_managed_entitlement(request)
fal_key = x_fal_key fal_key = x_fal_key
elevenlabs_key = x_elevenlabs_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 # Support retry: reuse output_dir so cached assets (image, voice, head, broll) are kept
reused = False reused = False
if req.retry_job_id: if req.retry_job_id:
# Check memory first, then disk # Check memory first, then disk. _safe_under() blocks a crafted
old_dir = os.path.join(OUTPUT_DIR, f"saas_{req.retry_job_id}") # 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: 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"] 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_id = req.retry_job_id
job_output_dir = old_dir job_output_dir = old_dir
reused = True reused = True
@ -2458,6 +2585,7 @@ async def saasshorts_generate(
if f.endswith("_final.mp4") and os.path.getsize(fp) == 0: if f.endswith("_final.mp4") and os.path.getsize(fp) == 0:
os.remove(fp) os.remove(fp)
saas_jobs[job_id] = { saas_jobs[job_id] = {
"user_id": await _owner_id(request),
"status": "processing", "status": "processing",
"logs": [f"Retrying job {job_id[:8]}... reusing cached assets from disk."], "logs": [f"Retrying job {job_id[:8]}... reusing cached assets from disk."],
"result": None, "result": None,
@ -2469,6 +2597,7 @@ async def saasshorts_generate(
job_output_dir = os.path.join(OUTPUT_DIR, f"saas_{job_id}") job_output_dir = os.path.join(OUTPUT_DIR, f"saas_{job_id}")
os.makedirs(job_output_dir, exist_ok=True) os.makedirs(job_output_dir, exist_ok=True)
saas_jobs[job_id] = { saas_jobs[job_id] = {
"user_id": await _owner_id(request),
"status": "processing", "status": "processing",
"logs": ["SaaSShorts job started."], "logs": ["SaaSShorts job started."],
"result": None, "result": None,
@ -2580,12 +2709,13 @@ async def saasshorts_generate(
@app.get("/api/saasshorts/status/{job_id}") @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.""" """Poll SaaSShorts job status."""
if job_id not in saas_jobs: if job_id not in saas_jobs:
raise HTTPException(status_code=404, detail="SaaSShorts job not found") raise HTTPException(status_code=404, detail="SaaSShorts job not found")
job = saas_jobs[job_id] job = saas_jobs[job_id]
await _assert_job_owner(request, job)
return { return {
"status": job["status"], "status": job["status"],
"logs": job["logs"], "logs": job["logs"],

66
cloud/LICENSE Normal file
View file

@ -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.

View file

@ -49,6 +49,18 @@ THUMBNAIL_MINUTES = 3
# burn the operator's managed Gemini budget. Pure-text calls (titles/desc) stay free. # burn the operator's managed Gemini budget. Pure-text calls (titles/desc) stay free.
MANAGED_ANALYSIS_MINUTES = 1 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 # 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). # IDs need to be copied into env vars (they differ between test and live anyway).
SUBSCRIPTION_LOOKUP_KEYS = [ SUBSCRIPTION_LOOKUP_KEYS = [

View file

@ -138,7 +138,7 @@ const SESSION_MAX_AGE = 3600000; // 1 hour (matches server job retention)
// Mock polling function // Mock polling function
const pollJob = async (jobId) => { 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'); if (!res.ok) throw new Error('Status check failed');
return res.json(); return res.json();
}; };

View file

@ -43,7 +43,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
// Fetch clip duration from transcript endpoint // Fetch clip duration from transcript endpoint
useEffect(() => { useEffect(() => {
if (!jobId || index === undefined) return; 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(res => res.ok ? res.json() : null)
.then(data => { .then(data => {
if (data && data.durationSec) setClipDuration(data.durationSec); 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 // Try Remotion effects endpoint first
const effectsRes = await fetch(getApiUrl('/api/effects/generate'), { const effectsRes = await apiFetch('/api/effects/generate', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -105,7 +105,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
} }
// Fallback: legacy FFmpeg edit endpoint // Fallback: legacy FFmpeg edit endpoint
const res = await fetch(getApiUrl('/api/edit'), { const res = await apiFetch('/api/edit', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', '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] Request body:', requestBody);
console.log('[Translate] Sending request to /api/translate'); console.log('[Translate] Sending request to /api/translate');
const res = await fetch(getApiUrl('/api/translate'), { const res = await apiFetch('/api/translate', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -354,7 +354,7 @@ export default function ResultCard({ clip, index, jobId, uploadPostKey, uploadUs
payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone; payload.timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
} }
const res = await fetch(getApiUrl('/api/social/post'), { const res = await apiFetch('/api/social/post', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload) body: JSON.stringify(payload)

View file

@ -144,7 +144,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
if (jobId && genStatus === 'processing') { if (jobId && genStatus === 'processing') {
interval = setInterval(async () => { interval = setInterval(async () => {
try { try {
const res = await fetch(getApiUrl(`/api/saasshorts/status/${jobId}`)); const res = await apiFetch(`/api/saasshorts/status/${jobId}`);
if (res.status === 404) { if (res.status === 404) {
// Job lost (server restart) — treat as failed so Retry appears // Job lost (server restart) — treat as failed so Retry appears
setGenStatus('failed'); setGenStatus('failed');
@ -1015,7 +1015,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
try { try {
const res = await fetch(getApiUrl('/api/saasshorts/actor-upload'), { const res = await apiFetch('/api/saasshorts/actor-upload', {
method: 'POST', method: 'POST',
body: formData, body: formData,
}); });
@ -1078,7 +1078,7 @@ export default function SaaShortsTab({ geminiApiKey, elevenLabsKey, falKey, uplo
setActorOptions([]); setActorOptions([]);
setSelectedActor(null); setSelectedActor(null);
try { try {
const res = await fetch(getApiUrl('/api/saasshorts/actor-options'), { const res = await apiFetch('/api/saasshorts/actor-options', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Fal-Key': falKey }, headers: { 'Content-Type': 'application/json', 'X-Fal-Key': falKey },
body: JSON.stringify({ actor_description: actorDescription, num_options: 3 }), body: JSON.stringify({ actor_description: actorDescription, num_options: 3 }),

View file

@ -1,6 +1,7 @@
import React, { useState, useMemo } from 'react'; import React, { useState, useMemo } from 'react';
import { X, Loader2, Calendar, Clock, CheckCircle, AlertCircle, Video, Instagram, Youtube, ChevronLeft, ChevronRight, Globe, ExternalLink } from 'lucide-react'; import { X, Loader2, Calendar, Clock, CheckCircle, AlertCircle, Video, Instagram, Youtube, ChevronLeft, ChevronRight, Globe, ExternalLink } from 'lucide-react';
import { getApiUrl } from '../config'; import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
const DAYS = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb']; const DAYS = ['Dom', 'Lun', 'Mar', 'Mié', 'Jue', 'Vie', 'Sáb'];
const MONTHS = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']; 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 { try {
const res = await fetch(getApiUrl('/api/social/post'), { const res = await apiFetch('/api/social/post', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload) body: JSON.stringify(payload)

View file

@ -1,6 +1,7 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { X, Type, Loader2 } from 'lucide-react'; import { X, Type, Loader2 } from 'lucide-react';
import { getApiUrl } from '../config'; import { getApiUrl } from '../config';
import { apiFetch } from '../lib/api';
import RemotionPreview from './RemotionPreview'; import RemotionPreview from './RemotionPreview';
const FONT_OPTIONS = [ const FONT_OPTIONS = [
@ -54,7 +55,7 @@ export default function SubtitleModal({ isOpen, onClose, onGenerate, isProcessin
if (!isOpen || !jobId || clipIndex === undefined) return; if (!isOpen || !jobId || clipIndex === undefined) return;
setCaptionsLoading(true); setCaptionsLoading(true);
fetch(getApiUrl(`/api/clip/${jobId}/${clipIndex}/transcript`)) apiFetch(`/api/clip/${jobId}/${clipIndex}/transcript`)
.then((res) => res.ok ? res.json() : null) .then((res) => res.ok ? res.json() : null)
.then((data) => { .then((data) => {
if (data && data.captions && data.captions.length > 0) { if (data && data.captions && data.captions.length > 0) {

View file

@ -221,9 +221,19 @@ def scrape_website(url: str) -> dict:
for sub_url in list(subpages)[:3]: for sub_url in list(subpages)[:3]:
try: try:
print(f"[SaaSShorts] → Subpage: {sub_url}") print(f"[SaaSShorts] → Subpage: {sub_url}")
with httpx.Client(timeout=20.0, follow_redirects=True) as client: # Same SSRF guard as the main page: no auto-redirects and re-validate
resp = client.get(sub_url, headers=headers) # every hop, so a same-host page can't 30x-bounce us onto an internal
if resp.status_code == 200: # 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") sub_soup = BeautifulSoup(resp.text, "html.parser")
for tag in sub_soup(["script", "style", "nav", "footer", "header", "noscript"]): for tag in sub_soup(["script", "style", "nav", "footer", "header", "noscript"]):
tag.decompose() tag.decompose()