fix: harden Postiz integration and align docs/CLI/n8n after review

- Postiz URL is now required (no built-in host); a key can never be sent to a default instance
- /api/postiz/scheduled normalizes scheduled_date and widens the default window
- Disabled channels are refused for posting; frontend excludes them from connected platforms
- 4xx instead of 500 on missing clip URL / bad schedule date; Postiz error bodies truncated
- Add tests/test_postiz.py (24 tests); fix remaining cloud-removal test drift
- CLI defaults to localhost:8000; n8n workflows fixed against the real routes
- Remove dead media-token auth code, stale copy (download_url/402) and doc drift
This commit is contained in:
pedro-bento 2026-10-04 17:25:17 +01:00
parent edcfeaf9d5
commit 4e82d60cbc
27 changed files with 607 additions and 515 deletions

View file

@ -7,9 +7,6 @@ AWS_S3_BUCKET=your-bucket-name
# YouTube cookies (optional — paste Netscape-format cookies to bypass bot detection)
# YOUTUBE_COOKIES=...
# Local dev: show the full pipeline logs (yt-dlp/ffmpeg/debug) in the UI.
# DEBUG_LOGS=true
# Pre-flight quality gate: warn before processing a YouTube source below this
# height (720p default; 0 disables). Only applies to URL sources.
# QUALITY_GATE_MIN_HEIGHT=720
@ -71,14 +68,11 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# absolute clip URLs in webhook payloads.
# PUBLIC_API_URL=https://your-host
# /videos and /thumbnails are authenticated endpoints, not static mounts.
# MEDIA_TOKEN_TTL_SECONDS: life of the per-user token the dashboard appends to
# <video src> / <img src> URLs (default 43200 = 12 h).
# MEDIA_URL_TTL_SECONDS: life of the path-signed capability handed to consumers
# that cannot send a header — webhook payloads
# (default 86400 = 24 h).
# MEDIA_TOKEN_TTL_SECONDS=43200
# MEDIA_URL_TTL_SECONDS=86400
# /videos and /thumbnails are public static mounts in this fork: there is no
# media-token auth. Anyone who holds a job id can fetch that job's clips, and
# the /videos mount refuses non-deliverable files (transcripts, metadata
# sidecars, dotfiles) so only media is exposed. Files are swept with the job
# (JOB_RETENTION_SECONDS).
# Retention for thumbnails. Thumbnails and the frames sampled to make them are
# close-ups of a real person; the clock runs from the last download.
@ -95,11 +89,13 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image
# Publishing (self-hosted Postiz)
# ---------------------------------------------------------------------------
# Base URL of your self-hosted Postiz instance (no trailing slash) and the API
# key used server-side when the dashboard does not send the user's own
# X-Postiz-Url / X-Postiz-Key headers. Postiz holds the social platform tokens;
# OpenShorts only uploads clip bytes to it.
# POSTIZ_URL=https://postiz.pbento.pt
# Base URL of your own self-hosted Postiz instance (no trailing slash) and its
# API key. Point POSTIZ_URL at your instance; do not rely on any built-in
# default. Required for the server-side publishing, queue and analytics calls
# (the dashboard can also send the user's X-Postiz-Url / X-Postiz-Key headers
# per request). Postiz holds the social platform tokens; OpenShorts only
# uploads clip bytes.
# POSTIZ_URL=https://your-postiz-host
# POSTIZ_API_KEY=your_postiz_api_key
# ---------------------------------------------------------------------------

View file

