Commit graph

52 commits

Author SHA1 Message Date
juancarlos.cavero
b4bf211b7b fix(cloud): close the gaps the account-deletion review turned up
Eight findings from re-reading the erasure path, each one something that would
have shown up in production rather than in a test:

- The local purge missed two stores. SaaSShorts outputs (output/saas_<id>) and
  generated thumbnails record ownership in their own in-memory dicts, not in
  the .owner file, so neither was erased. Thumbnails are the serious half: the
  hourly sweep deliberately skips their directory, so a deleted user's
  generated images stayed on disk forever, publicly served at /thumbnails/.
- The purge ran on the event loop. rmtree over gigabytes of video stalled every
  other request on the process; it goes through asyncio.to_thread now.
- Paths from those dicts are now resolved through _safe_under, so a session id
  or output_dir containing ".." deletes nothing.
- Deleting a user made a webhook path reachable that never was: _apply_topup
  takes the user id from Stripe metadata, so a top-up completing around the
  deletion inserted a row pointing at a user that no longer exists. The FK
  violation 500s the webhook, and since the event is only recorded after
  handle_event returns, Stripe retries the same doomed insert for three days.
  It confirms the row exists first.
- The "why are you leaving" box was free text stored in a record that
  deliberately outlives the account, which is how personal data ends up in one
  by accident. It is a closed list now, which also makes twenty deletions a
  month countable instead of readable.
- Two concurrent deletes wrote two erasure records and sent two goodbye emails.
  The DELETE's rowcount now decides which call is the real one; the UI holds a
  ref so a double click doesn't fire a second Stripe cancel and R2 purge.
- The delete button armed itself when the confirm box was empty, if the page
  ever rendered before /api/me resolved.
- The goodbye email claimed we keep "a one-way hash of your email and nothing
  else", which was not true of the Stripe reference beside it. Fixed in the
  email and in the privacy policy, EN and ES.

Also: skip the Upload-Post call when no managed key is configured, and say
plainly in the in-flight comment that it covers metered work only.

tests/test_account_local_purge.py covers tenant isolation across all three
stores and both traversal attempts; test_account_erasure.py gains the
confirmation gate, the API-key refusal, and the already-cancelled-at-Stripe
case that would otherwise trap a user forever.
2026-08-24 19:26:12 +02:00
juancarlos.cavero
1d9fef7445 feat(cloud): self-service account deletion (GDPR art. 17)
The privacy policy already told users that "deleting your account from the
dashboard removes your content" — there was no way to do it. This adds one:
Account -> Delete account in the dashboard, DELETE /api/account on the server.

The endpoint refuses API-key auth (a leaked osk_ must not destroy the account
it was issued from) and requires the caller to retype the account email; the UI
does the same, collapsed behind a danger zone that itemises what actually goes.
Erasure is immediate and irreversible, because after it there is nothing left
to authenticate a recovery request against.

The order of the steps is the design, each one a failure mode:

- Stripe cancel first, aborting everything if it fails, so we never erase a
  user we are still billing. An InvalidRequestError is treated as already
  cancelled: a portal cancellation whose webhook never landed leaves our row
  reading "active" forever, and the one account that could not be deleted
  would be the one Stripe already stopped charging.
- R2 before the database, because those rows are the only index of which
  objects belong to the user; dropping them first turns a failed purge into
  permanent orphans.
- The DB delete is one transaction over an explicit table list, not the
  declared ON DELETE CASCADEs: create_all never ALTERs an existing table, so a
  constraint added after a table shipped lives in the models and not in
  production. tests/test_account_erasure.py fails if a new table references
  users.id without joining that list.
- A reserved usage_ledger row blocks the delete: erasing under a running job
  would pull the output from beneath it and leave the reservation unsettled.

What survives, and why: the Stripe customer and its invoices (six years,
Spanish commercial law) and one account_deletions row holding a sha256 of the
email as proof the erasure happened, itself purged after five years by the
retention sweeper. app.py registers a callback so the working files in output/
and uploads/ go too instead of waiting for the hourly sweep.

Privacy policy sections 6 (EN + ES) now point at the button and name both
survivors; the Legal hub summary says the same in one line.
2026-08-24 19:12:05 +02:00
juancarlos.cavero
080dd5780b feat(delivery): serve clips from a custom R2 domain, and show download progress
Measured 22-ago-2026 against prod, on one 46 MB / 52 s clip:

  origin -> itself through Traefik   130 MB/s
  origin -> a datacenter client      838 KB/s
  origin -> the author's browser      90 KB/s   (8.5 min for one clip)
  R2 S3 endpoint -> the server        11 MB/s, 206
  R2 S3 endpoint -> that browser      503, every single request

So the API process is not the bottleneck (it serves the file at 130 MB/s while
the box sits at 0.01 MB/s of egress); the long path out of Hetzner is. And the
fix for that, R2, is unreachable from a browser: *.r2.cloudflarestorage.com is
an S3 endpoint, and a presigned GET that curl fetches at 11 MB/s with identical
headers returns 503 to Chrome.

R2_PUBLIC_BASE points presigned_get() at a custom domain bound to the bucket
instead, which serves the same objects through the normal Cloudflare edge.
Unset, everything keeps signing S3 URLs exactly as before, so this is inert
until the domain exists. Switched at that one choke point because every caller
hands the URL to a browser.

The download button streamed nothing to the screen while it buffered tens of MB
into a blob, which on a slow link is minutes of a button that looks dead. It now
reports percentage, which needs Content-Length readable from JS, which needs the
CORS middleware to name it in expose_headers.
2026-08-23 13:49:08 +02:00
juancarlos.cavero
e0fa3fd591 perf(dashboard): play clip previews from R2, not from the render box
Each result card streamed its clip from /videos, which is served by the
same single-worker API process that is running the renders, while the
same clip was already archived to R2 (free egress, edge-served). The
durable URL was in the browser the whole time and was only used as an
error fallback.

It becomes the playback source, but only while R2 holds exactly the file
the server considers current: a server-side edit rewrites the clip and the
re-archive behind it is fire-and-forget, so preferring the durable copy
blindly would show the clip from BEFORE the edit. /api/history therefore
returns the archived filename, and the card compares it against its own
serverVideoFile.

