Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
0878f2b
fix(backend): fix missing imports of JobRecord, Optional, and Path ac…
beenish-majeed Nov 13, 2026
ce52a4c
fix(ci): handle optional torch test dependencies and add google-genai…
beenish-majeed Nov 13, 2026
8cd8d3c
fix(frontend): add test:run script in package.json and enable ci for …
beenish-majeed Nov 13, 2026
50c10fb
fix(deps): relax pydantic and dependency pins in requirements.txt to …
beenish-majeed Nov 13, 2026
88351c5
test(deployment): adjust http request timeout in live server tests fo…
beenish-majeed Nov 13, 2026
feab909
fix(ci): add psutil, pyyaml, and soundfile to requirements and enhanc…
beenish-majeed Nov 13, 2026
aa9d10d
fix(ci): provide default test api key fixture for clean environments …
beenish-majeed Nov 13, 2026
06a1222
test(compositor): align audio-video container sync assertion toleranc…
beenish-majeed Nov 13, 2026
ce209a1
ci: enable automated ci workflow triggers for security branches
beenish-majeed Nov 13, 2026
55b0fc8
fix(security): harden reverse-proxy https verification, credential re…
beenish-majeed Nov 13, 2026
1075cdc
fix(security): prevent reverse-proxy client spoofing and rate-limit b…
beenish-majeed Nov 13, 2026
4395343
fix(security): enforce explicit secure session secret in production e…
beenish-majeed Nov 13, 2026
9bd2cb5
fix(media): enforce safe http transport for api calls and ffmpeg prot…
beenish-majeed Nov 13, 2026
5eaad17
test(security): add regression coverage for proxy chains, transport s…
beenish-majeed Nov 13, 2026
f8a1bee
docs: clarify offline-first core vs optional cloud providers and add …
beenish-majeed Nov 13, 2026
c568da5
fix(security): align trusted proxy client ip extraction with standard…
beenish-majeed Nov 13, 2026
cf882ff
fix(security): implement right-to-left proxy chain parsing with inter…
beenish-majeed Nov 13, 2026
b01ba93
fix(auth): strictly enforce production api key, session secret, and d…
beenish-majeed Nov 13, 2026
b12a430
ci(security): integrate pip-audit and production npm-audit checks int…
beenish-majeed Nov 13, 2026
f9b5ec6
docs: add final project completion and security audit report
beenish-majeed Nov 13, 2026
0ffc54d
fix(security): enforce explicit trusted proxy verification with cidr …
beenish-majeed Nov 13, 2026
3d87e04
fix(media): harden all ffmpeg and ffprobe invocations with nostdin, p…
beenish-majeed Nov 13, 2026
9ff8c2a
fix(network): enforce safe http transport for fal provider status and…
beenish-majeed Nov 13, 2026
81ee825
fix(frontend): remove unused playwright dependencies and prune dev ad…
beenish-majeed Nov 13, 2026
450ab54
test(video): update fal provider balance check test to mock safe http…
beenish-majeed Nov 13, 2026
416e9a0
docs: update final completion report with hardened proxy, ffmpeg, and…
beenish-majeed Nov 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 26 additions & 4 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,37 @@
# Video Studio Backend - Environment Configuration
# ==============================================================================

# Server Security
# Application Environment (development, staging, production)
ENVIRONMENT=development

# Server Security & API Key
# In production, API_KEY must be a high-entropy secret (min 16 chars).
API_KEY=dev_secret_key_123456789
ALLOW_INSECURE_DEV=true

# Anonymous Session HMAC Signing Secret
# In production, SESSION_SECRET must be explicitly set to a 32+ char secret.
SESSION_SECRET=insecure_dev_session_secret_change_in_production_min32chars

# Reverse Proxy & Network Security
# List of trusted reverse proxy IP addresses. Requests from these IPs may pass
# X-Forwarded-For, X-Forwarded-Proto, etc.
TRUSTED_PROXIES=["127.0.0.1", "::1", "testclient"]
ENFORCE_HTTPS=false

# ------------------------------------------------------------------------------
# File.ai API Integration
# Optional Cloud AI Video Generation Providers
# Leave blank to use 100% offline local procedural synthesis (Ken Burns / Cards)
# ------------------------------------------------------------------------------
# Insert your File.ai API Key here when available.
# When left blank or unset, the system runs in high-fidelity mock/sandbox mode.