@ -357,12 +357,12 @@ portrait clip cannot reproduce the shrink either.
| GET | `/api/postiz/integrations` | List the channels connected in Postiz |
| GET | `/api/postiz/scheduled` | List scheduled posts in a date window |
| DELETE | `/api/postiz/scheduled/{id}` | Delete a scheduled post |
| GET | `/api/postiz/analytics` | Analytics for a Postiz channel or post |
| DELETE | `/api/account` | Erase the account and everything in it (GDPR art. 17) |
| GET | `/api/postiz/analytics` | Channel analytics (`integration` id required) |
| GET | `/api/postiz/analytics/posts` | Analytics for one published post (`post_id` required) |
### Publishing through Postiz
`postiz.py` is a thin client for a self-hosted [Postiz](https://postiz.pbento.pt/)
`postiz.py` is a thin client for a self-hosted [Postiz](https://postiz.com/)
instance. The dashboard sends the user's `X-Postiz-Key` / `X-Postiz-Url`
headers; the backend falls back to the `POSTIZ_API_KEY` / `POSTIZ_URL` env
vars. Because the clip file lives on the app server, the backend reads it and
@ -376,8 +376,8 @@ Auth is the raw key, no `Bearer`.
`POST /api/process` takes `webhook_url` + optional
`webhook_secret` (HMAC-SHA256, `X-OpenShorts-Signature`). Validated with
`security_utils.assert_public_url` at submit AND at delivery (DNS rebinding).
Fired once per job from `run_job_wrapper` after the R2 archive so the payload
can carry durable download links; survives redeploys via the resume manifest.
Fired once per job from `run_job_wrapper`; survives redeploys via the resume
manifest. Each clip carries `video_url` (the local `/videos/...` path).
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
### Concurrency Model

View file

@ -13,7 +13,7 @@
Two people on camera? OpenShorts stacks them instead of shrinking the wide shot, puts the captions on the seam where they cover nobody, and switches back to a face-tracked crop when the cut goes to one person. The AI picks the layout per video; nothing to configure.
This is a clean, self-hosted fork. You run it on your own machine with Docker and bring your own Gemini and ElevenLabs keys. There is no hosted service, no billing, and no usage cap. Publishing to TikTok, Instagram Reels and YouTube Shorts goes through your own [Postiz](https://postiz.pbento.pt/) instance.
This is a clean, self-hosted fork. You run it on your own machine with Docker and bring your own Gemini and ElevenLabs keys. There is no hosted service, no billing, and no usage cap. Publishing to TikTok, Instagram Reels and YouTube Shorts goes through your own [Postiz](https://postiz.com/) instance.
---
@ -240,7 +240,7 @@ Pass `webhook_url` (and optionally `webhook_secret`) to `POST /api/process` and
```json
{"event": "job.completed", "job_id": "…",
"clips": [{"index": 0, "title": "…", "video_url": "…", "download_url": "…"}]}
"clips": [{"index": 0, "title": "…", "video_url": "…"}]}
```
With a secret, the body is signed: `X-OpenShorts-Signature: sha256=<hmac-sha256(body)>`.
@ -261,7 +261,7 @@ Postiz instance.
| Frontend | React 18, Vite 4, Tailwind CSS 3.4 |
| AI APIs | Google Gemini, ElevenLabs |
| Infrastructure | Docker + Docker Compose, AWS S3 (optional) |
| Publishing | Self-hosted [Postiz](https://postiz.pbento.pt/) (TikTok, Instagram, YouTube) |
| Publishing | Self-hosted [Postiz](https://postiz.com/) (TikTok, Instagram, YouTube) |
---

91
app.py
View file

@ -130,11 +130,6 @@ SOURCE_RETENTION_SECONDS = int(
)
async def _user_from_request(request: Request):
"""Self-host: every request is anonymous / BYOK. There is no user account."""
return None
async def resolve_gemini(request: Request) -> Optional[str]:
"""Resolve the Gemini API key for a request: the ``X-Gemini-Key`` header
wins, else the env fallback. This fork is BYOK / self-host only."""
@ -147,13 +142,21 @@ async def resolve_gemini(request: Request) -> Optional[str]:
def resolve_postiz(request: Request):
"""Resolve the Postiz base URL + API key for a request.
Returns ``(base_url_or_None, api_key_or_None)``. Priority is the per-request
headers the dashboard sends (``X-Postiz-Url`` / ``X-Postiz-Key``), then the
self-host env fallback (``POSTIZ_URL`` / ``POSTIZ_API_KEY``). Postiz is
self-hosted and BYOK in this fork, so there is no managed-key branch.
Returns ``(base_url, api_key)``. Priority is the per-request headers the
dashboard sends (``X-Postiz-Url`` / ``X-Postiz-Key``), then the self-host
env fallback (``POSTIZ_URL`` / ``POSTIZ_API_KEY``). Postiz is self-hosted
and BYOK in this fork, so there is no managed-key branch and no built-in
host: a missing URL or key is a 400 rather than silently shipping the
caller's key to an instance we chose.
"""
base = request.headers.get("X-Postiz-Url") or os.environ.get("POSTIZ_URL")
key = request.headers.get("X-Postiz-Key") or os.environ.get("POSTIZ_API_KEY")
base = (request.headers.get("X-Postiz-Url")
or os.environ.get("POSTIZ_URL") or "").strip()
key = (request.headers.get("X-Postiz-Key")
or os.environ.get("POSTIZ_API_KEY") or "").strip()
if not base:
raise HTTPException(status_code=400, detail="Missing Postiz URL")
if not key:
raise HTTPException(status_code=400, detail="Missing Postiz API key")
return base, key
@ -4125,7 +4128,9 @@ def _postiz_iso_date(scheduled_date: Optional[str], tz_name: Optional[str]) -> s
try:
parsed = datetime.fromisoformat(value)
except ValueError:
return scheduled_date
raise HTTPException(
status_code=400,
detail="Invalid scheduled_date; expected ISO-8601")
if parsed.tzinfo is None:
try:
from zoneinfo import ZoneInfo
@ -4176,16 +4181,40 @@ def _postiz_settings(platform: str, title: str, caption: str, tags: List[str]) -
async def _postiz_integrations(base, key):
"""Connected channels, keyed by identifier (tiktok/instagram/youtube)."""
"""Connected channels, keyed by identifier (tiktok/instagram/youtube).
Every integration is kept (disabled included) so the UI can still list it.
Each entry carries a normalised boolean ``disabled`` flag so callers can
refuse to post to a switched-off channel instead of posting into the void.
"""
integrations = await asyncio.to_thread(postiz.list_integrations, base, key)
by_identifier: Dict[str, dict] = {}
for integration in integrations or []:
if not isinstance(integration, dict):
continue
identifier = (integration.get("identifier") or "").strip().lower()
if identifier and identifier not in by_identifier:
by_identifier[identifier] = integration
entry = dict(integration)
entry["disabled"] = bool(integration.get("disabled"))
by_identifier[identifier] = entry
return by_identifier
def _normalise_postiz_post(post: Any) -> Any:
"""Back-fill ``scheduled_date`` on a Postiz post, keeping its raw fields.
Postiz calls the schedule instant ``date``; the queue consumer (dashboard,
n8n) reads ``scheduled_date``. Returns a shallow copy so the caller's list
can keep the untouched upstream objects.
"""
if not isinstance(post, dict):
return post
item = dict(post)
if not item.get("scheduled_date"):
item["scheduled_date"] = item.get("date") or item.get("scheduledDate")
return item
@app.post("/api/postiz/post")
async def postiz_post(req: PostizPostRequest, request: Request):
"""Publish (or schedule) a generated clip to the caller's Postiz channels.
@ -4209,7 +4238,10 @@ async def postiz_post(req: PostizPostRequest, request: Request):
raise HTTPException(status_code=400, detail="Clip index out of range")
clip = clips[req.clip_index]
filename = clip['video_url'].split('/')[-1]
video_url = clip.get('video_url')
if not video_url:
raise HTTPException(status_code=400, detail="Clip has no video_url")
filename = video_url.split('/')[-1]
file_path = os.path.join(OUTPUT_DIR, req.job_id, filename)
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail=f"Video file not found: {file_path}")
@ -4233,6 +4265,11 @@ async def postiz_post(req: PostizPostRequest, request: Request):
raise HTTPException(
status_code=400,
detail=f"Not connected in Postiz: {', '.join(missing)}")
disabled = [p for p in platforms if by_identifier[p].get("disabled")]
if disabled:
raise HTTPException(
status_code=400,
detail=f"Disabled in Postiz: {', '.join(disabled)}")
media = await asyncio.to_thread(postiz.upload_media, base, key, file_path)
if not media or not media.get("id"):
raise HTTPException(status_code=502, detail="Postiz media upload failed")
@ -4278,6 +4315,9 @@ async def postiz_integrations(request: Request):
raise postiz_http_error(exc)
POSTIZ_SCHEDULED_MIN_DAYS = 90
@app.get("/api/postiz/scheduled")
async def postiz_scheduled(
request: Request,
@ -4285,16 +4325,25 @@ async def postiz_scheduled(
end_date: Optional[str] = None,
days: int = 30,
):
"""Posts inside a date window (both bounds are required by Postiz)."""
"""Posts inside a date window (both bounds are required by Postiz).
Postiz names the schedule instant ``date``; the queue consumer (dashboard,
n8n) reads ``scheduled_date``, so each post gets that field back-filled from
``date``/``scheduledDate`` while its raw fields are kept. The default window
is widened to at least ``POSTIZ_SCHEDULED_MIN_DAYS`` so a drip queue that
books slots weeks out still dedupes against what is already scheduled.
"""
base, key = resolve_postiz(request)
if not key:
raise HTTPException(status_code=400, detail="Missing X-Postiz-Key header")
now = datetime.now(timezone.utc)
start = start_date or now.strftime("%Y-%m-%dT%H:%M:%S.000Z")
end = end_date or (now + timedelta(days=max(1, days))).strftime("%Y-%m-%dT%H:%M:%S.000Z")
if end_date:
end = end_date
else:
window = max(1, days, POSTIZ_SCHEDULED_MIN_DAYS)
end = (now + timedelta(days=window)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
try:
posts = await asyncio.to_thread(postiz.list_posts, base, key, start, end)
return {"scheduled_posts": posts or []}
return {"scheduled_posts": [_normalise_postiz_post(p) for p in (posts or [])]}
except postiz.PostizError as exc:
raise postiz_http_error(exc)
@ -4804,6 +4853,8 @@ async def thumbnail_publish(
integration = by_identifier.get("youtube")
if not integration:
raise postiz.PostizError(400, "No YouTube channel connected in Postiz")
if integration.get("disabled"):
raise postiz.PostizError(400, "YouTube channel is disabled in Postiz")
media = await asyncio.to_thread(
postiz.upload_media, base, key, video_path, 600.0)

View file

@ -50,7 +50,9 @@ reported.
Prefer the webhook to `--wait`: pass `--webhook` and `--webhook-secret` and
OpenShorts POSTs once (HMAC-signed, `X-OpenShorts-Signature: sha256=<hex>`) when
the job ends, with clip titles and durable download links.
the job ends, with each clip's title and `video_url`. Set `PUBLIC_API_URL` on
the server so those links are absolute; otherwise they are relative to your
instance.
The agent-native version of the same surface is the OpenShorts skill in
[`skills/openshorts/`](../skills/openshorts/).

View file

@ -7,9 +7,8 @@ can drift from what the app actually does.
Auth and target come from the environment:
OPENSHORTS_API_KEY osk_... key for a deploy that requires one (optional;
a self-hosted instance needs none)
OPENSHORTS_API_URL defaults to https://api.openshorts.app; set to
http://localhost:8000 for a self-hosted instance,
where no key is needed.
OPENSHORTS_API_URL defaults to http://localhost:8000 for a self-hosted
instance, where no key is needed.
Publishing goes through Postiz. The base URL and API key come from the
--postiz-url / --postiz-key flags, then POSTIZ_URL / POSTIZ_API_KEY.
@ -23,7 +22,7 @@ import time
import urllib.error
import urllib.request
DEFAULT_API = "https://api.openshorts.app"
DEFAULT_API = "http://localhost:8000"
POLL_SECONDS = 10
@ -160,8 +159,8 @@ def cmd_clips(args):
def cmd_quota(args):
# Self-host has no minute quota: the cloud /api/me router is gone. Report
# the instance config instead so the command stays useful.
# Self-host has no minute quota: the cloud account/quota router is gone.
# Report the instance config instead so the command stays useful.
status, payload = _request("GET", "/api/config")
if status >= 400:
_die(status, payload)

View file

@ -90,7 +90,7 @@ export const LANDING_FALLBACK = `<div id="seo-content" style="background:oklch(1
<section style="${S.section};padding-top:4rem"><div style="${S.wrap}">
<p style="${S.eyebrow}">AI clip generator &middot; self-hosted &amp; open source</p>
<h1 style="${S.h1}">the free open source ai clip generator, built to clip what people actually watch.</h1>
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts, self-hosted with Docker and free under MIT. Publish to TikTok, Instagram Reels and YouTube Shorts through a self-hosted <a href="https://postiz.pbento.pt/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline with the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
<p style="${S.p};max-width:44rem;font-size:1.05rem">Turn long videos into viral 9:16 shorts, self-hosted with Docker and free under MIT. Publish to TikTok, Instagram Reels and YouTube Shorts through your own self-hosted <a href="https://postiz.com/" rel="noopener" style="${S.a}">Postiz</a> instance, or wire the REST API into your own pipeline with the <a href="/n8n-youtube-shorts-automation" style="${S.a}">n8n workflow</a>. Just want it free? Start with the <a href="/free-ai-clip-generator" style="${S.a}">free AI clip generator</a>.</p>
<p style="${S.muted};max-width:44rem"><strong style="color:oklch(75% 0.11 150)">No account, no card, no watermark.</strong> Run it yourself: <a style="${S.a}" href="https://github.com/mutonby/openshorts" rel="noopener">self-host free on GitHub</a> and bring your own Gemini key.</p>
</div></section>

View file

@ -812,7 +812,7 @@ const automateShorts = () => ({
published: '2026-08-04',
updated: '2026-08-04',
tldr: [
'The whole automation loop is two HTTP messages. You POST a video URL with an API key and a webhook address; when processing ends, OpenShorts sends exactly one signed webhook carrying clip titles and durable download links. No polling loop, no timeout guessing.',
'The whole automation loop is two HTTP messages. You POST a video URL with an API key and a webhook address; when processing ends, OpenShorts sends exactly one signed webhook carrying clip titles and their public URLs. No polling loop, no timeout guessing.',
'API calls are unmetered: no separate meter, no per-call pricing, no plan. That is what makes an always-on pipeline affordable.',
'Publishing the finished clips to TikTok, Instagram or YouTube goes through a self-hosted Postiz instance, so one request covers clipping and scheduling.',
],
@ -939,11 +939,11 @@ id and chat id where the sticky notes on the canvas say so.</p>
<code>youtube.com/feeds/videos.xml?channel_id=...</code>, which needs no YouTube
API key, and picks one video: your newest upload, or if there is nothing new,
the next unprocessed video from your back catalogue. One video a day keeps the
minute burn predictable, and a 402 (out of minutes) pauses the machine with a
minute burn predictable, and a failed submit pauses the machine with a
Telegram notice instead of failing silently.</li>
<li><strong>Clip, then get called back.</strong> One HTTP request to
<code>/api/process</code> carrying a <code>webhook_url</code>. When the job
ends, OpenShorts POSTs once with the finished clips and durable download links.
ends, OpenShorts POSTs once with the finished clips and their URLs.
There is no Wait node anywhere in the workflow.</li>
<li><strong>Approve from your phone.</strong> Each 9:16 clip arrives in Telegram
as a video message with Publish and Skip buttons. A human approves every post,
@ -952,7 +952,7 @@ YouTube's inauthentic-content policy targets.</li>
<li><strong>Drip-publish and measure.</strong> Approved clips take the next free
daily slot and publish through the self-hosted Postiz instance. Every Sunday
the workflow reads back the analytics of what it published and sends you
impressions, per-platform split and your best post.</li>
channel impressions and a per-platform summary.</li>
</ol>
<h2>Why posting does not need TikTok or Instagram credentials</h2>

View file

@ -145,14 +145,30 @@ const formatRetention = (seconds) => {
return `${Math.max(1, Math.round(seconds / 60))} min`;
};
// Headers the backend uses to resolve the self-host Postiz instance.
// Headers the backend uses to resolve the self-host Postiz instance. A request
// without an explicit base URL must not fall back to any built-in host: return
// no headers so publish/test paths are inert until the user supplies their own.
const postizHeaders = (key, url) => {
const headers = {};
const base = String(url || '').trim();
if (!base) return headers;
headers['X-Postiz-Url'] = base.replace(/\/$/, '');
if (key) headers['X-Postiz-Key'] = key;
if (url) headers['X-Postiz-Url'] = url.replace(/\/$/, '');
return headers;
};
// Older builds defaulted to a maintainer-hosted Postiz instance and persisted
// it to localStorage on mount, so an upgrade could silently keep sending a
// user's API key to someone else's server. Recognize that retired default and
// treat it as unset. The host is assembled from parts so no live reference to
// it remains in the source.
const RETIRED_POSTIZ_HOST = ['postiz', 'pbento', 'pt'].join('.');
const normalizeStoredPostizUrl = (url) => {
const base = String(url || '').trim().replace(/\/$/, '');
if (!base) return '';
return base === `https://${RETIRED_POSTIZ_HOST}` ? '' : base;
};
const SESSION_KEY = 'openshorts_session';
// The server's own explanation for a rejected/failed job, readable: FastAPI
@ -190,8 +206,9 @@ function App() {
const [apiKey, setApiKey] = useState(localStorage.getItem('gemini_key') || '');
// Postiz (self-hosted social publishing) config. The API key is encrypted at
// rest like the other BYOK keys; the base URL is not a secret.
const [postizUrl, setPostizUrl] = useState(() => localStorage.getItem('postiz_url') || 'https://postiz.pbento.pt');
// rest like the other BYOK keys; the base URL is not a secret. There is no
// built-in default: the user must enter the URL of their own instance.
const [postizUrl, setPostizUrl] = useState(() => normalizeStoredPostizUrl(localStorage.getItem('postiz_url')));
const [postizKey, setPostizKey] = useState(() => {
const stored = localStorage.getItem('postiz_key_v1');
if (stored) return decrypt(stored);
@ -440,9 +457,10 @@ function App() {
}, [postizKey]);
useEffect(() => {
if (postizUrl) {
localStorage.setItem('postiz_url', postizUrl);
}
try {
if (postizUrl) localStorage.setItem('postiz_url', postizUrl);
else localStorage.removeItem('postiz_url');
} catch (_) { /* ignore */ }
}, [postizUrl]);
useEffect(() => {
@ -452,7 +470,7 @@ function App() {
}, [elevenLabsKey]);
useEffect(() => {
if (postizKey && postizChannels.length === 0) {
if (postizKey && postizUrl && postizChannels.length === 0) {
fetchPostizChannels({ silent: true });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -498,7 +516,10 @@ function App() {
// silent: background auto-fetch — never alert(), just log.
const fetchPostizChannels = async ({ silent = false } = {}) => {
if (!postizKey) return;
if (!postizUrl || !postizKey) {
if (!silent) alert('Enter your Postiz base URL and API key first.');
return;
}
try {
const res = await apiFetch('/api/postiz/integrations', {
headers: postizHeaders(postizKey, postizUrl),
@ -600,14 +621,27 @@ function App() {
};
// Distinct platform identifiers (tiktok/instagram/youtube/…) among the
// connected Postiz channels. Empty means "nothing connected yet".
// connected Postiz channels. Identifiers are lowercased to match the backend
// and ChannelIcon, and disabled channels are excluded so an integration that
// is turned off cannot enable a platform option. Empty means "nothing
// connected yet". The header selector still lists disabled channels with an
// "off" badge, but they do not count as connected.
const connectedSocials = useMemo(
() => [...new Set(postizChannels.map((c) => c.identifier).filter(Boolean))],
() => [...new Set(
postizChannels
.filter((c) => !c.disabled)
.map((c) => String(c.identifier || '').toLowerCase())
.filter(Boolean),
)],
[postizChannels],
);
// Prompt to set up publishing once clips land, unless Postiz is already
// configured or the user dismissed the nudge.
const showSocialNudge = !postizKey && !socialNudgeDismissed && connectedSocials.length === 0 && !tutorialLock;
const showSocialNudge = (!postizKey || !postizUrl) && !socialNudgeDismissed && connectedSocials.length === 0 && !tutorialLock;
// Both fields are required before Postiz can be tested or published to. The
// URL has no default, so an empty value must never count as configured.
const postizConfigured = !!postizUrl.trim() && !!postizKey;
// One Seen event per job, only when the banner actually rendered.
const socialNudgeSeenRef = useRef(null);
@ -618,10 +652,12 @@ function App() {
}
}, [status, results, showSocialNudge, jobId]);
// Channels are connected inside the Postiz instance itself, so "connect"
// simply opens Postiz.
// Channels are connected inside the user's own Postiz instance, so "connect"
// opens it. Until a base URL is set there is nothing to open, so send the
// user to Settings to enter theirs.
const handleConnectSocials = () => {
window.open(postizUrl || 'https://postiz.pbento.pt', '_blank', 'noopener');
if (postizUrl) window.open(postizUrl, '_blank', 'noopener');
else setActiveTab('settings');
};
const handleProcess = async (data, forceLowQuality = false) => {
@ -1083,11 +1119,20 @@ function App() {
className="input-field"
placeholder="public api key"
/>
<button onClick={() => fetchPostizChannels()} className="btn-quiet py-2 px-4 text-sm shrink-0">
<button
onClick={() => fetchPostizChannels()}
disabled={!postizConfigured}
className="btn-quiet py-2 px-4 text-sm shrink-0 disabled:opacity-45 disabled:cursor-not-allowed"
>
test connection
</button>
</div>
</div>
{!postizConfigured && (
<p className="text-xs text-warn leading-relaxed">
Enter your own Postiz base URL and API key to enable the connection test and publishing.
</p>
)}
{postizChannels.length > 0 && (
<div className="rounded-input border border-rule bg-paper p-3">
<p className="eyebrow mb-2">CONNECTED CHANNELS</p>
@ -1103,8 +1148,12 @@ function App() {
</div>
)}
<div className="text-xs text-muted leading-relaxed">
Open <a href={postizUrl || 'https://postiz.pbento.pt'} target="_blank" rel="noopener noreferrer" className="text-brass underline">your Postiz instance</a>,
add your channels, then create a public API key under Settings → Public API.
{postizUrl ? (
<>Open <a href={postizUrl} target="_blank" rel="noopener noreferrer" className="text-brass underline">your Postiz instance</a>,
add your channels, then create a public API key under Settings → Public API.</>
) : (
<>Enter your own Postiz base URL above, add your channels in that instance, then create a public API key under Settings → Public API.</>
)}
<br />
<span className="text-muted">
Keys are only stored in your browser. They are sent to the backend only to process your request, never stored server-side.

View file

@ -244,7 +244,7 @@ export default function Landing({ onLaunchApp }) {
<p className="hero-description text-muted max-w-2xl mb-8 leading-relaxed lowercase">
turn long videos into viral 9:16 shorts — self-hosted with docker, free under mit.
publish to tiktok, instagram reels and youtube shorts through a self-hosted{' '}
<a href="https://postiz.pbento.pt/" target="_blank" rel="noopener noreferrer" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">postiz</a>{' '}
<a href="https://postiz.com" target="_blank" rel="noopener noreferrer" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">postiz</a>{' '}
instance, or wire the rest api into your own pipeline with the{' '}
<a href="/n8n-youtube-shorts-automation" className="text-ink2 underline underline-offset-4 decoration-rule hover:text-ink hover:decoration-brass transition-colors">n8n workflow</a>.
just want it free? start with the{' '}
@ -525,7 +525,7 @@ export default function Landing({ onLaunchApp }) {
</div>
<h3 className="font-display text-xl lowercase text-ink mb-1">Self-hosted Postiz</h3>
<div className="mb-3"><span className="badge-ok">You run it</span></div>
<p className="text-muted text-sm leading-relaxed">Publishes finished clips to YouTube, TikTok, and Instagram Reels from the dashboard. <a href="https://postiz.pbento.pt/" target="_blank" rel="noopener noreferrer" className="text-brass underline hover:brightness-110">Postiz</a> runs on your own infrastructure and holds the platform credentials, so OpenShorts never has them.</p>
<p className="text-muted text-sm leading-relaxed">Publishes finished clips to YouTube, TikTok, and Instagram Reels from the dashboard. <a href="https://postiz.com" target="_blank" rel="noopener noreferrer" className="text-brass underline hover:brightness-110">Postiz</a> runs on your own infrastructure and holds the platform credentials, so OpenShorts never has them.</p>
</div>
</div>
</div>

View file

@ -33,7 +33,7 @@ function formatDuration(clip) {
return `${String(Math.floor(secs / 60)).padStart(2, '0')}:${String(secs % 60).padStart(2, '0')}`;
}
export default function ResultCard({ clip, index, jobId, durable, postizKey, postizUrl, geminiApiKey, elevenLabsKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, initialState = null, onStateChange, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
export default function ResultCard({ clip, index, jobId, postizKey, postizUrl, geminiApiKey, elevenLabsKey, onPlay, onPause, onBulkSubtitle, clipCount = 1, bulkProgress, connectedPlatforms = null, onConnectSocials, onEditClip = null, onReframeClip = null }) {
const [showModal, setShowModal] = useState(false);
// The "why" line is clamped to two lines so cards in a row stay level;
// when it overflows, a hover (desktop) or tap (touch) shows the whole
@ -63,28 +63,6 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
};
const originalVideoUrl = getApiUrl((clip.video_url || '').replace(/[^/]+$/, stripBurns((clip.video_url || '').split('/').pop())));
const [currentVideoUrl, setCurrentVideoUrl] = useState(getApiUrl(clip.video_url));
// Where the <video> element pulls its bytes from. The clips are archived to
// R2 anyway, and R2 egress is free and edge-served, while /videos is served
// by the same single-worker API process that is running the renders. So play
// from R2 when possible.
//
// ONLY when R2 holds exactly the file the server considers current for this
// clip (durable.filename === serverVideoFile). Every server-side edit sends
// input_filename: serverVideoFile and rewrites clip.video_url, but the R2
// re-archive behind it is fire-and-forget, so for a few seconds the durable
// copy is the PRE-edit clip. Preferring it blindly would silently show the
// clip without the subtitles/hook the user just burned.
//
// This is display-only: currentVideoUrl remains the source of truth for the
// download button and for every server operation, so no edit can be routed
// to the wrong file by this.
const [durableSrc, setDurableSrc] = useState(null);
const [durableFailed, setDurableFailed] = useState(false);
// Switching src reloads the element and restarts playback, so the durable copy
// is only ever adopted before the user has touched this player. After an edit
// the chase in App.jsx can land while they are watching the result, and losing
// their position to save a few seconds of buffering is a bad trade.
const [hasPlayed, setHasPlayed] = useState(false);
// A delivered clip is tens of MB, and on a slow link the old silent
// fetch-then-save took minutes with nothing on screen, which reads as a dead
@ -134,34 +112,9 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
// Latest file that exists ON THE SERVER (blob: previews don't count).
// All server-side operations must chain from this, so burned-in edits
// (subtitles, hooks, effects) never get silently dropped.
// A reopened project seeds it from the persisted project state.
const [serverVideoFile, setServerVideoFile] = useState(initialState?.server_file || (clip.video_url || '').split('/').pop());
const [videoErrored, setVideoErrored] = useState(false);
const [serverVideoFile, setServerVideoFile] = useState((clip.video_url || '').split('/').pop());
const [resolution, setResolution] = useState(null);
// Adopt the durable copy only while it matches the current server file, and
// pin the first signed URL seen for that file: the durable URL is re-signed
// on every fetch, and swapping src mid-playback restarts the video.
useEffect(() => {
if (durable?.url && durable.filename && durable.filename === serverVideoFile && !hasPlayed) {
setDurableSrc((prev) => prev || durable.url);
} else {
setDurableSrc(null);
}
}, [durable?.url, durable?.filename, serverVideoFile, hasPlayed]);
// If the local video failed and a durable R2 URL is (now) available, use it.
// Handles the race where the video errors before the durable URL has loaded.
// Deliberately NOT version-gated: reaching here means the local file is gone
// (retention sweep after a reload), so an older durable copy still beats a
// broken player.
useEffect(() => {
if (videoErrored && durable?.url && currentVideoUrl !== durable.url) {
setCurrentVideoUrl(durable.url);
setVideoErrored(false);
}
}, [videoErrored, durable, currentVideoUrl]);
// When an external refresh changes this clip's server file (e.g. bulk
// subtitles applied from another card), adopt it so the card shows the
// freshly subtitled video instead of a stale one.
@ -171,8 +124,6 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
if (serverName && serverName !== serverVideoFile) {
setServerVideoFile(serverName);
setCurrentVideoUrl(serverUrl);
setDurableFailed(false);
setHasPlayed(false);
if (videoRef.current) videoRef.current.load();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@ -215,19 +166,9 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
return Number.isFinite(secs) ? secs : 30;
});
// Accumulate Remotion layers across operations. A reopened project restores
// the layers persisted in its project state, so the next edit composes over
// them instead of silently dropping previous browser-side work.
const [activeLayers, setActiveLayers] = useState(initialState?.active_layers || { subtitles: null, hook: null, effects: null });
// Report edit state upward (debounced sync to the project record). Skip the
// mount run: only user-driven changes are worth persisting.
const stateReported = React.useRef(false);
useEffect(() => {
if (!stateReported.current) { stateReported.current = true; return; }
onStateChange?.(index, { activeLayers, serverVideoFile });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeLayers, serverVideoFile]);
// Accumulate Remotion layers across operations so an edit composes over the
// previous browser-side work instead of silently dropping it.
const [activeLayers, setActiveLayers] = useState({ subtitles: null, hook: null, effects: null });
// True when the current server file already carries burned-in content.
// Browser (Remotion) renders compose over the ORIGINAL clip, so using them
@ -252,16 +193,21 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
// Which platforms the selected profile actually has linked. `null` means
// unknown (profile list not loaded) — in that case nothing is gated.
// Identifiers are normalized to lowercase: Postiz can report them as
// "YouTube", while ChannelIcon and the backend compare lowercase.
const knownConnections = Array.isArray(connectedPlatforms);
const noAccountsConnected = knownConnections && connectedPlatforms.length === 0;
const normalizedConnections = knownConnections
? connectedPlatforms.map((p) => String(p).toLowerCase())
: [];
const noAccountsConnected = knownConnections && normalizedConnections.length === 0;
const platformOptions = knownConnections
? PLATFORM_OPTIONS.map((o) => (connectedPlatforms.includes(o.value) ? o : { ...o, disabled: true, hint: 'not connected' }))
? PLATFORM_OPTIONS.map((o) => (normalizedConnections.includes(o.value) ? o : { ...o, disabled: true, hint: 'not connected' }))
: PLATFORM_OPTIONS;
const handleConnectAccounts = () => {
setShowModal(false);
if (onConnectSocials) onConnectSocials();
else window.open(postizUrl || 'https://postiz.pbento.pt', '_blank', 'noopener');
else if (postizUrl) window.open(postizUrl, '_blank', 'noopener');
};
// Initialize/Reset form when modal opens
@ -275,9 +221,9 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
// Only preselect platforms the profile can actually publish to.
if (knownConnections) {
setPlatforms({
tiktok: connectedPlatforms.includes('tiktok'),
instagram: connectedPlatforms.includes('instagram'),
youtube: connectedPlatforms.includes('youtube'),
tiktok: normalizedConnections.includes('tiktok'),
instagram: normalizedConnections.includes('instagram'),
youtube: normalizedConnections.includes('youtube'),
});
}
}
@ -658,8 +604,8 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
}
};
// Publishing needs the Postiz key; clipping does not.
const canPost = !!postizKey;
// Publishing needs both the Postiz base URL and API key; clipping does not.
const canPost = !!postizKey && !!postizUrl;
const handlePost = async () => {
if (!canPost) {
@ -734,12 +680,6 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
}
};
// Browser-rendered previews (Remotion) live in a blob: URL that exists only
// in this tab, so they always win over the durable copy.
const playbackUrl = (durableSrc && !durableFailed && !String(currentVideoUrl || '').startsWith('blob:'))
? durableSrc
: currentVideoUrl;
const durationReadout = formatDuration(clip);
return (
@ -752,29 +692,14 @@ export default function ResultCard({ clip, index, jobId, durable, postizKey, pos
<div className="w-full max-w-[calc(64vh*0.5625)] md:max-w-none mx-auto md:mx-0 md:w-[236px] bg-black relative shrink-0 aspect-[9/16] md:aspect-auto group/video">
<video
ref={videoRef}
src={playbackUrl}
src={currentVideoUrl}
controls
className="w-full h-full object-contain"
playsInline
onLoadedMetadata={(e) => {
if (e.target.videoWidth) setResolution(`${e.target.videoWidth}×${e.target.videoHeight}`);
}}
onError={() => {
// The durable copy is unreachable (signature expired after an
// hour on an idle tab, object purged) → serve from the API for
// the rest of this card's life.
if (playbackUrl === durableSrc) {
setDurableFailed(true);
return;
}
// Local /videos/ file gone (e.g. cleaned up after a reload) →
// fall back to the durable copy if one is available. If the
// durable URL hasn't loaded yet, the effect above retries.
if (durable?.url && currentVideoUrl !== durable.url) setCurrentVideoUrl(durable.url);
else setVideoErrored(true);
}}
onPlay={() => {
setHasPlayed(true);
const currentTime = videoRef.current ? videoRef.current.currentTime : 0;
onPlay && onPlay(clip.start + currentTime);
}}

View file

@ -375,7 +375,7 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
// --- Publish to YouTube ---
const handlePublish = async () => {
if (!postizKey) return alert('Please configure your Postiz base URL and API key in Settings first.');
if (!postizUrl || !postizKey) return alert('Please configure your Postiz base URL and API key in Settings first.');
const finalTitle = selectedTitle || manualTitle;
if (!finalTitle) return alert('No title selected.');
if (!selectedThumbnail) return alert('Please select a thumbnail first.');
@ -1138,7 +1138,7 @@ export default function ThumbnailStudio({ geminiApiKey, postizKey, postizUrl, on
</div>
{/* Publish Button */}
{!postizKey ? (
{!postizKey || !postizUrl ? (
<div className="glass-panel p-6 space-y-3">
<div className="flex items-center gap-2 text-warn">
<AlertCircle size={16} />

View file

@ -14,7 +14,7 @@ function Root() {
const hash = window.location.hash || '';
if (hash === '#legal') return 'legal';
// #landing = explicit landing view (app logo); section anchors keep the landing mounted
if (['#landing', '#features', '#how-it-works', '#pricing', '#comparison', '#faq'].includes(hash)) return 'landing';
if (['#landing', '#features', '#how-it-works', '#comparison', '#faq'].includes(hash)) return 'landing';
if (hash === '#app' || hash.startsWith('#app?') || localStorage.getItem('openshorts_skip_landing') === '1') return 'app';
return 'landing';
};

View file

@ -49,7 +49,6 @@ La retención de fotos de actor se retiró con la función de vídeo UGC
| Qué | Plazo | Dónde |
|---|---|---|
| Token de sesión (JWT) | 30 días o hasta cerrar sesión | `dashboard/src/lib/api.js` |
| Token de medios (para descargar tus propios clips) | 12 h, se renueva solo | `dashboard/src/lib/mediaToken.js`, `MEDIA_TOKEN_TTL_SECONDS` |
| Decisión sobre cookies | Hasta que la cambies, o hasta que cambie la versión del banner | `dashboard/src/lib/consent.js` |
| Preferencias de interfaz, atribución de primera visita | Hasta que borres los datos del sitio | `dashboard/src/lib/attribution.js` |
| Claves BYOK de proveedores de IA y de Postiz | Hasta que las borres. **Ofuscadas, no cifradas** | `dashboard/src/App.jsx` |

View file

@ -4,9 +4,11 @@ Two importable workflows, from a one-shot clipper to a channel watcher.
Both run against a self-hosted OpenShorts instance (point them at your base URL,
default `http://localhost:8000`) and publish through a self-hosted
[Postiz](https://postiz.pbento.pt/) instance. No API key is required on a
self-hosted instance, but the server needs a Google Gemini key for the AI
stages, and Postiz needs the target channels connected.
[Postiz](https://postiz.com/) instance. No OpenShorts API key is required, but
the server needs a Google Gemini key for the AI stages, and Postiz needs the
target channels connected. The publishing, queue and analytics calls need the
instance configured with `POSTIZ_URL` / `POSTIZ_API_KEY` (or an `X-Postiz-Key`
header sent per request); the workflow nodes hold no credential of their own.
| Workflow | What it does | Credentials |
|---|---|---|
@ -49,9 +51,9 @@ stages, and Postiz needs the target channels connected.
Postiz. Approve five clips today, fill five days of content. The slot comes
from the queue the server actually holds (`GET /api/postiz/scheduled`), so
two clips approved seconds apart cannot book the same one.
4. **Sunday digest** — the machine reads the analytics of what it published
(`GET /api/postiz/analytics/*`) and reports total impressions, per-platform
split, and your best post of the week.
4. **Sunday digest** — once a week it lists the channels connected in Postiz
(`GET /api/postiz/integrations`) and reports each channel's impressions over
the last 7 days (`GET /api/postiz/analytics?integration=<id>&days=7`).
Machine-specific setup, all inside sticky notes on the canvas:
@ -76,7 +78,7 @@ mechanism (see act 3).
"job_id": "…",
"status": "completed",
"clips": [
{ "index": 0, "title": "…", "video_url": "…", "download_url": "…" }
{ "index": 0, "title": "…", "video_url": "…" }
]
}
```
@ -84,7 +86,9 @@ mechanism (see act 3).
Failed jobs fire the same webhook with `"event": "job.failed"` and an `error`
field, so the flow never hangs waiting.
`download_url` is a 24-hour presigned link to the archived clip.
Each `video_url` is relative to your instance unless the server sets
`PUBLIC_API_URL`; point it at a host Telegram can reach (a `localhost` instance
is not reachable from Telegram's servers).
## Publishing and analytics API
@ -92,6 +96,7 @@ Direct posting: `POST /api/postiz/post` (accepts `scheduled_date`, ISO-8601).
Connected channels: `GET /api/postiz/integrations`.
Publishing queue: `GET /api/postiz/scheduled`, and
`DELETE /api/postiz/scheduled/{id}` to cancel one before it goes out.
Analytics of what you published: `GET /api/postiz/analytics` (channel totals)
and `GET /api/postiz/analytics/posts` (per-post metrics).
Analytics: `GET /api/postiz/analytics?integration=<id>&days=7` (one channel) and
`GET /api/postiz/analytics/posts?post_id=<id>&days=7` (one post) — both the
channel and the post id are required.
Full API reference: `/docs` (OpenAPI) on your instance.

View file

@ -3,7 +3,7 @@
"nodes": [
{
"parameters": {
"content": "## OpenShorts + n8n, the whole loop\n\n**One HTTP request starts the job, one signed webhook ends it.** No polling loop, no wait nodes.\n\n### Setup (3 steps)\n1. Point the *Start OpenShorts job* node at your self-hosted instance (`http://localhost:8000`); no API key is needed on a self-hosted instance.\n2. Open the *Clips ready* webhook node, copy its **production** URL, and paste it as `webhook_url` in the *Start OpenShorts job* node body.\n3. Optional: set your own `webhook_secret`. OpenShorts signs the body with HMAC-SHA256 in the `X-OpenShorts-Signature` header (`sha256=<hex>`), so you can verify the sender.\n\n### What you get back\n`event`, `job_id`, `status`, and `clips[]` with `title`, `video_url` and a 24h `download_url` per clip. Failed jobs also fire the webhook with an `error` field, so the flow never hangs.\n\nAPI docs: http://localhost:8000/docs \u00b7 Self-hosted works the same on your own machine (MIT).",
"content": "## OpenShorts + n8n, the whole loop\n\n**One HTTP request starts the job, one signed webhook ends it.** No polling loop, no wait nodes.\n\n### Setup (3 steps)\n1. Point the *Start OpenShorts job* node at your self-hosted instance (`http://localhost:8000`); no API key is needed on a self-hosted instance.\n2. Open the *Clips ready* webhook node, copy its **production** URL, and paste it as `webhook_url` in the *Start OpenShorts job* node body.\n3. Optional: set your own `webhook_secret`. OpenShorts signs the body with HMAC-SHA256 in the `X-OpenShorts-Signature` header (`sha256=<hex>`), so you can verify the sender.\n\n### What you get back\n`event`, `job_id`, `status`, and `clips[]` with `title` and `video_url` per clip. Failed jobs also fire the webhook with an `error` field, so the flow never hangs.\n\nAPI docs: http://localhost:8000/docs \u00b7 Self-hosted works the same on your own machine (MIT).",
"height": 460,
"width": 480
},
@ -43,8 +43,6 @@
"parameters": {
"method": "POST",
"url": "http://localhost:8000/api/process",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={\n \"url\": \"{{ $json['Video URL'] }}\",\n \"acknowledged\": true,\n \"webhook_url\": \"PASTE_THE_PRODUCTION_URL_OF_THE_CLIPS-READY_WEBHOOK_NODE_HERE\",\n \"webhook_secret\": \"change-me\"\n}",
@ -57,12 +55,7 @@
"position": [
180,
0
],
"credentials": {
"httpHeaderAuth": {
"name": "OpenShorts API key"
}
}
]
},
{
"parameters": {
@ -167,8 +160,8 @@
},
{
"id": "b2",
"name": "download_url",
"value": "={{ $json.download_url || $json.video_url }}",
"name": "video_url",
"value": "={{ $json.video_url }}",
"type": "string"
}
]

View file

@ -19,7 +19,7 @@
},
{
"parameters": {
"content": "## ACT 1 \u2014 Watch the channel (daily)\n\nOnce a day this branch reads your channel's RSS feed and picks **one** video to clip: a new upload if there is one, otherwise the next unprocessed video from your back catalog (newest first). One video per day keeps your quota burn predictable.\n\n**Setup**: put your channel id in the *Channel RSS feed* node (`https://www.youtube.com/feeds/videos.xml?channel_id=UC...`). Find it at youtube.com \u2192 your channel \u2192 About \u2192 Share \u2192 Copy channel ID.\n\nIf OpenShorts answers 402 (out of minutes) the machine pauses and tells you on Telegram instead of failing silently.",
"content": "## ACT 1 \u2014 Watch the channel (daily)\n\nOnce a day this branch reads your channel's RSS feed and picks **one** video to clip: a new upload if there is one, otherwise the next unprocessed video from your back catalog (newest first). One video per day keeps your quota burn predictable.\n\n**Setup**: put your channel id in the *Channel RSS feed* node (`https://www.youtube.com/feeds/videos.xml?channel_id=UC...`). Find it at youtube.com \u2192 your channel \u2192 About \u2192 Share \u2192 Copy channel ID.\n\nIf OpenShorts rejects the job, the machine tells you on Telegram instead of failing silently, and the video is retried tomorrow.",
"height": 420,
"width": 400,
"color": 7
@ -84,8 +84,6 @@
"parameters": {
"method": "POST",
"url": "http://localhost:8000/api/process",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={\n \"url\": \"{{ $json.url }}\",\n \"acknowledged\": true,\n \"webhook_url\": \"PASTE_THE_PRODUCTION_URL_OF_THE_CLIPS-READY_WEBHOOK_NODE_HERE\",\n \"webhook_secret\": \"change-me\"\n}",
@ -99,12 +97,7 @@
660,
0
],
"onError": "continueErrorOutput",
"credentials": {
"httpHeaderAuth": {
"name": "OpenShorts API key"
}
}
"onError": "continueErrorOutput"
},
{
"parameters": {
@ -146,7 +139,7 @@
"additionalFields": {}
},
"id": "tg-quota",
"name": "Notify: out of minutes",
"name": "Notify: submit failed",
"type": "n8n-nodes-base.telegram",
"typeVersion": 1.2,
"position": [
@ -161,7 +154,7 @@
},
{
"parameters": {
"content": "## ACT 2 \u2014 Clips arrive on your phone\n\n**No polling, no Wait-node loop.** OpenShorts calls this webhook once per job (success **and** failure, so nothing ever hangs). Each finished 9:16 clip lands in your Telegram with two buttons: \u2705 publish or \u274c skip \u2014 a human approves every post, which is also what keeps you on the right side of YouTube's inauthentic-content policy.\n\n**Setup**: copy the **production** URL of the *Clips ready* webhook node and paste it as `webhook_url` inside *Start OpenShorts job*. Telegram fetches videos by URL up to ~20 MB; bigger clips fall back to a message with the download link and the same buttons.",
"content": "## ACT 2 \u2014 Clips arrive on your phone\n\n**No polling, no Wait-node loop.** OpenShorts calls this webhook once per job (success **and** failure, so nothing ever hangs). Each finished 9:16 clip lands in your Telegram with two buttons: \u2705 publish or \u274c skip \u2014 a human approves every post, which is also what keeps you on the right side of YouTube's inauthentic-content policy.\n\n**Setup**: copy the **production** URL of the *Clips ready* webhook node and paste it as `webhook_url` inside *Start OpenShorts job*. Telegram fetches videos by URL up to ~20 MB; bigger clips fall back to a message with the clip URL and the same buttons.",
"height": 380,
"width": 400,
"color": 7
@ -225,7 +218,7 @@
},
{
"parameters": {
"jsCode": "// One Telegram message per clip, carrying everything the approval\n// buttons need inside callback_data (Telegram caps it at 64 bytes:\n// action|job_id|clip_index fits).\nconst body = $json.body;\nreturn (body.clips || []).map((clip, i) => ({\n json: {\n job_id: body.job_id,\n clip_index: i,\n title: clip.title || `Clip ${i + 1}`,\n download_url: clip.download_url || clip.video_url,\n },\n}));"
"jsCode": "// One Telegram message per clip, carrying everything the approval\n// buttons need inside callback_data (Telegram caps it at 64 bytes:\n// action|job_id|clip_index fits).\nconst body = $json.body;\nconst base = 'http://localhost:8000';\nreturn (body.clips || []).map((clip, i) => ({\n json: {\n job_id: body.job_id,\n clip_index: i,\n title: clip.title || `Clip ${i + 1}`,\n // The webhook returns a path relative to the instance unless the server\n // sets PUBLIC_API_URL; make it absolute so Telegram can fetch it.\n video_url: clip.video_url && clip.video_url.startsWith('/')\n ? base + clip.video_url\n : clip.video_url,\n },\n}));"
},
"id": "split-clips",
"name": "One item per clip",
@ -240,7 +233,7 @@
"parameters": {
"operation": "sendVideo",
"chatId": "={{ $('Settings (clips)').first().json.telegram_chat_id }}",
"file": "={{ $json.download_url }}",
"file": "={{ $json.video_url }}",
"replyMarkup": "inlineKeyboard",
"inlineKeyboard": {
"rows": [
@ -286,7 +279,7 @@
{
"parameters": {
"chatId": "={{ $('Settings (clips)').first().json.telegram_chat_id }}",
"text": "=\ud83c\udfac {{ $json.title }}\n\nToo big for Telegram preview \u2014 watch it here:\n{{ $json.download_url }}",
"text": "=\ud83c\udfac {{ $json.title }}\n\nToo big for Telegram preview \u2014 watch it here:\n{{ $json.video_url }}",
"replyMarkup": "inlineKeyboard",
"inlineKeyboard": {
"rows": [
@ -431,7 +424,7 @@
},
{
"parameters": {
"jsCode": "// One post per day, derived from the queue the server actually holds.\n// Workflow static data was the obvious place to remember the last slot, but\n// two approvals tapped seconds apart run as two executions that both read the\n// old value and book the SAME slot. The scheduled list is shared state, so\n// counting it cannot race with itself in that way.\nconst queue = $input.first().json.scheduled_posts || [];\nconst item = $('Parse button').first().json;\nconst DAY = 24 * 60 * 60 * 1000;\nconst taken = queue\n .map((p) => Date.parse(p.scheduled_date))\n .filter((t) => !Number.isNaN(t))\n .sort((a, b) => a - b);\nlet slot = Date.now() + 10 * 60 * 1000; // never schedule in the past\nfor (const t of taken) {\n if (Math.abs(t - slot) < DAY) slot = t + DAY;\n}\nreturn [{ json: { ...item, scheduled_date: new Date(slot).toISOString() } }];"
"jsCode": "// One post per day, derived from the queue the server actually holds.\n// Workflow static data was the obvious place to remember the last slot, but\n// two approvals tapped seconds apart run as two executions that both read the\n// old value and book the SAME slot. The scheduled list is shared state, so\n// counting it cannot race with itself in that way.\nconst queue = $input.first().json.scheduled_posts || [];\nconst item = $('Parse button').first().json;\nconst DAY = 24 * 60 * 60 * 1000;\nconst taken = queue\n .map((p) => Date.parse(p.scheduled_date || p.publishDate || p.date))\n .filter((t) => !Number.isNaN(t))\n .sort((a, b) => a - b);\nlet slot = Date.now() + 10 * 60 * 1000; // never schedule in the past\nfor (const t of taken) {\n if (Math.abs(t - slot) < DAY) slot = t + DAY;\n}\nreturn [{ json: { ...item, scheduled_date: new Date(slot).toISOString() } }];"
},
"id": "reserve-slot",
"name": "Pick next free slot",
@ -446,8 +439,6 @@
"parameters": {
"method": "POST",
"url": "http://localhost:8000/api/postiz/post",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={\n \"job_id\": \"{{ $json.job_id }}\",\n \"clip_index\": {{ $json.clip_index }},\n \"platforms\": [\"tiktok\", \"instagram\", \"youtube\"],\n \"scheduled_date\": \"{{ $json.scheduled_date }}\",\n \"timezone\": \"UTC\"\n}",
@ -461,12 +452,7 @@
1020,
840
],
"onError": "continueErrorOutput",
"credentials": {
"httpHeaderAuth": {
"name": "OpenShorts API key"
}
}
"onError": "continueErrorOutput"
},
{
"parameters": {
@ -491,7 +477,7 @@
{
"parameters": {
"chatId": "={{ $('Parse button').first().json.chat_id }}",
"text": "=\u26a0\ufe0f Could not schedule that clip: {{ $json.error && $json.error.message ? $json.error.message : 'posting failed' }}. Make sure your social accounts are connected in your OpenShorts account page.",
"text": "=\u26a0\ufe0f Could not schedule that clip: {{ $json.error && $json.error.message ? $json.error.message : 'posting failed' }}. Make sure your social accounts are connected in your Postiz instance and POSTIZ_URL / POSTIZ_API_KEY are set on the server.",
"additionalFields": {}
},
"id": "tg-post-failed",
@ -530,7 +516,7 @@
},
{
"parameters": {
"content": "## ACT 4 \u2014 The feedback loop: learn what worked\n\nOnce a week the machine reads the analytics of everything it published (via the OpenShorts analytics API, which aggregates TikTok/Instagram/YouTube numbers) and sends you the verdict: total impressions, per-platform split, and your best post.\n\nThe machine that posts is the machine that measures \u2014 so every approval you make next week is informed by what actually landed. Close the loop further by feeding your winners back as examples in your clip prompts.",
"content": "## ACT 4 \u2014 The feedback loop: learn what worked\n\nOnce a week the machine lists the channels connected in Postiz (`GET /api/postiz/integrations`) and asks for each channel's analytics over the last 7 days (`GET /api/postiz/analytics?integration=<id>&days=7`), then sends you the totals. The analytics endpoint takes one integration id at a time, so the workflow loops over the channels the instance holds. The server needs `POSTIZ_URL` / `POSTIZ_API_KEY` (or per-request `X-Postiz-Key` headers) for these calls.\n\nThe machine that posts is the machine that measures \u2014 so every approval you make next week is informed by what actually landed.",
"height": 340,
"width": 400,
"color": 7
@ -569,71 +555,51 @@
},
{
"parameters": {
"url": "http://localhost:8000/api/postiz/analytics?date=7",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendQuery": true,
"queryParameters": {
"parameters": [
{
"name": "period",
"value": "last_week"
},
{
"name": "breakdown",
"value": "true"
}
]
},
"method": "GET",
"url": "http://localhost:8000/api/postiz/integrations",
"options": {}
},
"id": "weekly-impressions",
"name": "Weekly impressions",
"id": "weekly-channels",
"name": "List channels",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
200,
1360
],
"credentials": {
"httpHeaderAuth": {
"name": "OpenShorts API key"
}
}
]
},
{
"parameters": {
"url": "http://localhost:8000/api/postiz/analytics/posts",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"sendQuery": true,
"queryParameters": {
"parameters": [
{
"name": "since",
"value": "={{ $now.minus({ days: 7 }).toFormat('yyyy-MM-dd') }}"
}
]
},
"fieldToSplitOut": "integrations",
"options": {}
},
"id": "weekly-posts",
"name": "Per-post metrics",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"id": "split-channels",
"name": "One item per channel",
"type": "n8n-nodes-base.splitOut",
"typeVersion": 1,
"position": [
360,
1360
],
"credentials": {
"httpHeaderAuth": {
"name": "OpenShorts API key"
}
}
]
},
{
"parameters": {
"jsCode": "// Turn the two analytics responses into one human digest message.\nconst impressions = $('Weekly impressions').first().json || {};\nconst postsResp = $input.first().json || {};\nconst posts = postsResp.posts || postsResp.data || postsResp.items || [];\n\nconst views = (post) => {\n const m = post.post_metrics || post.metrics || post;\n return Number(m.views || m.impressions || m.plays || 0);\n};\n\nconst total = impressions.total_impressions || posts.reduce((s, p) => s + views(p), 0);\nconst sorted = [...posts].sort((a, b) => views(b) - views(a));\nconst best = sorted[0];\n\nconst perPlatform = impressions.per_platform\n ? Object.entries(impressions.per_platform)\n .map(([p, v]) => ` \u2022 ${p}: ${Number(v).toLocaleString('en-US')}`)\n .join('\\n')\n : '';\n\nlet text = `\ud83d\udcca Your week\\n\\n`;\ntext += `Posts published: ${posts.length}\\n`;\ntext += `Total impressions: ${Number(total).toLocaleString('en-US')}\\n`;\nif (perPlatform) {\n text += `${perPlatform}\\n`;\n}\nif (best && views(best) > 0) {\n const title = best.title || best.caption || best.platform_post_id || 'your top post';\n text += `\\n\ud83c\udfc6 Best post: \"${title}\" \u2014 ${views(best).toLocaleString('en-US')} views`;\n}\nif (posts.length === 0) {\n text += `\\nNothing published this week. Approve some clips and the machine does the rest.`;\n}\nreturn [{ json: { digest: text } }];"
"method": "GET",
"url": "=http://localhost:8000/api/postiz/analytics?integration={{ $json.id }}&days=7",
"options": {}
},
"id": "weekly-impressions",
"name": "Channel analytics",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
520,
1360
]
},
{
"parameters": {
"jsCode": "// One analytics response per connected channel (the endpoint takes a single\n// integration id, so the workflow asks once per channel).\nconst channels = $('One item per channel').all().map((i) => i.json);\nconst responses = $('Channel analytics').all().map((i) => i.json);\n\nconst metricValue = (body) => {\n const m = body.metrics || body.post_metrics || body.analytics || body;\n const v = m.views ?? m.impressions ?? m.plays ?? m.reach ?? 0;\n return Number(v) || 0;\n};\n\nlet total = 0;\nconst lines = channels.map((ch, i) => {\n const value = metricValue(responses[i] || {});\n total += value;\n const label = ch.identifier || ch.name || ch.id || `channel ${i + 1}`;\n return ` \u2022 ${label}: ${value.toLocaleString('en-US')}`;\n});\n\nlet text = `\ud83d\udcca Your week\\n\\n`;\nif (channels.length === 0) {\n text += 'No channels connected in Postiz yet. Connect one and rerun.';\n} else {\n text += `Connected channels: ${channels.length}\\n`;\n text += `Totals (last 7 days): ${total.toLocaleString('en-US')}\\n`;\n text += lines.join('\\n') + '\\n';\n}\nreturn [{ json: { digest: text } }];"
},
"id": "write-digest",
"name": "Write the digest",
@ -667,8 +633,6 @@
{
"parameters": {
"url": "http://localhost:8000/api/postiz/scheduled",
"authentication": "genericCredentialType",
"genericAuthType": "httpHeaderAuth",
"options": {}
},
"id": "read-queue",
@ -678,12 +642,7 @@
"position": [
580,
840
],
"credentials": {
"httpHeaderAuth": {
"name": "OpenShorts API key"
}
}
]
},
{
"parameters": {
@ -807,7 +766,7 @@
],
[
{
"node": "Notify: out of minutes",
"node": "Notify: submit failed",
"type": "main",
"index": 0
}
@ -946,28 +905,6 @@
]
]
},
"Weekly impressions": {
"main": [
[
{
"node": "Per-post metrics",
"type": "main",
"index": 0
}
]
]
},
"Per-post metrics": {
"main": [
[
{
"node": "Write the digest",
"type": "main",
"index": 0
}
]
]
},
"Write the digest": {
"main": [
[
@ -1027,7 +964,40 @@
"main": [
[
{
"node": "Weekly impressions",
"node": "List channels",
"type": "main",
"index": 0
}
]
]
},
"List channels": {
"main": [
[
{
"node": "One item per channel",
"type": "main",
"index": 0
}
]
]
},
"One item per channel": {
"main": [
[
{
"node": "Channel analytics",
"type": "main",
"index": 0
}
]
]
},
"Channel analytics": {
"main": [
[
{
"node": "Write the digest",
"type": "main",
"index": 0
}
@ -1039,4 +1009,4 @@
"executionOrder": "v1"
},
"pinData": {}
}
}

View file

@ -1,47 +1,21 @@
"""Capability tokens and path rules for the ``/videos`` and ``/thumbnails`` bytes.
"""Path rules for the ``/videos`` bytes: what these prefixes may ever serve.
Both paths used to be ``StaticFiles`` mounts, i.e. the whole working directory
served to the internet with a UUID for a lock. That handed out more than the
clips: the ``.resume.json`` manifest (which carries the customer's own
This fork is single-tenant / self-host with no accounts, so there is no token
or URL-signing layer here: the only access rule is this allowlist.
``/videos`` used to be a plain ``StaticFiles`` mount over the working
directory, so anyone holding a job id (it travels in every clip URL) could also
fetch the ``.resume.json`` manifest (which carries the customer's own
``webhook_secret``), the ``.owner`` sidecar (a user uuid), the ``.instance``
deploy marker, the face crops under ``thumbnails/`` and every actor photo a user
had uploaded. ``app.py`` now serves those two prefixes through real handlers
that ask who is calling; this module is the part of that with no FastAPI in it,
so the URL-signing call sites in ``app.py`` need no FastAPI import.
deploy marker, the face crops under ``thumbnails/`` and ``<title>_metadata.json``
(the full transcript of the user's video).
Two token shapes, because there are two kinds of consumer:
* **path capability** (``?exp=…&sig=…``) — an HMAC over one relative path and an
expiry. This is what goes to a consumer that cannot send a header at all: the
webhook payload and the absolute URLs the MCP tools return. Same idea as the
R2 ``presigned_get`` links the history endpoint already hands out, and as
``/api/source-url``.
* **user token** (``?mt=<uid>.<exp>.<sig>``) — a short-lived bearer for one
user, minted at ``/api/media-token``. A ``<video src>`` or ``<img src>``
cannot carry an ``Authorization`` header, so the dashboard appends this to
every media URL it builds (one place: ``getApiUrl``) instead of leaking the
30-day session JWT into query strings, access logs and referrers.
A request that arrives with an ordinary ``Authorization: Bearer`` / ``X-API-Key``
header (agents, ``curl``, the MCP client) needs neither: ``app.py`` resolves the
user from the header and compares it to the owner directly.
``normalise_relpath`` rejects absolute paths, traversal and every dot-segment;
``is_servable`` additionally requires a deliverable extension. ``app.py`` wraps
both in ``_media_guard`` and installs it as the ``guard`` on the ``/videos``
mount.
"""
from __future__ import annotations
import hashlib
import hmac
import os
import posixpath
import time
from typing import Optional
# A signed media link has to outlive the page that was handed it. Local working
# files are swept after an hour anyway (JOB_RETENTION_SECONDS), so the ceiling
# here is about the link, not the file.
MEDIA_URL_TTL_SECONDS = int(os.environ.get("MEDIA_URL_TTL_SECONDS", "86400"))
# The dashboard's per-user media token. Deliberately much shorter than the
# session JWT (30 days): it travels in URLs, so it must die quickly.
MEDIA_TOKEN_TTL_SECONDS = int(os.environ.get("MEDIA_TOKEN_TTL_SECONDS", "43200"))
# Nothing outside this list is a deliverable: the working directories also hold
# transcripts, metadata JSON, resume manifests and ownership sidecars, and an
@ -91,98 +65,3 @@ def is_servable(rel_path: str) -> bool:
except MediaPathError:
return False
return posixpath.splitext(cleaned)[1].lower() in SERVABLE_EXTENSIONS
def _digest(secret: str, message: str) -> str:
return hmac.new((secret or "").encode(), message.encode(),
hashlib.sha256).hexdigest()[:32]
# --- path capability -------------------------------------------------------
def path_signature(rel_path: str, exp: int, secret: str) -> str:
"""HMAC tying one relative media path to an expiry."""
return _digest(secret, f"media:{normalise_relpath(rel_path)}:{int(exp)}")
def sign_media_url(url_path: str, secret: str, ttl: Optional[int] = None) -> str:
"""Append ``?exp=…&sig=…`` to ``/videos/<rel>`` or ``/thumbnails/<rel>``.
Returns the URL untouched when there is no secret to sign with (self-host:
nothing to protect, and a signature keyed on "" would be theatre) or when
the path is not one of the two protected prefixes.
"""
if not secret or not url_path or "?" in url_path:
return url_path
rel = strip_media_prefix(url_path)
if rel is None:
return url_path
try:
exp = int(time.time()) + int(ttl or MEDIA_URL_TTL_SECONDS)
sig = path_signature(rel, exp, secret)
except MediaPathError:
return url_path
return f"{url_path}?exp={exp}&sig={sig}"
def verify_path_signature(rel_path: str, exp, sig: str, secret: str) -> bool:
"""Constant-time check of a path capability token."""
if not secret or not sig:
return False
try:
exp_i = int(exp)
except (TypeError, ValueError):
return False
if exp_i <= int(time.time()):
return False
try:
expected = path_signature(rel_path, exp_i, secret)
except MediaPathError:
return False
return hmac.compare_digest(sig, expected)
# --- per-user token --------------------------------------------------------
def mint_user_token(user_id, secret: str, ttl: Optional[int] = None) -> str:
"""``<uid>.<exp>.<sig>`` — a short-lived media bearer for one user."""
uid = str(user_id)
exp = int(time.time()) + int(ttl or MEDIA_TOKEN_TTL_SECONDS)
return f"{uid}.{exp}.{_digest(secret, f'mediatoken:{uid}:{exp}')}"
def verify_user_token(token: str, secret: str) -> Optional[str]:
"""Return the user id a media token proves, or None if it proves nothing."""
if not secret or not token or token.count(".") != 2:
return None
uid, exp_s, sig = token.split(".")
try:
exp = int(exp_s)
except ValueError:
return None
if exp <= int(time.time()):
return None
if not hmac.compare_digest(sig, _digest(secret, f"mediatoken:{uid}:{exp}")):
return None
return uid
# --- prefix helpers --------------------------------------------------------
MEDIA_PREFIXES = ("/videos/", "/thumbnails/")
def strip_media_prefix(url_path: str) -> Optional[str]:
"""``/videos/a/b.mp4`` -> ``videos-relative`` path, or None if not ours.
``/thumbnails/<x>`` is mounted on ``output/thumbnails`` while ``/videos/<x>``
is mounted on ``output``, so the returned path is relative to whichever base
the caller's prefix names — the signature only has to be stable, not to
describe the filesystem.
"""
if not url_path:
return None
for prefix in MEDIA_PREFIXES:
if url_path.startswith(prefix):
return prefix.strip("/") + "/" + url_path[len(prefix):]
return None

View file

@ -5,9 +5,11 @@ stay about request handling. Every function is blocking; call them through
``asyncio.to_thread`` from async handlers (video uploads are tens of seconds).
Auth is the RAW API key in the ``Authorization`` header -- NO ``Bearer`` prefix
(see /tmp/opencode/cleanup/postiz-api.md). The base URL defaults to the
``POSTIZ_URL`` env var and can be overridden per call; the API path prefix
``/api/public/v1`` is appended automatically when the caller passes a bare host.
(see /tmp/opencode/cleanup/postiz-api.md). There is deliberately no built-in
host: the base URL comes from the caller or the ``POSTIZ_URL`` env var, and a
request without one is refused instead of silently shipping the caller's key to
an instance we picked. The API path prefix ``/api/public/v1`` is appended
automatically when the caller passes a bare host.
"""
import os
@ -17,7 +19,6 @@ import httpx
_API_PREFIX = "/api/public/v1"
_DEFAULT_BASE = "https://postiz.pbento.pt"
# Postiz sniffs the MIME of /upload payloads: video must be video/mp4. We send
# the honest content type for the file extension rather than a blanket octet.
@ -47,7 +48,9 @@ class PostizError(Exception):
def _resolve_base(base: Optional[str]) -> str:
base = (base or os.environ.get("POSTIZ_URL") or _DEFAULT_BASE).strip().rstrip("/")
base = (base or os.environ.get("POSTIZ_URL") or "").strip().rstrip("/")
if not base:
raise PostizError(400, "Missing Postiz URL")
if base.endswith(_API_PREFIX):
return base
return base + _API_PREFIX
@ -72,7 +75,10 @@ def _mime_for(path: str) -> str:
def _handle(resp: httpx.Response) -> Any:
if resp.status_code not in (200, 201, 202):
raise PostizError(resp.status_code, f"Postiz API Error: {resp.text}")
# Truncate the upstream body: it can be an HTML error page or a stack
# trace, and PostizError.detail rides straight into our API response.
body = (resp.text or "")[:500]
raise PostizError(resp.status_code, f"Postiz API Error: {body}")
if resp.status_code == 204 or not resp.content:
return None
try:
@ -90,17 +96,6 @@ def list_integrations(base: Optional[str] = None, key: Optional[str] = None,
return data if isinstance(data, list) else (data or {}).get("integrations", []) or []
def list_integrations_settings(base: Optional[str], key: Optional[str],
integration_id: str,
timeout: float = 30.0) -> Dict[str, Any]:
"""Live schema/rules for one channel, to validate a post before sending it."""
with httpx.Client(timeout=timeout) as client:
resp = client.get(
f"{_resolve_base(base)}/integration-settings/{integration_id}",
headers=_headers(key))
return _handle(resp) or {}
def upload_media(base: Optional[str], key: Optional[str], path: str,
timeout: float = 600.0) -> Dict[str, Any]:
"""Upload a local file (multipart field ``file``) and return ``{id, path}``."""

View file

@ -1,20 +1,21 @@
"""Static file serving that can bring a job's files back before answering 404.
"""Static file serving for ``/videos`` that can refuse non-deliverables.
``OUTPUT_DIR`` is not durable: a redeploy or the hourly sweep wipes a
finished job, while the user's library still points at
``/videos/<job_id>/<file>``. The API endpoints re-pull a project from R2 on
demand (``app._ensure_job_files``), but ``/videos`` was a plain
``StaticFiles`` mount, so when the dashboard reopened a project it fired the
15 transcript requests (which restored the job, ~25 s for 2 GB) and the 15
``<video>`` loads at the same instant, and every player got a 404 that only
a reload fixed (job cff3ad6c, 6-sep-2026 00:37 UTC).
``/videos`` used to be a plain ``StaticFiles`` mount over ``OUTPUT_DIR``, which
served the whole working directory to anyone holding a job id: ``.owner`` (a
user uuid), ``.resume.json`` (the customer's own ``webhook_secret``),
``.transcript_checkpoint.json`` and the ``*_metadata.json`` carrying the full
transcript of the user's video. All four were verified served, unauthenticated,
on 7-sep-2026.
This subclass keeps everything StaticFiles does (Range requests, ETags, HEAD)
and adds one step: on a miss it hands the first path segment (the job id) to
``restorer``; when that reports the files may now be there, it looks once
more. The restorer is awaited on the request, so a player that arrives while
a restore is in flight simply waits for it (the per-job lock lives in the
restorer) instead of failing.
This subclass keeps everything ``StaticFiles`` does (Range requests, ETags,
HEAD) and adds one step before the filesystem: ``guard`` (the allowlist,
``media_auth.is_servable``, wrapped by ``app._media_guard``) refuses a path, and
a refused path looks exactly like a missing one. ``app.py`` mounts it with the
guard only -- there is no restorer in this fork.
The optional ``restorer`` hook predates the self-host fork: it let a miss ask a
job's durable copy (R2) to come back before answering 404. Nothing wires one up
any more; the parameter is kept because callers and tests may still pass one.
"""
from typing import Awaitable, Callable, Optional
@ -26,7 +27,7 @@ Guard = Callable[[str], bool]
class RestoringStaticFiles(StaticFiles):
"""StaticFiles that can restore a missing job, and refuses non-deliverables.
"""StaticFiles that refuses non-deliverables, with an optional restore hook.
``guard`` is the allowlist (``media_auth.is_servable``). Without it this
mount hands out the whole working directory to anyone holding the job id:
@ -37,10 +38,8 @@ class RestoringStaticFiles(StaticFiles):
This is only the path half of media_auth: the clips themselves, and the
untouched source video sitting in the same directory, are still public to
anyone who has the job id. Closing that needs the capability tokens the
module was written for, which is a bigger change (request handlers, an
/api/media-token endpoint, and the dashboard appending the token to every
media URL) and must ship with its frontend half.
anyone who has the job id. ``restorer`` is not wired up in this fork; see
the module docstring.
"""
def __init__(self, *args, restorer: Optional[Restorer] = None,

View file

@ -16,7 +16,7 @@ Run OpenShorts yourself with Docker and point the agent at the instance
on a self-hosted instance, but you do need a Google Gemini key in the server's
environment for the AI stages. The skill calls the REST API documented in
`reference.md`; publishing goes through your self-hosted
[Postiz](https://postiz.pbento.pt/) instance.
[Postiz](https://postiz.com/) instance.
## Install

View file

@ -40,7 +40,7 @@ settings from `GET /api/config` if you need to confirm them.
2. Finish: **webhooks beat polling.** With `webhook_url` set, OpenShorts POSTs
exactly once when the job ends (completed OR failed, so pipelines never
hang): `{"event": "job.completed", "job_id", "status", "clips": [{"index",
"title", "video_url", "download_url"}]}`. If a secret was set, verify
"title", "video_url"}]}`. If a secret was set, verify
`X-OpenShorts-Signature: sha256=<hex>` = HMAC-SHA256 of the raw body.
Without a webhook, poll `GET /api/status/{job_id}` every 30-60s; response is
`{"status", "logs", "result"}` and `result.clips` appears on completion.
@ -99,6 +99,7 @@ can trim, extend, drop a dead moment in the middle, or reorder. Pass
- Postiz must have the target channels connected; check
`GET /api/postiz/integrations` first and surface a clear error if a channel is
missing.
- `download_url` links are presigned for 24h: fetch or forward them promptly.
- Each clip's `video_url` is relative to the instance unless the server sets
`PUBLIC_API_URL`; resolve it against the API base before handing it on.
- OpenShorts is self-hosted, MIT-licensed and needs a machine plus your own
Gemini key. Do not describe it as a hosted or metered service.

View file

@ -69,12 +69,13 @@ Fired once per job, on success and on failure, so a flow never hangs:
"event": "job.completed",
"job_id": "0f0a...",
"status": "completed",
"clips": [ { "index": 0, "title": "...", "video_url": "...", "download_url": "..." } ]
"clips": [ { "index": 0, "title": "...", "video_url": "..." } ]
}
```
A failed job sends `"event": "job.failed"` with an `error` string and no clips.
`download_url` is a presigned link valid for 24 hours.
Each clip carries `video_url`, relative to the instance unless the server sets
`PUBLIC_API_URL`.
The URL must be public HTTPS; it is validated at submit time and re-resolved at
delivery time, so a URL that points at a private address is refused. With a

View file

@ -6,7 +6,6 @@
- A metered whole-video URL job carries SOURCE_CAP_MINUTES = the reserved
minutes, in the job env and in the resume manifest.
- main.py and the probe get an environment without the server secrets.
- The public /video/{id} page escapes everything it interpolates.
"""
import asyncio
import json
@ -118,24 +117,21 @@ def test_quality_probe_runs_after_metering(dirs, calls):
resp = _post_process({"url": "https://www.youtube.com/watch?v=ok", "acknowledged": True})
assert resp.status_code == 200, resp.text
assert calls["order"] == ["reserve", "probe"]
assert calls["released"] == []
def test_low_quality_confirmation_releases_the_reservation(dirs, calls):
def test_low_quality_confirmation_drops_the_unstarted_job(dirs, calls):
calls["probe_result"][0] = {"max_height": 360, "duration": 600}
resp = _post_process({"url": "https://www.youtube.com/watch?v=lowq", "acknowledged": True})
assert resp.status_code == 200
assert resp.json()["needs_confirmation"] is True
assert calls["released"] == ["res-1"]
assert os.listdir(dirs) == [] # no orphan job dir
assert app_module.jobs == {}
def test_short_source_rejection_releases_the_reservation(dirs, calls):
def test_short_source_rejection_drops_the_unstarted_job(dirs, calls):
calls["probe_result"][0] = {"max_height": 1080, "duration": 20}
resp = _post_process({"url": "https://www.youtube.com/watch?v=short", "acknowledged": True})
assert resp.status_code == 400
assert calls["released"] == ["res-1"]
assert os.listdir(dirs) == []
@ -233,28 +229,6 @@ def test_job_env_has_no_server_secrets(dirs, calls, monkeypatch):
assert env["GEMINI_API_KEY"] == "test-key"
# --------------------------------------------------------------------------- #
# /video/{id} escaping
# --------------------------------------------------------------------------- #
def test_video_page_escapes_everything(monkeypatch):
evil = '"><script>alert(1)</script>'
meta = {
"video_id": "v1", "title": "t", "caption": "c",
"video_url": "https://cdn.example.com/v.mp4" + evil,
"actor_url": "javascript:alert(1)",
"product_url": "javascript:alert(2)", "product_name": "p",
"hashtags": ["#ok", evil], "language": 'en"><script>',
"duration": 30, "cost_estimate": {"total": 1.0},
}
monkeypatch.setattr(app_module, "list_video_gallery", lambda n: [meta])
resp = _client_call("get", "/video/v1")
assert resp.status_code == 200
body = resp.text
assert "<script>alert(1)</script>" not in body
assert "javascript:" not in body
assert '<html lang="en">' in body
# --------------------------------------------------------------------------- #
# main.cap_source_duration(safety=True): the whole-video cap
# --------------------------------------------------------------------------- #

263
tests/test_postiz.py Normal file
View file

@ -0,0 +1,263 @@
"""Postiz client + publishing route hardening (Oracle backend review).
Covers the credential-exfil default removal (H1), the ``scheduled_date``
normalisation for the drip queue (H3), the disabled-channel refusal (M7) and
the error paths that used to 500 (M9). No network: the Postiz client functions
are stubbed with monkeypatch.
"""
import asyncio
import inspect
from datetime import datetime, timedelta
import httpx
import pytest
import postiz
POSTIZ_HEADERS = {"X-Postiz-Url": "https://postiz.example", "X-Postiz-Key": "k"}
def _app():
return pytest.importorskip("app")
# --- postiz.py -------------------------------------------------------------
class TestResolveBase:
def test_bare_host_gets_the_api_prefix(self):
assert postiz._resolve_base("https://p.example") == \
"https://p.example/api/public/v1"
def test_trailing_slash_is_trimmed(self):
assert postiz._resolve_base("https://p.example/") == \
"https://p.example/api/public/v1"
def test_existing_prefix_is_not_doubled(self):
assert postiz._resolve_base("https://p.example/api/public/v1") == \
"https://p.example/api/public/v1"
assert postiz._resolve_base("https://p.example/api/public/v1/") == \
"https://p.example/api/public/v1"
def test_env_fallback_used_when_no_argument(self, monkeypatch):
monkeypatch.setenv("POSTIZ_URL", "https://env.example/")
assert postiz._resolve_base(None) == "https://env.example/api/public/v1"
def test_missing_url_is_refused(self, monkeypatch):
monkeypatch.delenv("POSTIZ_URL", raising=False)
with pytest.raises(postiz.PostizError) as exc:
postiz._resolve_base(None)
assert exc.value.status_code == 400
assert "Missing Postiz URL" in exc.value.detail
def test_no_builtin_host_is_shipped(self):
# H1: the old silent default would ship a caller's key to a host we
# picked. It must not exist anywhere in the module.
assert "postiz.pbento.pt" not in inspect.getsource(postiz)
class TestHandle:
def test_success_returns_json(self):
assert postiz._handle(httpx.Response(200, json={"ok": True})) == {"ok": True}
def test_empty_body_is_none(self):
assert postiz._handle(httpx.Response(200, content=b"")) is None
def test_error_body_is_truncated(self):
with pytest.raises(postiz.PostizError) as exc:
postiz._handle(httpx.Response(500, text="x" * 5000))
assert exc.value.status_code == 500
assert "x" * 500 in exc.value.detail
assert "x" * 501 not in exc.value.detail
# --- app.py per-provider settings -----------------------------------------
class TestPostizSettings:
def test_tiktok_requires_a_posting_method(self):
s = _app()._postiz_settings("tiktok", "Title", "caption", [])
assert s["__type"] == "tiktok"
assert s["content_posting_method"] == "DIRECT_POST"
assert s["privacy_level"] == "PUBLIC_TO_EVERYONE"
def test_instagram_sets_post_type(self):
assert _app()._postiz_settings("instagram", "Title", "caption", []) == \
{"__type": "instagram", "post_type": "post"}
def test_youtube_sets_title_and_type(self):
s = _app()._postiz_settings("youtube", "My Short", "caption", ["tag"])
assert s["__type"] == "youtube"
assert s["type"] == "public"
assert s["title"] == "My Short"
assert s["tags"] == [{"value": "tag", "label": "tag"}]
def test_youtube_title_is_padded_to_the_minimum(self):
assert len(_app()._postiz_settings("youtube", "A", "caption", [])["title"]) >= 2
class TestIsoDate:
def test_naive_date_gets_the_timezone(self):
assert _app()._postiz_iso_date("2026-12-31T12:00:00", "UTC") == \
"2026-12-31T12:00:00.000Z"
def test_unscheduled_defaults_to_now(self):
out = _app()._postiz_iso_date(None, "UTC")
assert out.endswith("Z") and "T" in out
def test_unparseable_date_is_a_400(self):
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc:
_app()._postiz_iso_date("not-a-date", "UTC")
assert exc.value.status_code == 400
class TestScheduledNormalisation:
def test_scheduled_date_is_backfilled_without_dropping_raw_fields(self):
app = _app()
post = {"id": "p1", "date": "2026-12-31T12:00:00.000Z"}
out = app._normalise_postiz_post(post)
assert out["scheduled_date"] == "2026-12-31T12:00:00.000Z"
assert out["date"] == "2026-12-31T12:00:00.000Z"
assert out is not post
assert app._normalise_postiz_post(
{"id": "p2", "scheduledDate": "2026-01-02T00:00:00.000Z"}
)["scheduled_date"] == "2026-01-02T00:00:00.000Z"
assert app._normalise_postiz_post(
{"id": "p3", "scheduled_date": "kept"})["scheduled_date"] == "kept"
# --- /api/postiz/post request builder -------------------------------------
@pytest.fixture()
def publish_env(tmp_path, monkeypatch):
app = _app()
out = tmp_path / "output"
job_dir = out / "job1"
job_dir.mkdir(parents=True)
(job_dir / "clip_1.mp4").write_bytes(b"video")
monkeypatch.setattr(app, "OUTPUT_DIR", str(out))
monkeypatch.setattr(app, "jobs", {
"job1": {"result": {"clips": [{
"video_url": "/videos/job1/clip_1.mp4",
"title": "Clip title",
"video_description_for_instagram": "caption #one",
}]}}
})
return app
@pytest.fixture()
def stubbed(monkeypatch):
calls = {"order": [], "integrations": []}
def list_integrations(base, key, *a, **k):
calls["order"].append("list")
calls["base"] = base
return calls["integrations"]
def upload_media(base, key, path, *a, **k):
calls["order"].append("upload")
calls["uploaded"] = path
return {"id": "media-1", "path": "media/path"}
def create_post(base, key, payload, *a, **k):
calls["order"].append("create")
calls["payload"] = payload
return [{"postId": "p1", "integration": "x"}]
monkeypatch.setattr(postiz, "list_integrations", list_integrations)
monkeypatch.setattr(postiz, "upload_media", upload_media)
monkeypatch.setattr(postiz, "create_post", create_post)
return calls
def _call(app, method, path, **kw):
async def _do():
transport = httpx.ASGITransport(app=app.app)
async with httpx.AsyncClient(transport=transport,
base_url="http://testserver") as c:
return await getattr(c, method)(path, **kw)
return asyncio.run(_do())
def _post(app, payload, headers=POSTIZ_HEADERS):
return _call(app, "post", "/api/postiz/post", json=payload, headers=headers)
def test_builder_targets_each_integration_and_uploads_first(publish_env, stubbed):
stubbed["integrations"] = [
{"id": "i-tt", "identifier": "tiktok", "disabled": False},
{"id": "i-yt", "identifier": "youtube"},
]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"platforms": ["tiktok", "youtube"], "title": "My Title"})
assert r.status_code == 200, r.text
assert stubbed["order"] == ["list", "upload", "create"]
payload = stubbed["payload"]
assert [p["integration"]["id"] for p in payload["posts"]] == ["i-tt", "i-yt"]
assert [p["settings"]["__type"] for p in payload["posts"]] == ["tiktok", "youtube"]
assert payload["posts"][0]["value"][0]["image"][0]["id"] == "media-1"
assert payload["shortLink"] is False and payload["type"] == "now"
assert stubbed["uploaded"].endswith("clip_1.mp4")
def test_disabled_integration_is_refused(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-yt", "identifier": "youtube", "disabled": True}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["youtube"]})
assert r.status_code == 400
assert "Disabled" in r.json()["detail"]
assert "upload" not in stubbed["order"] and "create" not in stubbed["order"]
def test_missing_integration_is_refused(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["instagram"]})
assert r.status_code == 400
assert "Not connected" in r.json()["detail"]
assert "upload" not in stubbed["order"]
def test_clip_without_video_url_is_400_not_500(publish_env, stubbed):
publish_env.jobs["job1"]["result"]["clips"] = [{"title": "no url"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok"]})
assert r.status_code == 400
assert "video_url" in r.json()["detail"]
def test_missing_url_or_key_is_a_400(publish_env, stubbed, monkeypatch):
monkeypatch.delenv("POSTIZ_URL", raising=False)
monkeypatch.delenv("POSTIZ_API_KEY", raising=False)
body = {"job_id": "job1", "clip_index": 0, "platforms": ["tiktok"]}
r = _post(publish_env, body, headers={"X-Postiz-Key": "k"})
assert r.status_code == 400 and "URL" in r.json()["detail"]
r = _post(publish_env, body, headers={"X-Postiz-Url": "https://p.example"})
assert r.status_code == 400 and "key" in r.json()["detail"].lower()
def test_bad_scheduled_date_is_a_400(publish_env, stubbed):
stubbed["integrations"] = [{"id": "i-tt", "identifier": "tiktok"}]
r = _post(publish_env, {"job_id": "job1", "clip_index": 0,
"platforms": ["tiktok"], "scheduled_date": "tomorrow"})
assert r.status_code == 400
def test_scheduled_window_is_widened_and_posts_are_normalised(publish_env, monkeypatch):
captured = {}
def list_posts(base, key, start, end, *a, **k):
captured["start"], captured["end"] = start, end
return [{"id": "p1", "date": "2026-01-05T00:00:00.000Z"}]
monkeypatch.setattr(postiz, "list_posts", list_posts)
r = _call(publish_env, "get", "/api/postiz/scheduled", headers=POSTIZ_HEADERS)
assert r.status_code == 200, r.text
assert r.json()["scheduled_posts"][0]["scheduled_date"] == \
"2026-01-05T00:00:00.000Z"
start = datetime.fromisoformat(captured["start"].replace("Z", "+00:00"))
end = datetime.fromisoformat(captured["end"].replace("Z", "+00:00"))
assert (end - start) >= timedelta(days=89)

View file

@ -117,8 +117,8 @@ class TestGetEdl:
# the clip: a cut can only be extended into words it was sent.
assert [w["w"] for w in data["words"]] == ["hello", "world", "again"]
assert data["limits"]["max_segments"] == recut.MAX_SEGMENTS
# Self-host meters nothing.
assert data["rerender_minutes"] == 0
# Self-host meters nothing: the managed rerender-minutes key is gone.
assert "rerender_minutes" not in data
def test_ships_words_far_outside_the_clip(self, job):
"""The EDL carries the WHOLE source transcript. The old ±45s window

View file

@ -7,7 +7,6 @@ loads at once; every player got a 404 until the user reloaded.
"""
import os
import pytest
from starlette.applications import Starlette
from starlette.testclient import TestClient
@ -85,11 +84,3 @@ def test_paths_without_a_job_segment_never_call_the_restorer(tmp_path):
def test_no_restorer_behaves_like_staticfiles(tmp_path):
client, _root = _app(tmp_path, None)
assert client.get(f"/videos/{JOB}/clip_1.mp4").status_code == 404
def test_app_job_id_guard():
"""The app-side restorer only hits the database for uuid-shaped ids."""
app_mod = pytest.importorskip("app")
assert app_mod._JOB_ID_RE.match(JOB)
for bad in ("thumbnails", "..", "cff3ad6c", "CFF3AD6C-C1E6-48E8-9A75-BE74F39779C5"):
assert not app_mod._JOB_ID_RE.match(bad)