Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
21 changes: 19 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ Interactive docs open at **`http://127.0.0.1:8001/docs`**
```bash
curl -X POST http://127.0.0.1:8001/api/v1/image \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-flow-..." \
-d '{"prompt": "neon cyber dragon over misty mountains", "aspect": "16:9"}'
```

Expand All @@ -184,6 +185,22 @@ curl -X POST http://127.0.0.1:8001/api/v1/image \
}
```

### 🔒 API Key Authentication

Protect your server when exposing it publicly (e.g. via Cloudflare Tunnel or reverse proxy):

```bash
# Generate a new API key
python main.py key create --name "my-laptop"
# → key: sk-flow-JNhS...Wxyz

# List, revoke, or delete keys
python main.py key list
python main.py key revoke "my-laptop"
```

Once a key is created, all protected endpoints enforce authentication via `Authorization: Bearer <key>` or `X-API-Key: <key>`. Setting the `FLOW_API_KEY` environment variable also acts as a master key.

---

## OpenAI SDK — Drop-in Replacement
Expand All @@ -193,8 +210,8 @@ Change **one line** in your existing OpenAI code:
```python
from openai import OpenAI

# ← Change only this line
client = OpenAI(base_url="http://127.0.0.1:8001/v1", api_key="not-needed")
# ← Change only this line (use api_key="not-needed" if authentication is unconfigured)
client = OpenAI(base_url="http://127.0.0.1:8001/v1", api_key="your-sk-flow-key")