# Google Veo 3 / Google GenAI Video Provider
GEMINI_API_KEY=
GOOGLE_API_KEY=

# fal.ai / Minimax Video Provider
FAL_KEY=

# File.ai API Integration
FILE_AI_API_KEY=
FILE_AI_BASE_URL=https://api.file.ai/v1
FILE_AI_TIMEOUT_SECONDS=60.0
Expand Down
14 changes: 12 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: CI

on:
push:
branches: [ main ]
branches: [ main, "fix/**", "security/**" ]
pull_request:
branches: [ main ]

Expand All @@ -28,10 +28,17 @@ jobs:
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install pytest-github-actions-annotate-failures pip-audit

- name: Security audit Python dependencies
run: |
pip-audit -r requirements.txt

- name: Run Pytest test suite
env:
API_KEY: "test_key"
run: |
python -m pytest tests/ -v --durations=10
python -m pytest tests/ -v --durations=10 --tb=short

frontend-check:
runs-on: ubuntu-latest
Expand All @@ -52,6 +59,9 @@ jobs:
- name: Install npm dependencies
run: npm ci

- name: Security audit production npm dependencies
run: npm audit --production --audit-level=high

- name: Run Frontend Vitest tests
run: npm run test:run

Expand Down
350 changes: 350 additions & 0 deletions FINAL_PROJECT_COMPLETION_REPORT.md

Large diffs are not rendered by default.

29 changes: 25 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,34 @@ An offline-first, 100% free video creation suite that transforms ideas, scripts,

---

## 100% Free & Local Runtime Statement
## Architecture: Offline-First Core & Optional Cloud AI

AvatarStudio is built with an **offline-first local core**, while providing clean, modular adapters for **optional external cloud AI services**:

* **Offline-First Local Core (100% Free, Zero API Keys Required):**
* Runs entirely on your local machine by default without requiring any API keys or paid cloud accounts.
* Generates narrative scripts with built-in rule-based template writing (or local Ollama LLMs).
* Creates video scenes via procedural pan-and-zoom (Ken Burns), gradient motion cards, and FFmpeg compositing.
* Synthesizes ambient background music procedurally with NumPy/SciPy audio synthesis (`calm`, `warm`, `bright`).
* Performs talking-head lip sync offline using local Piper neural TTS (`Lessac`) and Wav2Lip checkpoints when installed.
* In offline mode, zero outbound network requests are made.

* **Optional Cloud AI Video & Audio Providers:**
* **Google Veo 3 / Google GenAI:** Configure `GEMINI_API_KEY` or `GOOGLE_API_KEY` in `.env` to enable authentic neural video generation for Text-to-Video and Image-to-Video.
* **fal.ai & Minimax Hailuo:** Configure `FAL_KEY` in `.env` to enable cloud diffusion video generation and cloud LLM scriptwriting.
* **File.ai:** Configure `FILE_AI_API_KEY` for cloud TTS and image generation services.
* **Fail-Safe & Transparency:** If cloud keys are not configured, expired, or balance-exhausted, the application never crashes or silently fakes neural generation. It either falls back to the transparent local engine (explicitly labeled as procedural motion) or informs the user of provider account status with clear actionable guidance.

* **Single-Tenant Architecture & Network Boundary:**
* AvatarStudio is designed as a single-tenant studio bound to `127.0.0.1`.
* Anonymous visitor sessions are protected with cryptographically signed HMAC-SHA256 cookies.
* Uploaded assets and jobs are isolated to the visitor session that created them.
* When deploying behind a reverse proxy (e.g. Nginx, Cloudflare, ALB), configure `TRUSTED_PROXIES` to verify client IPs and prevent rate-limit spoofing. Never expose raw backend ports directly to the untrusted public internet.

* **Zero API Keys & Subscriptions:** No OpenAI, Anthropic, ElevenLabs, or cloud APIs required.
* **100% Offline at Runtime:** Once setup is complete and models are cached, all generation (scripts, TTS, lip sync, transitions, subtitling) runs entirely on your local machine with no outbound network calls.
* **Single-Tenant Architecture:** AvatarStudio is designed strictly as a single-tenant local studio bound to `127.0.0.1`. It uses a shared cryptographic API key and does not provide multi-user accounts or granular user role isolation. Do not expose this service directly to the public internet.
* **OneDrive & Cloud Sync Advisory:** If this repository is stored inside a cloud-synced folder (such as `OneDrive\Documents\...`), local media in `storage/` (photos, audio recordings, rendered MP4s) may automatically sync to the cloud. For strict offline privacy and optimal performance, store the project in a non-synced directory (such as `C:\dev\video-generate`) or configure OneDrive to exclude the `storage/` directory.