The map is chased after each edit and again once the job completes, since
a job is marked completed before _archive_managed_job finishes uploading
and the first read otherwise lands empty and never retries. The effect
that reads it is keyed on the clip count instead of the results object, so
it no longer re-reads the history on every status poll. The durable copy
is never adopted under a player the user already started, because swapping
src restarts playback.

Display only: currentVideoUrl still drives the download button and every
server operation (all of which pass input_filename, never a URL), so no
edit can be routed to the wrong file by this.
2026-08-22 19:52:17 +02:00
juancarlos.cavero
658defe614 fix(proxy): probe the duration over the static pool, not the per-GB proxy
The static ISP pool (dfa3124) moved downloads off the paid proxy but never
touched cloud/metering.py, so probe_url_minutes kept reading PROXY_URL alone.
Every managed YouTube submission still paid DataImpulse for 0.2-1 MB of yt-dlp
metadata (measured through a counting proxy) while the download itself went out
free over Decodo — and invisibly, because PROXY_BYTES only counts the bytes of
the winning download attempt.

The probe now walks the same cheapest-first chain as the download: direct when
DIRECT_FIRST=1, then the statics rotated per probe, then the paid proxy as the
last resort. Proxies are the outer loop and extractor strategies the inner one,
so the paid route is only reached after every free one has failed on both.
That also stops a drained paid proxy from taking YouTube ingest down on its own
("Could not determine the video duration") while the statics are healthy.

Two smaller cuts on the same path: a user with no minutes left now gets its 402
before the probe instead of after it, and a failed route no longer dumps a
yt-dlp ERROR block per proxy per strategy into the API log (the watcher is what
reports a dead route).
2026-08-21 22:45:53 +02:00
juancarlos.cavero
730f7de949 fix: reject too-short sources at submit and stop alerts blaming recovered downloads
Prod 20-ago, 5 of 12 managed jobs failed and the alert said 'youtube
download' — no download had terminally failed. Three fixes:

- The quality probe now reports source duration, and /api/process rejects
  sources under MIN_SOURCE_SECONDS (default 45, 0 disables) on all three
  ingest paths with a clear message. A 24s YouTube Short cannot yield
  15-60s clips; Gemini returns nothing and the job burns managed minutes
  to die with 'no usable clips' (3 of the 5 failures, one user retrying
  the same cat video).

- _job_error_text drops per-attempt download warnings when a later
  attempt succeeded (HD-direct fails on every job since the server IP
  ban; static proxies recover it), and gained an 'Error:' marker so
  raised exceptions (RuntimeError:, GeminiBlockedError:) reach the alert
  instead of a bare 'Traceback ... exit code 1'. The classifier names
  'no clips found (user video)' as its own content-shaped category.

- (env, no code) DIRECT_FIRST=0 in prod: with the server IP banned the
  direct attempt only added ~10s and the noise behind these alerts.
2026-08-20 22:54:51 +02:00
juancarlos.cavero
dfa31241ca feat(download): flat-rate static ISP proxies before the per-GB proxy
New STATIC_PROXY_URLS env (comma-separated): dedicated ISP IPs with
unlimited traffic, tried after the direct attempt and before the per-GB
paid proxy. With it unset the chain is byte-identical to before.

- plan_download_attempts: pure, unit-tested attempt ordering. Cheapest
  bandwidth first: direct -> statics (rotated per job, uncapped 1080p,
  free bytes) -> paid HD (720p cost cap) -> fallback via paid.
- The 720p cap and the PROXY_BYTES monthly counter now apply ONLY to
  attempts that actually bill per GB — static downloads come in at 1080p
  and don't count toward the cost alert.
- alerts.py watcher generalized to multiple targets: the static pool
  (down = ingest silently moves to per-GB billing, nag with a cost hint)
  and the paid proxy (down = ingest at risk), each with its own
  down/nag/recovered incident state.