# Everything else stays exactly the same ↓
response = client.images.generate(
Expand Down
51 changes: 43 additions & 8 deletions docs/API_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@ All endpoints assume the server is running at its default address.
## Table of Contents

1. [Endpoints Overview](#1-endpoints-overview)
2. [Native Flow Endpoints (`/api/v1/*`)](#2-native-flow-endpoints)
3. [OpenAI-Compatible Endpoints (`/v1/*`)](#3-openai-compatible-endpoints)
4. [System Endpoints](#4-system-endpoints)
5. [Route Aliases](#5-route-aliases)
6. [Error Responses](#6-error-responses)
7. [Client Examples](#7-client-examples)
2. [Authentication](#2-authentication)
3. [Native Flow Endpoints (`/api/v1/*`)](#3-native-flow-endpoints)
4. [OpenAI-Compatible Endpoints (`/v1/*`)](#4-openai-compatible-endpoints)
5. [System Endpoints](#5-system-endpoints)
6. [Route Aliases](#6-route-aliases)
7. [Error Responses](#7-error-responses)
8. [Client Examples](#8-client-examples)

---

Expand Down Expand Up @@ -47,11 +48,43 @@ All endpoints assume the server is running at its default address.
| :--- | :--- | :--- |
| `GET` | `/health` | Engine liveness check |

> **Route Aliases**: Every `/api/v1/*` native endpoint is also reachable under `/v1/*` for convenience. See [Section 5](#5-route-aliases) for the full alias map.
> **Route Aliases**: Every `/api/v1/*` native endpoint is also reachable under `/v1/*` for convenience. See [Section 6](#6-route-aliases) for the full alias map.

---

## 2. Native Flow Endpoints
## 2. Authentication

Flow Agent supports optional API key authentication for production and public deployments.

### Operating Modes

- **Unauthenticated (Local / Dev Mode)**: If no API keys are registered and `FLOW_API_KEY` is unset, authentication is disabled so existing local workflows work without credentials.
- **Enforced Mode**: Active when at least one API key is created via `python main.py key create` or the `FLOW_API_KEY` environment variable is set. Protected endpoints require a valid key.

### Providing Credentials

Credentials are accepted from headers only:
1. **Authorization Header (OpenAI SDK Standard)**:
```http
Authorization: Bearer sk-flow-...
```
2. **X-API-Key Header (Standard HTTP Client)**:
```http
X-API-Key: sk-flow-...
```

*(Note: Credentials in query parameters like `?api_key=` are deliberately rejected to prevent key leakage in server access logs and `Referer` headers).*

### Public Endpoints

The following routes are always accessible without credentials:
- `GET /health` (Liveness probe)
- `GET /docs`, `GET /redoc`, `GET /openapi.json` (API documentation)
- `GET /v1/media/*`, `GET /api/v1/media/*` (Generated media downloads)

---

## 3. Native Flow Endpoints

### 2.1 Generate Image

Expand Down Expand Up @@ -485,9 +518,11 @@ All errors return a JSON body with a `detail` field:
| HTTP Status | Meaning |
| :--- | :--- |
| `400 Bad Request` | Invalid parameter value (e.g. unsupported image size) |
| `401 Unauthorized` | API key missing, invalid, or revoked when authentication is enforced |
| `404 Not Found` | Media file not found or path traversal blocked |
| `422 Unprocessable Entity` | Request body validation failure (missing required field, out-of-range value) |
| `502 Bad Gateway` | Google Flow upstream refused the generation request (anti-abuse / rate limit) — not a server error |
| `503 Service Unavailable` | API key store corrupted or unreadable (Fail-Closed protection enforces request refusal) |

> **Note on 502:** A `502` means the code path executed correctly and Google declined the request. Retrying after a cooldown of 30–120 s usually succeeds. Attaching the Flow Chrome extension and using `--captcha broker` significantly reduces the chance of refusal.

Expand Down
37 changes: 37 additions & 0 deletions docs/CLI_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Complete command-line documentation for **Flow Agent** and the underlying **Flow
- [balance](#15-balance--account-credits)
- [stats](#16-stats--generation-history)
- [projects](#17-projects--list-flow-projects)
- [key](#18-key--manage-api-keys)
2. [Engine Binary (`./bin/flow`)](#2-engine-binary-binflow)
3. [Environment Variables](#3-environment-variables)
4. [Exit Codes](#4-exit-codes)
Expand Down Expand Up @@ -237,6 +238,41 @@ python main.py projects --cookies cookies/account_abc.json

---

### 1.8 `key` — Manage API Keys

Manages API keys used to secure the REST API endpoints when exposing the server externally.

```bash
python main.py key {create,list,revoke,delete} [options]
```

#### Subcommands

| Subcommand | Arguments | Description |
| :--- | :--- | :--- |
| `create` | `[--name NAME]` | Generate a new random secret API key (`sk-flow-...`) and register it. Refuses duplicate names. |
| `list` | None | List all registered API keys with their status and masked secrets |
| `revoke` | `TARGET` | Deactivate an API key by its secret value or unique alias name (soft delete) |
| `delete` | `TARGET` | Permanently remove an API key from the local store (hard delete) |

**Examples:**

```bash
# Generate a new API key with an alias
python main.py key create --name "my-laptop"

# List all keys
python main.py key list

# Revoke a key by alias or secret
python main.py key revoke "my-laptop"

# Permanently delete a key
python main.py key delete "my-laptop"
```

---

## 2. Engine Binary (`./bin/flow`)

The low-level Go binary (`flow-macos` on macOS, `flow-linux` on Linux, `flow-windows.exe` on Windows) is invoked automatically by the Python layer. It can also be used directly for advanced workflows.
Expand Down Expand Up @@ -351,6 +387,7 @@ Starts the WebSocket bridge on `ws://127.0.0.1:9222` that the Chrome Flow extens
| Variable | Default | Description |
| :--- | :--- | :--- |
| `IMAGE_MODEL` | `narwhal` | Default image model key. Overrides the `--model` default without passing the flag. |
| `FLOW_API_KEY` | *(empty)* | Optional master secret key. Enforces API authentication across all protected REST routes. |
| `FLOW_COOKIES_DIR` | `cookies/` | Directory to scan for account JSON bundles. |
| `FLOW_OUTPUT_DIR` | `output/` | Directory where generated images and videos are saved. |
| `FLOW_DB_PATH` | `data/flow.db` | SQLite database path for generation history. |
Expand Down
2 changes: 1 addition & 1 deletion docs/superpowers/plans/engine-architecture-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,5 +54,5 @@ Transform Google Flow image and video generation into a high-throughput, program
## 3. Future Roadmap

- [ ] **Docker Containerization**: Multi-stage `Dockerfile` and `docker-compose.yml` for cloud deployments.
- [ ] **Optional API Key Authentication**: Bearer token middleware for public-facing deployments.
- [x] **Optional API Key Authentication**: Bearer token middleware, CLI key management, and constant-time verification for public-facing deployments.
- [ ] **Web UI Dashboard**: Built-in visual prompt testing playground served on `/`.
16 changes: 16 additions & 0 deletions flow-agent/flow_agent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@
from .engine import EngineError, FlowEngine, extract_json
from .api import app
from .mcp_server import create_sse_app, run_stdio
from .auth import (
create_api_key,
delete_api_key,
is_auth_enforced,
list_api_keys,
mask_key,
revoke_api_key,
verify_api_key,
)

__version__ = "1.0.0"

Expand All @@ -13,5 +22,12 @@
"app",
"create_sse_app",
"run_stdio",
"create_api_key",
"delete_api_key",
"is_auth_enforced",
"list_api_keys",
"mask_key",
"revoke_api_key",
"verify_api_key",
"__version__",
]
31 changes: 16 additions & 15 deletions flow-agent/flow_agent/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@
from pathlib import Path
from typing import Any, Optional

from fastapi import FastAPI, HTTPException, Request
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field

from .auth import verify_api_key
from .engine import EngineError, FlowEngine

app = FastAPI(
Expand Down Expand Up @@ -260,7 +261,7 @@ async def frames():
# --------------------------------------------------------------------------- #


@app.post("/v1/images/generations")
@app.post("/v1/images/generations", dependencies=[Depends(verify_api_key)])
async def openai_images(payload: ImageGenerationRequest, request: Request):
"""Generate an image from an OpenAI images payload."""
aspect = SIZE_TO_ASPECT.get(payload.size.strip().lower())
Expand Down Expand Up @@ -295,7 +296,7 @@ async def openai_images(payload: ImageGenerationRequest, request: Request):
return payload_out


@app.post("/v1/chat/completions")
@app.post("/v1/chat/completions", dependencies=[Depends(verify_api_key)])
async def openai_chat(payload: ChatCompletionRequest, request: Request):
"""Generate from the last user turn and answer with a Markdown link."""
prompt = _prompt_from_messages(payload.messages)
Expand Down Expand Up @@ -332,9 +333,9 @@ async def openai_chat(payload: ChatCompletionRequest, request: Request):
# --------------------------------------------------------------------------- #


@app.post("/v1/generate/image")
@app.post("/v1/image")
@app.post("/api/v1/image")
@app.post("/v1/generate/image", dependencies=[Depends(verify_api_key)])
@app.post("/v1/image", dependencies=[Depends(verify_api_key)])
@app.post("/api/v1/image", dependencies=[Depends(verify_api_key)])
async def flow_image(payload: FlowImageRequest):
"""Generate an image, speaking the engine's own vocabulary."""
try:
Expand All @@ -350,9 +351,9 @@ async def flow_image(payload: FlowImageRequest):
raise HTTPException(status_code=502, detail=str(exc)) from exc


@app.post("/v1/generate/video")
@app.post("/v1/video")
@app.post("/api/v1/video")
@app.post("/v1/generate/video", dependencies=[Depends(verify_api_key)])
@app.post("/v1/video", dependencies=[Depends(verify_api_key)])
@app.post("/api/v1/video", dependencies=[Depends(verify_api_key)])
async def flow_video(payload: FlowVideoRequest):
"""Generate a video, speaking the engine's own vocabulary."""
try:
Expand All @@ -370,8 +371,8 @@ async def flow_video(payload: FlowVideoRequest):
raise HTTPException(status_code=502, detail=str(exc)) from exc


@app.get("/v1/balance")
@app.get("/api/v1/balance")
@app.get("/v1/balance", dependencies=[Depends(verify_api_key)])
@app.get("/api/v1/balance", dependencies=[Depends(verify_api_key)])
async def flow_balance(refresh: bool = False):
"""Credits per account, cached by default and probed with `?refresh=true`."""
try:
Expand All @@ -380,8 +381,8 @@ async def flow_balance(refresh: bool = False):
raise HTTPException(status_code=502, detail=str(exc)) from exc


@app.get("/v1/stats")
@app.get("/api/v1/stats")
@app.get("/v1/stats", dependencies=[Depends(verify_api_key)])
@app.get("/api/v1/stats", dependencies=[Depends(verify_api_key)])
async def flow_stats():
"""Generation history and engine totals, read from the database."""
try:
Expand All @@ -390,8 +391,8 @@ async def flow_stats():
raise HTTPException(status_code=502, detail=str(exc)) from exc


@app.get("/v1/projects")
@app.get("/api/v1/projects")
@app.get("/v1/projects", dependencies=[Depends(verify_api_key)])
@app.get("/api/v1/projects", dependencies=[Depends(verify_api_key)])
async def flow_projects(cookies: Optional[str] = None):
try:
return {"projects": await engine.get_projects(cookies=cookies)}
Expand Down
Loading