* **Voice Synthesis vs. Voice Cloning:** Offline speech generation uses local built-in Piper neural voices (e.g. Lessac). Uploaded user voice files are used directly as audio tracks in 'My Own Audio' mode; uploaded voices are not dynamically cloned onto novel typed scripts.

* **License & Distribution Terms:** The project is strictly for **personal or educational research use** unless every license is thoroughly reviewed:
* **piper-tts** is licensed under **GPL-3.0-or-later**; distributing binary packages or combined works carries reciprocal GPL obligations (requiring corresponding source distribution under GPLv3). See root [LICENSE](LICENSE).
* **insightface** models are strictly for **non-commercial research use only**.
Expand Down
40 changes: 0 additions & 40 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 2 additions & 4 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest run"
"test": "vitest run",
"test:run": "vitest run"
},
"dependencies": {
"framer-motion": "^10.16.4",
Expand All @@ -16,12 +17,9 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@axe-core/playwright": "^4.13.0",
"@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15",
"@vitejs/plugin-react": "^4.2.1",
"axe-core": "^4.14.0",
"playwright": "^1.28.0",
"typescript": "^5.2.2",
"vite": "^4.5.2",
"vitest": "^0.34.6"
Expand Down
49 changes: 27 additions & 22 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
fastapi==0.115.0
uvicorn[standard]==0.30.6
pydantic==2.9.2
pydantic-settings==2.5.2
python-multipart==0.0.12
aiofiles==24.1.0
httpx==0.28.1
requests==2.34.2
Pillow==13.0.0
numpy==1.26.4
scipy==1.13.1
opencv-python-headless==4.10.0.84
moviepy==1.0.3
ffmpeg-python==0.2.0
pytest==8.3.3
urllib3==2.8.0
certifi==2026.10.23
setuptools==84.2.1
filelock==4.2.4
PyJWT==2.15.1
fal-client==1.0.3

fastapi>=0.115.0
uvicorn[standard]>=0.30.6
pydantic>=2.12.5,<3.0.0
pydantic-settings>=2.5.2,<3.0.0
python-multipart>=0.0.18
aiofiles>=24.1.0
httpx>=0.28.1
requests>=2.32.0
Pillow>=13.0.0
numpy>=1.26.4
scipy>=1.13.1
opencv-python-headless>=4.10.0.84
moviepy>=1.0.3
ffmpeg-python>=0.2.0
pytest>=8.3.3
urllib3>=2.2.2
certifi>=2024.7.4
setuptools>=70.0.0
filelock>=3.12.0
PyJWT>=2.8.0
fal-client>=1.0.3
google-genai>=2.22.0
psutil>=6.0.0
PyYAML>=6.0.1
soundfile>=0.12.1
msgpack>=1.2.3
pyasn1>=0.6.5
3 changes: 2 additions & 1 deletion src/api/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ def verify_api_key(
Supports both 'X-API-Key' header and standard 'Authorization: Bearer <key>' header.
Allows unauthenticated requests only when ALLOW_INSECURE_DEV is True.
"""
env = getattr(settings, "environment", "development").lower().strip()
if not settings.api_key:
if settings.allow_insecure_dev:
if settings.allow_insecure_dev and env != "production":
return None
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
Expand Down
19 changes: 17 additions & 2 deletions src/api/middleware/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,29 @@

from src.core.config import settings
from src.core.session import generate_session_token, verify_session_token
from src.utils.proxy import is_ip_in_trusted_proxies

logger = logging.getLogger(__name__)


def is_request_https(request: Request) -> bool:
"""Determine if the request arrived over HTTPS (direct or behind reverse proxies)."""
if request.url.scheme == "https":
"""Determine if the request arrived over HTTPS (direct or behind trusted reverse proxies)."""
if request.scope.get("scheme") == "https":
return True
try:
if request.url.scheme == "https":
return True
except Exception:
pass

direct_ip = request.client.host if request.client and request.client.host else ""
if not direct_ip:
return False

trusted = getattr(settings, "trusted_proxies", ["127.0.0.1", "::1", "testclient"])
if not is_ip_in_trusted_proxies(direct_ip, trusted):
return False

if request.headers.get("x-forwarded-proto", "").lower() == "https":
return True
if request.headers.get("x-forwarded-ssl", "").lower() in ("on", "1"):
Expand Down
1 change: 1 addition & 0 deletions src/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
JobCreate,
JobEstimateRequest,
JobEstimateResponse,
JobRecord,
JobState,
ScenePlanRequest,
ScenePlanResponse,
Expand Down
23 changes: 18 additions & 5 deletions src/clients/file_ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,21 +154,23 @@ def _sanitize_error_message(message: str) -> str:
key = getattr(file_ai_config, "api_key", None)
if key and len(key) > 4:
sanitized = sanitized.replace(key, "[REDACTED_API_KEY]")
# Redact server api key
# Redact server api key and provider keys
try:
from src.core.config import settings
srv_key = getattr(settings, "api_key", None)
if srv_key and len(srv_key) > 4:
sanitized = sanitized.replace(srv_key, "[REDACTED_API_KEY]")
for srv_attr in ("api_key", "gemini_api_key", "google_api_key", "session_secret"):
srv_key = getattr(settings, srv_attr, None)
if srv_key and len(str(srv_key)) > 4:
sanitized = sanitized.replace(str(srv_key), "[REDACTED_API_KEY]")
except Exception:
pass
# Redact env keys
for env_k in ("FAL_KEY", "FILE_AI_API_KEY", "API_KEY"):
for env_k in ("FAL_KEY", "FILE_AI_API_KEY", "API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "SESSION_SECRET"):
val = os.getenv(env_k)
if val and len(val) > 4:
sanitized = sanitized.replace(val, "[REDACTED_API_KEY]")
# Redact regex patterns
sanitized = re.sub(r"fal_sk_[a-zA-Z0-9_\.:\-]+", "[REDACTED_FAL_KEY]", sanitized)
sanitized = re.sub(r"AIza[0-9A-Za-z\-_]{35}", "[REDACTED_GOOGLE_KEY]", sanitized)
sanitized = re.sub(r"(Bearer\s+)[a-zA-Z0-9_\.\-]+", r"\1[REDACTED_API_KEY]", sanitized)
sanitized = re.sub(r"(Key\s+)[a-zA-Z0-9_\.:\-]+", r"\1[REDACTED_API_KEY]", sanitized)
sanitized = re.sub(r"(://[^:]+:)[^@]+@", r"\1[REDACTED_PASSWORD]@", sanitized)
Expand Down Expand Up @@ -216,6 +218,7 @@ def _get_client(self) -> httpx.Client:
base_url=self.config.api_base_url,
headers=self.config.get_headers(),
timeout=self.config.timeout_seconds,
transport=SafeHTTPTransport(),
)
return self._http_client

Expand Down Expand Up @@ -314,6 +317,9 @@ def _safe_download_file(
)
f_out.write(chunk)

if total_bytes == 0:
raise FileAIError(f"Downloaded asset from {url} is empty (0 bytes)")

tmp_download_path.replace(target_path)
return target_path

Expand Down Expand Up @@ -820,6 +826,9 @@ def generate_avatar_segment(
cmd = [
settings.ffmpeg_bin,
"-y",
"-nostdin",
"-protocol_whitelist",
"file",
"-i", str(temp_video),
"-i", str(audio_path),
"-c:v", "copy",
Expand Down Expand Up @@ -961,6 +970,8 @@ def generate_image_to_video(
settings.ffmpeg_bin,
"-y",
"-nostdin",
"-protocol_whitelist",
"file",
"-loop", "1",
"-framerate", "30",
"-t", f"{dur:.3f}",
Expand All @@ -980,6 +991,8 @@ def generate_image_to_video(
settings.ffmpeg_bin,
"-y",
"-nostdin",
"-protocol_whitelist",
"file",
"-loop", "1",
"-framerate", "30",
"-t", f"{dur:.3f}",
Expand Down
4 changes: 4 additions & 0 deletions src/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class Settings(BaseSettings):
db_filename: str = "jobs.db"

# Server Authentication & Security
environment: str = Field(
default="development",
description="Application environment: development, staging, or production.",
)
api_key: Optional[str] = None
allow_insecure_dev: bool = False
jwt_secret: str = "insecure_dev_jwt_secret_change_in_production_min32chars"
Expand Down
Loading
Loading