Context: the server's IPv4 is hard-banned by YouTube (19-aug-2026), so
DIRECT_FIRST serves nothing and every download was going through
DataImpulse at $1/GB capped to 720p. Verified from prod: all 3 Decodo
dedicated IPs pass the bot-check with cookies+bgutil at 1080p.
2026-08-19 19:28:52 +02:00
juancarlos.cavero
72288bba82 fix(alerts): probe the proxy over plain HTTP
HTTPS through DataImpulse fails in httpx with an SSL record-layer error
even when the proxy is healthy (verified against a working proxy right
after the top-up; yt-dlp's stack tunnels the same proxy fine), so an
HTTPS probe would report a permanent false outage. An exhausted balance
rejects the request at the proxy before forwarding, so plain HTTP still
catches the 407.
2026-08-19 17:11:10 +02:00
juancarlos.cavero
5e84e6486a feat(alerts): proxy balance watcher — nag on Telegram until topped up
The residential proxy ran out of traffic (407 TRAFFIC_EXHAUSTED,
19-aug-2026) and every YouTube-URL job failed with only easy-to-miss
one-shot alerts. Now:

- cloud/alerts.py: a background watcher probes the proxy every 30 min
  (generate_204, a few bytes of paid traffic). On failure it alerts
  immediately, re-alerts every 2 h while the proxy stays down, and sends
  a recovery confirmation when it answers again — so exhaustion is caught
  even before the next user job fails.
- record_job_outcome: a proxy-classified job failure also opens the
  incident, so job-driven detection and the probe share one state.
- app.py: the watcher starts from the lifespan in managed mode.
- tests/test_proxy_watch.py: state machine (first alert, renotify window,
  recovery + reset, job-error trigger).
2026-08-19 17:07:09 +02:00
juancarlos.cavero
2b2e287a9b feat(hook): replace semantics — a new hook swaps the burned one, plus remove
The auto-hook was burned into the canonical clip in place, so editing the
hook stacked a second overlay on top of the first. Hooks now follow the
exact derivation pattern captions use:

- main.py: auto_hook_clip writes hooked_<ts>_<clean>.mp4 next to the clean
  canonical instead of mutating it; captions burn on top of the hooked file
  (subtitled_<ts>_hooked_<ts>_<clean>). Watermark moves BEFORE the hook so
  the branding lives in the canonical and survives hook replacement.
- app.py: _strip_burned_hook walks hooked_/legacy hook_ prefixes back like
  _strip_burned_captions; /api/hook strips captions AND the old hook before
  burning, so a new hook always REPLACES the previous one. New remove flag
  strips the hook entirely (captions re-applied, no metering). Burned hook
  recorded/cleared in clip metadata (auto_hook key) and returned as
  burned_hook. _canonical_clip_file resolves hooked_*/hook_* derivations.
- cloud/videos.py: archive the hooked_ intermediate of a captioned hook so
  restored projects keep the walk-back chain editable.
- ResultCard: stripBurns knows hooked_<ts>_ (the Remotion preview now
  composes over the truly clean clip — no more stacked preview), burned
  hook tracked in state, remove handler wired to the modal.
- HookModal: warning now says replace, plus a 'remove hook from clip'
  action when one is burned.
2026-08-19 16:01:53 +02:00
juancarlos.cavero
100fa583a1 Merge feat/clip-editor: per-clip EDL editor + manual generation controls (PR #62, discussion #65) 2026-08-18 19:27:49 +02:00
juancarlos.cavero
a0e25828fd fix(cloud): archive clean canonical clips so restored projects stay editable
The clip editor's fast path (and /api/subtitle re-styles) cut from the
clean canonical file, but archive_job only uploaded the served derivative,
so every project restored from R2 after a redeploy 409'd on rerender even
for in-range segments. Archive the clean canonical alongside the served
file; restore already downloads everything under the job prefix. The
free-retention purge now deletes the whole job prefix so these extra keys
(and previously leaked derivatives) can't become orphans.
2026-08-18 15:26:45 +02:00
juancarlos.cavero
5b4f5b2891 fix(digest): harden daily digest after code review
- Retry the 06:00 send in place (6x / 5 min) instead of silently skipping
  the day when a DB blip or Telegram outage lands on the send minute; the
  digest path now uses send_telegram(raise_errors=True) so failures are
  visible to that retry, and send_telegram checks the HTTP status.
- Filter Stripe lines by processed_at, not the Stripe-side created stamp
  that survives delivery retries and could land inside an already-digested
  window.
- Drop invoice.payment_succeeded (near-alias of invoice.paid; counting both
  double-reports payments) and the Subscription.created_at count (upserts
  hide re-subscribing churned users) — customer.subscription.created events
  cover new subs correctly.
- Keep a strong reference to the digest task so it can't be GC'd mid-sleep.
2026-08-18 14:53:31 +02:00
juancarlos.cavero
9a4439af48 feat(alerts): daily Telegram ops digest
One message per day at 06:00 UTC with signups, processing activity (users,
jobs, minutes, refunds), clips created, new subscriptions and notable Stripe
events, all computed from the DB at send time so redeploys lose nothing.
Replaces the per-event free-tier pings removed in the previous commit.
2026-08-18 14:40:55 +02:00
juancarlos.cavero
e4331467e5 fix(auth): harden MX verification after code review
Review findings on the MX-gate commit, addressed:

- Rate limits now run BEFORE the DNS work, and the attempt row is
  inserted before the MX gate, so rejected junk-domain floods count
  toward both limits instead of getting unlimited free DNS lookups.
- Existing accounts bypass the MX gate: it protects sign-up only, so a
  domain whose MX later matches the disposable list can't lock an owner
  out of their account.
- RFC 5321 implicit MX now also checks AAAA (IPv6-only mail domains
  were falsely rejected).
- Error-derived verdicts cache for 60s instead of 1h: a transient
  NXDOMAIN no longer pins a lockout, a resolver blip no longer
  whitelists a domain for an hour.
- One shared resolver with an LRU record cache (was: new resolver +
  resolv.conf read per lookup); verdict cache evicts FIFO instead of
  full clear.
- MX blocklist moved to disposable_mx.txt, same loader and ops workflow
  as disposable_domains.txt (the two lists were already drifting).
- Both rate-limit counts merged into one FILTER query; distinct 429
  message for the per-IP limit (shared-NAT lockouts diagnosable).
- Index on (request_ip, created_at) + 30-day token purge in the
  retention sweeper. NOTE: schema is create_all-only, prod needs:
  CREATE INDEX IF NOT EXISTS ix_magic_ip_created
    ON magic_link_tokens (request_ip, created_at);
2026-08-13 10:07:20 +02:00
juancarlos.cavero
a76decd56f feat(auth): verify email domain MX before sending magic links
Bot sign-ups with rotating temp-mail domains (onldm.net -> 10minutemail's
SMTP) and nonexistent addresses were bouncing every magic link back into
the support inbox and hurting sender reputation.

- email_policy.mx_verdict(): resolve the domain's MX (A fallback per RFC
  5321) and reject when nothing can receive mail or when the MX target
  belongs to known disposable-mail infrastructure - catches the rotating
  front domains the static blocklist can't keep up with. Cached per
  domain, fails open on resolver trouble.
- auth: per-IP rate limit on magic-link requests (bots rotate addresses,
  not IPs).
- blocklist: add onldm.net; pin dnspython (already transitive via
  email-validator).
2026-08-13 01:03:05 +02:00
juancarlos.cavero
f10655fd1c feat(agents): the pipeline as a platform — API keys, MCP server, webhooks
Agents don't forget to come back; humans do. Make the whole pipeline
drivable without the dashboard:

- API keys (osk_...): sha256-stored tokens minted from the account page.
  get_current_user_optional resolves them like a session, so metering,
  entitlement, priority and job ownership apply to agents with zero
  endpoint changes. Key management refuses API-key auth (a leaked key
  cannot mint replacements).
- MCP server at /mcp: stateless Streamable-HTTP JSON-RPC, no SDK
  dependency. Six tools (process_video, get_job_status, list_clips,
  get_quota, add_subtitles, publish_clip) that call back into this same
  app in-process via ASGITransport with the caller's auth headers, so
  MCP can never drift from REST behavior. Cloud requires a key;
  self-host stays BYOK-open.
- Completion webhooks: webhook_url (+ optional HMAC webhook_secret) on
  /api/process, SSRF-checked at submit AND delivery, fired once after
  the R2 archive so payloads carry durable links, survives redeploys
  via the resume manifest.
- Dashboard: API keys card in the account page (create once-shown key,
  list, revoke).
- Tests pin BILLING_ENABLED=0 in conftest so the suite no longer
  depends on the developer's personal .env.
2026-08-03 22:33:16 +02:00
juancarlos.cavero
51aafb5290 feat(analytics): report job outcomes to OpenPanel, with the user's job index
The browser reports the funnel, but not what decides whether this product
retains: on 26-jul-2026, 491 of the 564 users who ever processed a video did it
exactly once. Every clip-quality fix that shipped that day — 1080p delivery,
captions by default, loudness normalisation — was aimed at that 87%, and
nothing in the stack could measure whether it moved.

Client-side cannot answer it. A render finishes minutes later, often after the
tab is gone, and ad-blockers eat a share of the rest. So the backend now emits
ClipsDelivered / JobFailed with the user's profileId and a `job_index` — the
count of process jobs that user has run. Counting distinct users at index 1
versus index >= 2, before and after today, answers the question directly.
Failures carry the same reason classification the Telegram alerts use, so the
"did it break or did they just not come back" split is visible too.

Fire-and-forget throughout: no config means a silent no-op (the normal state
for self-hosted), every send is a background task, and every failure is
swallowed. Analytics must never slow down or break a job.

Needs OPENPANEL_CLIENT_ID and OPENPANEL_CLIENT_SECRET in the environment — a
WRITE client, which is a different credential from the read/root client the MCP
needs. Verified against the live instance: the write path returns 200 and the
module no-ops cleanly when unconfigured.
2026-07-28 21:49:40 +02:00
juancarlos.cavero
8f873296a1 fix(emails): stop duplicate expiry warnings and fix the button that 404s
Two bugs in the "your N clips will be deleted tomorrow" email.

The button pointed at {frontend_url}/dashboard, a route that has never existed:
the app is a single-page app routed entirely through the hash, and #app is what
opens it. Until today /dashboard fell through to the SPA fallback and quietly
showed the marketing landing, so the link looked like it worked. Now that
unknown paths return a real 404 it fails visibly. Both this and the clips-ready
email now link to /#app; the clips-ready one was passing the bare frontend URL,
which showed the landing page to anyone whose browser had not already set the
skip-landing flag.

The duplicate send is worse. De-duplication was `_warned_video_ids`, a set in
process memory, and the warning window is a full day while the sweep runs every
six hours. Any API restart inside that window re-armed the warning for everyone
already told. That is exactly what happened today: the 06:00 warning went out,
three deploys restarted the API (frontend and API share this repo, so the SEO
pushes redeployed both), the container came up at 12:36, and the sweeper's first
run six hours later at 18:36 mailed the same clips again.

Warnings are now recorded in clip_expiry_warnings, keyed by clip id, written
before the send. A new table rather than a column because the schema bootstrap
is create_all, which creates missing tables but never ALTERs one — same reason
SignupAttribution is its own table. The FK cascades from user_videos, so rows
disappear when purge_free_expired deletes the clip and no cleanup pass is needed.

Recording before sending is deliberate: a duplicate email is the failure being
fixed, while a warning row for a mail that then failed to send costs that user
one notice.

No backfill. Clips already warned about have no row yet, so the current cohort
gets one more warning after this deploys and none after that. Backfilling the
window would also silence the first warning for anyone who entered it since the
last sweep, and a missed deletion notice costs the user their clips, while a
duplicate only costs them an email.

Verified against a real Postgres: create_all builds the table, the primary key
rejects a second row for the same clip, the cascade removes warnings when the
clip is deleted, and warn_free_expiring sends exactly one email across two
sweeps plus a module reload standing in for a restart (which is what used to
produce the second email).
2026-07-27 22:31:04 +02:00
juancarlos.cavero
9b01e02a9b feat(attribution): record where each new account came from
Every strategic read on the funnel so far has been inference: 94% of search
clicks are brand queries, so the real acquisition channel is upstream of
Google, but `users` stores no source at all and we cannot tell GitHub from
YouTube from a directory listing, nor say which channel produced the few
accounts that pay.

Capture `document.referrer` + UTM on the first page load, keep it in
localStorage (our own auth redirects destroy the referrer), and post it once
the account exists. First touch wins, so arriving from GitHub and later
returning via a search still attributes to GitHub.

- New `signup_attribution` table rather than columns on `users`: the schema
  bootstrap is create_all, which adds missing tables but never ALTERs an
  existing one, so this lands on deploy with no migration.
- Only recorded for accounts minutes old, so the 1196 existing users cannot
  be mislabelled with their next login.
- ON CONFLICT DO NOTHING for two tabs finishing the same redirect; the client
  call is fire-and-forget and can never fail a sign-in.
2026-07-27 10:39:24 +02:00
juancarlos.cavero
a793e02ddf fix(subtitles): stop charging quota for burning captions
Captions are table stakes for short-form — a clip without them barely works on
any platform — but every burn cost 2 minutes, 10% of the free monthly quota,
roughly what generating the clip cost in the first place. People skipped them:
only 9% of delivered clips had captions in the 25-jul-2026 prod audit (35
subtitle jobs against 380 process jobs).

The charge never matched the work. The normal path reads the transcript already
stored in metadata.json and runs one short FFmpeg pass — measured at 4s on CPU
for a 12s clip, 1-2s on the GPU. Charging 120s of quota for that is ~30x the
compute, and it was invisible in the UI, so users were drained without being
told. The endpoint is already gated by require_managed_entitlement, so the
charge was never what bounded abuse.

Dubbed clips keep the charge: subtitling them re-runs Whisper over the
translated audio, which is real work. The rule lives in cloud.config next to
the constant so it stays testable without importing app.

Also short-circuit reserve_managed_action on a zero-minute action rather than
writing a 0-minute ledger row on every call.
2026-07-25 17:16:59 +02:00
juancarlos.cavero
5b5d3d2306 fix(billing): stop stranding customers whose payment failed
A declined card left the account in a state with no way out. `past_due` grants
no minutes, so the metering layer resolved the user to the free plan — which
meant /api/me reported status=null, the account page swapped "Manage billing"
for "Upgrade" (hiding the only button that fixes a card), and the checkout guard
then rejected the upgrade with a 409 that every call site swallowed into a
generic "Could not start checkout." Silently free, unwarned, unable to pay.

Found on 25-jul-2026 in prod: 14 subscriptions in this state, all first charges
that failed when the (now retired) 3-day trial ended. The trial is gone, but the
trap is not — a renewal failure or an abandoned 3DS payment reproduces it.

- metering: split `_subscription_row` (raw) from `_active_subscription`
  (entitling), and expose both on the balance. Entitlement logic is unchanged.
- /api/me: report status/interval from a row needing attention when no
  subscription entitles, plus `has_billing_account` to route the portal button.
- checkout: drop `incomplete` from the blocking states. Stripe collects nothing
  on it and expires it within 24h, so blocking only stopped the user's retry.
  Give past_due/unpaid a message that names the problem and the fix.
- account page: explain the failed payment inline with a link to the portal
  instead of showing a bare "past_due" chip, and keep the portal reachable for
  any Stripe relationship, live or broken.
- api client: throw a typed ApiError carrying the server's detail so callers
  stop replacing real, actionable messages with generic copy.

Verified against a real DB: past_due stays blocked but visible and fixable,
incomplete can retry, canceled is silent and can subscribe again.
2026-07-25 15:14:15 +02:00
juancarlos.cavero
c88239921e feat(conversion): vender también en los momentos buenos, no solo en el muro
Hasta ahora el único camino al upgrade era fallar contra la cuota. Tres
momentos nuevos, todos con el mismo mensaje ya validado (watermark +
caducidad 7d + minutos):

- Resultados (pico de satisfacción): banner para usuarios free junto a
  sus clips recién generados — "Like these clips? Keep them forever →" —
  que abre la modal de upgrade en modo 'upsell' (copy adaptado: aún
  tienen minutos, se vende permanencia y limpieza, no "te quedaste sin").
- Medidor del header: para free abre la modal de upgrade en vez de ir a
  account — antes no existía ningún camino visible a los planes desde el
  dashboard sin fallar primero.
- Email "tus clips se borran mañana": warn_free_expiring() en el sweeper
  avisa el día 6 de los 7 de retención free, con descarga o upgrade como
  salidas. Aversión a la pérdida honesta: la fecha es real y hoy se
  borraba en silencio, lo que no convertía a nadie. Dedupe en memoria
  (peor caso tras restart: un duplicado).

Eventos UpsellModalSeen/UpsellModalCheckout separados de los del muro
para medir cada momento por su lado.

Verificado: lógica del aviso probada contra la DB local (clip de 6.5d
avisa, el de 8d ya purgeable no, segundo pase no duplica); 141 tests y
build del dashboard en verde.
2026-07-25 02:27:34 +02:00
juancarlos.cavero
95a9a5ff1e feat(conversion): vender el plan (no top-ups) en el momento del muro de cuota
De 76 impactos del muro 402 en 72h solo 4 llegaron a checkout y la única
compra fue un top-up: la modal antigua ofrecía packs de minutos sueltos
como opción principal, el upgrade a plan era un párrafo NO clickable y
un StarBanner empujaba a GitHub en pleno momento de compra.

Nueva modal (mismo fichero/props, cero cambios en App.jsx):
- Starter destacado + Creator al lado como ancla de precio; bullets del
  valor real de pagar: 5x/15x minutos, sin watermark, clips permanentes
  (los free caducan a 7 dias) y prioridad de cola sobre free — todo
  cierto, sin escasez inventada ni cuentas atras falsas.
- Copy goal-gradient con los datos del 402: "this video needs X min and
  you have Y left — upgrade and it starts processing right away".
- "cancel anytime" como reversion de riesgo; top-ups relegados a un link
  discreto que expande; StarBanner fuera.
- Eventos QuotaWallSeen / QuotaWallCheckout para medir la conversion del
  muro, que hasta ahora era invisible.

El email de sin-minutos replica el mismo mensaje (perdida + plan concreto
+ CTA unico) y por fin deja rastro en logs al enviarse.

Verificado end-to-end en local: usuario free con cuota agotada via DB,
402 real de /api/process, modal con datos reales y packs expandibles.
2026-07-25 02:14:58 +02:00
juancarlos.cavero
77905a9790 fix(gemini): distinguir bloqueo de contenido de fallo transitorio
La alerta del 23-jul (5/12 jobs, "empty response body") no era la API
fallando: un vídeo subido (stand-up con contenido explícito) devuelve
prompt_feedback.block_reason=PROHIBITED_CONTENT en ~300ms, de forma
determinista — verificado con la transcripción real, y BLOCK_NONE en
safety_settings NO lo levanta (es el filtro de política de Google, no
configurable). Reintentábamos 3 veces algo imposible, el error parecía
un fallo nuestro, y el usuario reintegró el mismo vídeo varias veces
inflando la tasa de fallos.

- gemini_worker: GeminiBlockedError + raise_if_blocked() (block_reason
  del prompt y finish_reason SAFETY/PROHIBITED_CONTENT/... del candidato).
- main: _run_gemini_stage falla rápido sin reintentos ante bloqueo (0.5s
  vs ~15s) y propaga el motivo real hasta el log del job en ambas vías
  (transcript y visión); ya no se convierte en el genérico "no clips".
- alerts: categoría propia "blocked content (user video)" para que la
  alerta no se lea como caída del servicio.
2026-07-24 00:37:14 +02:00
juancarlos.cavero
b8159990a9 fix(transcribe): manejar vídeos sin audio + alerta de fallos honesta
El error del admin ('High download failure rate... rebuild image') era
engañoso: el fallo real no era descarga sino transcripción de un vídeo SUBIDO
sin pista de audio (un clip generado por IA, Gen-4 de Runway). faster-whisper
revienta dentro de libav con 'tuple index out of range' cuando el fichero no
tiene audio.

- transcribe_media detecta la ausencia de pista de audio (ffprobe) ANTES de
  transcribir y lanza NoAudioError con mensaje claro; main.py lo convierte en
  un fallo user-facing ('NO_AUDIO: este vídeo no tiene audio...') en vez de un
  traceback. Verificado en contenedor con vídeo con/sin audio.
- La alerta de tasa de fallos ya no culpa siempre a la descarga: clasifica el
  último error (proxy / youtube download / no audio / transcription / gemini /
  ffmpeg) y lo pone en el título.

123 tests (nuevos: vídeo mudo + clasificación de fallos).
2026-07-21 21:13:59 +02:00
juancarlos.cavero
7d6c232165 feat(alerts): prefijo 'OPENSHORTS ✂️ -' en todos los mensajes de Telegram
El chat de Telegram es compartido con Upload-Post y otros productos, así que
cada mensaje de OpenShorts se marca con el nombre para distinguirlos de un
vistazo. Aplicado en send_telegram, cubre todas las alertas (pagos, subs,
churn, clips).
2026-07-21 02:20:56 +02:00
juancarlos.cavero
2efbeb2828 feat(alerts): avisar del dinero de Stripe (con importe) y de activación de clips
Stripe — dos huecos que faltaban:
- invoice.paid no disparaba nada: las renovaciones mensuales entraban en
  silencio. Ahora 💵 'Payment received: $X' en cada cobro real (primera compra
  Y renovación), con el importe y el motivo (new subscription / renewal).
- El aviso de top-up ahora incluye el importe cobrado.
- Helper _money() para formatear cents+currency ('$59.00 USD').

Clips (opción 1, alta señal para no ahogar el canal cuando crezca el free):
- _notify_clip_activity avisa por Telegram SOLO en el primer clip de un
  usuario (activación) o en clips de usuarios de pago. Nada de un ping por
  cada clip free. Incluye email, plan, título y nº de clips.

Verificado enviando los formatos reales al Telegram del admin.
2026-07-21 02:06:04 +02:00
juancarlos.cavero
26135fb485 feat(abuse): abrir free a email normal + bloquear dominios desechables
El free ya no exige Google: cualquier cuenta Google o de email permanente
entra. Para que no sea un grifo de minutos gratis:
- Bloqueo de dominios desechables/temp-mail en el registro por email
  (cloud/disposable_domains.txt, 155 dominios: los clásicos temp-mail + los
  vistos en nuestra propia DB). Refrescable desde el proyecto upstream.
- Normalización de alias: gmail dots/+tags y +tags de otros proveedores se
  colapsan a una sola cuenta canónica, para que foo+1@ / f.oo@ no minten
  cuentas infinitas. Aplicado en magic-link y en Google OAuth.
- free_plan_eligible: Google siempre; email solo si el dominio no es
  desechable (defensa en profundidad además del bloqueo en registro).
- Popup de bienvenida ahora sale una vez por navegador en el primer registro
  (Google o email), no solo a los no-entitled; el botón free arranca directo
  sin forzar Google.

Verificado: registro con mailinator/luckfeed -> 400; gmail -> 200. 115 tests
(9 nuevos de email_policy).
2026-07-21 00:45:54 +02:00
juancarlos.cavero
fe0f32e86b feat(onboarding): popup de selección de plan + quitar tope diario free y 'free trial'
- Quitado el tope de 3 jobs/día por cuenta y 5 por IP en el plan free: la
  cuota de 20 min/mes es el único límite (el ledger ya capa el coste real y el
  tope diario confundía). Verificado que un free NO puede pasar de 20 min ni
  con reservas concurrentes: 10 reservas simultáneas de 5min -> solo 4
  concedidas, ledger clavado en 20, el lock por usuario serializa.
- Registro por email ya no tira a la página de pricing (rayaba): aterriza en
  la app y sale un popup PlanChoiceModal para elegir plan — free (via Google,
  por el gate anti-abuso) o los de pago inline con su precio.
- Eliminado 'start free trial' / '3 days free' de la cabecera y de settings;
  ahora dicen 'choose a plan'.
- vite.config: target del proxy configurable con VITE_PROXY_TARGET para dev
  en el host contra localhost:8000 sin CORS.

Probado en dev local: el popup aparece al aterrizar sin plan y desde el botón
'choose a plan', con free + starter/creator/pro.
2026-07-21 00:30:56 +02:00
juancarlos.cavero
900dc441d3 feat(jobs): reanudar trabajos cortados por un redeploy en vez de perderlos
Un job vive solo en memoria, así que matar el contenedor a mitad de proceso
lo perdía: al usuario se le cortaba el clip. Ahora al encolar se escribe un
manifiesto mínimo (.resume.json: cmd, prioridad, user, reserva, watermark —
sin secretos, el env se reconstruye al reanudar) y en el arranque se
re-encolan los que se quedaron a medias, tras _recover_jobs_from_disk (los que
ya habían terminado de generar clips se recuperan como completados, no se
reanudan).

- Tope MAX_RESUME_ATTEMPTS=2: un vídeo que reviente el worker no puede meter
  al servicio en un bucle; se rinde y se refunda por la vía de huérfanos.
- La reserva de minutos del job reanudado se conserva (no se refunda como
  huérfana) para que la liquide el run reanudado.
- El manifiesto se borra en cualquier estado terminal (éxito o fallo real);
  solo sobrevive si el contenedor murió a mitad, que es cuando queremos
  reanudar.

Verificado en el contenedor: reanuda conservando reserva, no re-ejecuta
completados, se rinde con envenenados. Reconstruye env con la clave gestionada
sin volcar secretos a disco.
2026-07-20 22:32:53 +02:00
juancarlos.cavero
a42297f120 Merge origin/main: analytics + billing cross-sub guard
Conflicto resuelto en AuthContext (se mantienen el track('Signup') y el
enrutado del plan free). Además, fix de la interacción entre ambos cambios:
AccountPage daba el checkout por activado en cuanto /api/me devolvía un
plan, pero 'free' ahora existe desde el primer instante — se exige un plan
de pago antes de parar el polling, disparar el goal Subscribed y llevar al
usuario a conectar sus redes.
2026-07-20 15:22:52 +02:00
juancarlos.cavero
9fd1cacb0c feat(billing): free plan (20 min/mes sin tarjeta) + retirar trial + opt-in galería UGC
- Plan free resuelto en metering (sin fila Stripe): 20 min/mes para cuentas
  Google, período sintético de mes natural con reset automático
- TRIAL_DAYS=0 para nuevos checkouts; trials en curso grandfathered
- Watermark drawtext en clips free (pasada única post-render, sobrevive
  subtítulos/hooks); thumbnails IA solo de pago
- Anti-abuso: 3 jobs/día por cuenta, 5 por IP, rate-limit de probes,
  contador mensual de GB de proxy con alerta Telegram a 100 GB
- Clips free caducan a 7 días (purge_free_expired); purge_expired respeta
  a cancelados que ahora son free
- Galería UGC pública pasa a opt-in (share_to_gallery, antes publicaba
  producto+guion de todos los usuarios sin permiso)
- Emails: clips listos (con star-ask) y sin-minutos (cooldown 24h)
- Frontend: card Free en pricing, copy sin trial (landing/legal/gates),
  StarBanner en resultados y TopUpModal, upsell de watermark
2026-07-20 00:26:21 +02:00
victormanuel.caverogracia
747a1d5f95 fix(billing): don't let a non-current subscription clobber the live row
subscriptions keeps one row per user, keyed on user_id in _upsert. An event
for a *different* sub of the same user (e.g. canceling a dangling past_due
annual while a monthly trial is live) would overwrite the good row. Add a
cross-subscription guard: another sub only takes over the row when the stored
one is no longer live.
2026-07-18 23:42:21 +02:00
victormanuel.caverogracia
9e5aa7431d fix(billing): block new checkout for past_due/unpaid/incomplete subs
Guard only blocked active/trialing, so a user whose first charge failed
(sub in past_due) could create a second subscription. Real case: annual
trial -> end-trial -> card declined -> past_due, then a fresh monthly sub,
leaving two live subs on one customer. Now any non-terminal status blocks.
2026-07-18 23:35:08 +02:00
juancarlos.cavero
927ee09ffc feat(projects): reopen archived projects from history for further editing
- New projects table (job_id, metadata_r2_key, state JSONB) — created via create_all
- archive_job also uploads the metadata JSON (transcript) and upserts the
  Project row + user_videos (no more duplicate rows on re-archive)
- archive_clip_edit re-archives a clip after each server-side edit, keeping
  only the pristine original + current version per clip in R2
- fix /api/edit: persist new video_url in job result + metadata.json (the
  other edit endpoints already did)
- POST /api/projects/{job_id}/restore re-hydrates R2 files into output/{job_id}
  (per-job lock, temp-dir download, .owner sidecar, idempotent fast path)
- GET /api/projects + PUT /api/projects/{job_id}/state (debounced Remotion
  layer sync from the frontend)
- History tab groups clips by project with a reopen button; App restores
  jobId/results/project state; ResultCard seeds serverVideoFile/activeLayers
  from the restored state and reports changes upward
2026-07-18 03:42:17 +02:00
juancarlos.cavero
61954a7f28 fix(auth): OAUTH_REDIRECT_URI override for local login through the Vite proxy
Through the dev proxy the backend sees Host backend:8000, so url_for built
redirect_uri=https://backend:8000/... which Google rejects with 400
invalid_request. Allow pinning the callback via OAUTH_REDIRECT_URI; the
Host-derived behavior is unchanged when the variable is unset (prod).
2026-07-17 21:26:04 +02:00
juancarlos.cavero
83b0649b20 fix(cloud): precise proxy alerts, scrub proxy creds from logs, hide system logs from paid users
- alerts.py: _looks_like_proxy_error only matches genuine proxy/download-stage
  signatures (407, ProxyError, tunnel failed, 402/out-of-credits) instead of a
  bare "proxy"/"credit"/"balance" substring — a job that failed in processing (or
  a video titled with one of those words) no longer fires a false "out of credits"
  alert. Real proxy failures still alert.
- app.py: _scrub_secrets() masks user:pass in any URL before a subprocess line is
  printed or stored, so the residential proxy URL yt-dlp echoes in verbose debug
  never lands in the server console or job log.
- app.py: _visible_logs() — cloud (BILLING on) surfaces only the pipeline's own
  friendly progress lines (emoji-prefixed + worker start/finish) and hides the raw
  yt-dlp/ffmpeg/debug spew from paying users; self-host still shows everything.
2026-07-17 21:23:54 +02:00
juancarlos.cavero
687412a860 fix(cloud): preview falls back to durable R2 url when local clip is gone
After a reload the ephemeral /videos/ files may be cleaned up (1h retention),
leaving black previews on the results screen. For managed users, fetch the job's
clips from /api/history (now includes clip_index) and fall back to the durable R2
url on video error (with a retry for the load race).
2026-07-16 19:44:26 +02:00
juancarlos.cavero
0373c8571b feat(social): keep scheduling calendar + add Content calendar button in dashboard
- revert showCalendar to true (calendar stays available in the white-label page)
- add a 'Content calendar' button (opens the Upload-Post page in a new tab) so users
  can consult/manage scheduled posts from the dashboard
2026-07-16 19:26:51 +02:00
juancarlos.cavero
8ce4d3c5d9 feat(social): auto-connect socials after paying, same-tab redirect, hide calendar
- social connect JWT: showCalendar=false (hide scheduling calendar in white-label page)
- connect opens in the same tab so the page's redirectUrl returns the user to the app
- after the first plan activation (checkout success), take the user straight to the
  social-connect flow; guarded so top-up checkouts don't re-trigger it
2026-07-16 19:24:49 +02:00
juancarlos.cavero
1f7ec835db fix(oauth): force https on Google redirect_uri for public hosts
Proxy-header trust alone wasn't enough in prod (still built http://). Build the
redirect_uri and force https for non-localhost hosts so it matches the registered
Google URI regardless of how the reverse proxy forwards the scheme.
2026-07-16 18:52:39 +02:00
juancarlos.cavero
c32d579675 chore: scrub infra hints from repo
- Remove vendor name (proxy provider) and strategy-revealing comments across
  Dockerfile, docker-compose.cloud.yml, main.py, cloud/metering.py, cloud/alerts.py
- Stop tracking .env.cloud.example (kept local only; added to .gitignore)

Functional references (yt-dlp helper plugin, env var names) necessarily remain.
2026-07-16 18:31:55 +02:00
juancarlos.cavero
3b2221b0d2 feat(alerts): Telegram admin alerts for purchases + ops issues
- config: TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID + telegram_configured
- alerts: send_telegram(); send_admin_alert now pushes to Telegram + email
  (so existing proxy-out-of-credits and high-failure alerts hit Telegram too)
- billing webhook: alert on new subscription, trial→paid conversion, and top-up
- .env.cloud.example documents the Telegram vars

Verified end-to-end: alert delivered to the admin group via the same
send_admin_alert path the webhook uses. Token stays in gitignored .env.
2026-07-16 17:59:07 +02:00
juancarlos.cavero
6ec6935532 fix(cloud): harden paid-mode surface + source-available license for cloud/
Security fixes on the hosted/paid surface (all no-op in self-host / BYOK):
- upload path traversal: basename() client filenames in /api/process,
  /api/thumbnail/upload, /api/thumbnail/analyze fallback, /api/thumbnail/generate
  (face/bg + session_id) so "../" can't escape UPLOAD_DIR
- SSRF: saasshorts subpage scraper now follow_redirects=False + assert_public_url
  per hop (was open to 302 -> 169.254.169.254 metadata)
- metering: reserve+commit/release on /api/render, /api/subtitle, /api/hook and a
  fixed guard cost on /api/thumbnail/upload transcription (were entitlement-gated
  but unmetered -> unlimited off-quota compute)
- entitlement: SaaSShorts generate/actor-options/actor-upload now require a plan
  in cloud; /api/edit ignores body api_key in cloud (no gate/meter bypass)
- multi-tenant IDOR: stamp user_id on thumbnail_sessions/saas_jobs and reject
  non-owners (404) across status/mutation/publish/post endpoints
- DoS: bounded/streamed reads on actor-upload and thumbnail uploads
- retry_job_id routed through _safe_under

Frontend: raw fetch -> apiFetch on the now-gated/owner-checked endpoints so the
bearer token attaches.

License: cloud/ is now source-available under the OpenShorts Commercial License
(self-host/personal use allowed; no competing hosted service). Core stays MIT.
2026-07-16 17:30:12 +02:00
juancarlos.cavero
c0ad5e0de8 feat(billing): 20-min trial cap + activate-plan-now upgrade flow
- config: TRIAL_MINUTE_CAP=20 — trial allowance capped across all plans
- metering: apply the cap in _balance while status=trialing (full minutes once active)
- billing: POST /api/billing/end-trial ends the Stripe trial immediately (charge now,
  unlock full minutes); webhook flips status→active
- frontend: hitting the cap while trialing opens TrialUpgradeModal (activate plan now)
  instead of the top-up modal; polls /api/me until active
- Legal: disclose the 20-minute trial allowance
2026-07-16 02:13:55 +02:00
juancarlos.cavero
d298f69f12 feat(cloud): bake bgutil 720p into image, profile menu, video-URL info, trial→pricing
- Dockerfile: bake bgutil PO-token provider in script mode (no sidecar); 720p verified
- main.py / cloud/metering.py: support BGUTIL_SCRIPT_PATH (script mode) alongside HTTP
- docker-compose.cloud.yml: drop bgutil sidecar; .env.cloud.example documents script mode
- docker-compose.e2e.local.yml: local FRONTEND_URL/ALLOWED_ORIGINS/VITE_API_URL for testing
- AuthContext: new/non-entitled sign-ins land on pricing to start the trial
- ProfileMenu: header account dropdown (email, account & billing, sign out)
- MediaInput: "YouTube URL" → "Video URL" + supported-platforms info popover
2026-07-16 02:07:53 +02:00
juancarlos.cavero
0ba4fac47b feat: durable video library on Cloudflare R2 (history + retention)
- cloud/storage.py: R2 (S3-compatible) client — upload, presigned view/download
  URLs, delete-by-prefix.
- cloud/videos.py: archive a completed managed job's clips to R2 under
  users/<uid>/<job>/, GET /api/history (private signed links), and a retention
  sweeper that deletes a user's videos 7 days after their subscription ends.
- models.py: user_videos table (created via create_all).
- app.py: archive clips to R2 on managed-job completion.
- billing.py: email the admin the moment a subscriber hits cancel.
- Frontend: History tab (library grid with per-video view + download).

R2 bucket 'openshorts-videos' + scoped API token created; end-to-end verified:
archive -> presigned GET (200) -> purge after grace -> object 404.
2026-07-14 14:56:40 +02:00
juancarlos.cavero
12d423d739 feat: 720p->360p download fallback + SMTP email alerts
- main.py / metering.py: try the HD (bgutil/720p) strategy first, fall back to
  the conservative (360p) clients on any failure, so a YouTube/yt-dlp change
  degrades gracefully instead of failing the whole job.
- cloud/alerts.py: in-memory tracking of managed-job outcomes; emails the admin
  (ADMIN_EMAIL) when a proxy/credit error appears or when many jobs fail in a
  row, with a 1h per-alert cooldown. Wired into run_job_wrapper.
- Email switched from Resend to SMTP (cloud/emails.py) for magic link + alerts
  (Namecheap Private Email). Config via SMTP_* / EMAIL_FROM / ADMIN_EMAIL in the
  mounted .env (kept out of compose so the password's $/* aren't mangled).

SMTP send verified from host and from the backend container.
2026-07-14 14:00:02 +02:00
juancarlos.cavero
ebe876c497 feat: unlock 720p/1080p YouTube downloads (Deno + bgutil PO tokens)
YouTube now forces SABR streaming, capping downloads at 360p without a GVS PO
token. Adds the full recipe (cloud mode only):
- Dockerfile: Deno JS runtime (nsig challenge) + latest yt-dlp[default] nightly
  + bgutil-ytdlp-pot-provider plugin
- docker-compose.cloud.yml: bgutil PO-token sidecar + BGUTIL_BASE_URL
- main.py / metering.py: when BGUTIL_BASE_URL is set, use yt-dlp default clients
  + the bgutil HTTP provider (→ 720p); self-host keeps the conservative fallback

Verified E2E through the container: managed user -> YouTube -> DataImpulse
residential proxy + Deno + bgutil -> real 720p (format 136) download, no 403.
2026-07-14 13:42:07 +02:00