From 1d9fef7445d8b3b10ff14ce60d155f4765d81ec8 Mon Sep 17 00:00:00 2001
From: "juancarlos.cavero"
Date: Mon, 24 Aug 2026 19:12:05 +0200
Subject: [PATCH] feat(cloud): self-service account deletion (GDPR art. 17)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
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.
---
CLAUDE.md | 26 ++
app.py | 44 +++
cloud/__init__.py | 3 +-
cloud/account.py | 312 ++++++++++++++++++
cloud/config.py | 5 +
cloud/emails.py | 28 ++
cloud/models.py | 30 ++
cloud/videos.py | 2 +
dashboard/seo/legal.js | 29 +-
dashboard/src/Legal.jsx | 3 +-
dashboard/src/components/AccountPage.jsx | 3 +
.../src/components/DeleteAccountCard.jsx | 124 +++++++
dashboard/src/main.jsx | 25 ++
tests/test_account_erasure.py | 64 ++++
14 files changed, 687 insertions(+), 11 deletions(-)
create mode 100644 cloud/account.py
create mode 100644 dashboard/src/components/DeleteAccountCard.jsx
create mode 100644 tests/test_account_erasure.py
diff --git a/CLAUDE.md b/CLAUDE.md
index 70fcc07..bbef33e 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -176,6 +176,7 @@ se desactiva porque el modelo diga `none`.
| POST | `/api/social/post` | Post to social media (async upload) |
| POST | `/mcp` | MCP server (JSON-RPC): the pipeline as agent tools |
| POST/GET/DELETE | `/api/keys` | User API keys (cloud mode, session JWT only) |
+| DELETE | `/api/account` | Erase the account and everything in it (GDPR art. 17) |
### Agent access (MCP, API keys, webhooks)
@@ -197,6 +198,31 @@ se desactiva porque el modelo diga `none`.
can carry durable download links; survives redeploys via the resume manifest.
`PUBLIC_API_URL` env sets the absolute-URL base when behind a proxy.
+### Account erasure (GDPR art. 17)
+
+`DELETE /api/account` (`cloud/account.py`, dashboard: Account → Delete account)
+is immediate and irreversible: there is no recovery window because after the
+delete there is nothing left to authenticate a recovery request against. It
+refuses API-key auth (a leaked `osk_` must not destroy its own account) and
+requires the caller to retype the account email.
+
+The order of the steps is the design, and each one is a failure mode:
+**Stripe cancel first**, aborting the whole thing if it fails, so we never erase
+a user we are still billing; **R2 before the database**, because those rows are
+the only index of which objects are theirs and dropping them first turns a
+failed purge into permanent orphans; the DB delete is **one transaction** over
+an explicit table list (`USER_OWNED_TABLES`) rather than the declared ON DELETE
+CASCADEs, since `create_all` never ALTERs an existing table and a constraint
+added after a table shipped exists in the models but not in production.
+`tests/test_account_erasure.py` fails if a new table references `users.id`
+without joining that list.
+
+What deliberately survives: the Stripe customer and its invoices (6-year
+retention, Spanish commercial law) and one `account_deletions` row holding a
+sha256 of the email as proof the erasure happened, itself purged after 5 years.
+`app.py` registers a callback so the local `output/` and `uploads/` working
+files go too, instead of waiting for the hourly sweep.
+
### Concurrency Model
Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour.
diff --git a/app.py b/app.py
index e003d18..4cf8ecf 100644
--- a/app.py
+++ b/app.py
@@ -1218,6 +1218,47 @@ async def _settle_reservation(job_id):
except Exception as e:
print(f"⚠️ Reservation settle error for {job_id}: {e}")
+def _purge_local_jobs_for_user(user_id) -> int:
+ """Delete this user's job dirs, source uploads and in-memory job records.
+
+ Called by cloud/account.py when an account is erased. The durable copies
+ live on R2 and are deleted there; these are the working files on the API's
+ own disk, which would otherwise sit around until the one-hour cleanup sweep
+ — a long time to keep the videos of someone who just asked to be forgotten.
+
+ Ownership comes from the ``.owner`` file each managed job writes, so jobs
+ recovered from disk after a restart (no in-memory record) are covered too.
+ """
+ uid = str(user_id)
+ job_ids = {jid for jid, job in list(jobs.items())
+ if job.get('user_id') is not None and str(job['user_id']) == uid}
+ try:
+ entries = os.listdir(OUTPUT_DIR)
+ except OSError:
+ entries = []
+ for job_id in entries:
+ owner_path = os.path.join(OUTPUT_DIR, job_id, ".owner")
+ try:
+ with open(owner_path) as f:
+ if f.read().strip() == uid:
+ job_ids.add(job_id)
+ except OSError:
+ continue
+
+ for job_id in job_ids:
+ shutil.rmtree(os.path.join(OUTPUT_DIR, job_id), ignore_errors=True)
+ jobs.pop(job_id, None)
+ # Source uploads are named "_" (see /api/process).
+ for path in glob.glob(os.path.join(UPLOAD_DIR, f"{glob.escape(job_id)}_*")):
+ try:
+ os.remove(path)
+ except OSError:
+ pass
+ if job_ids:
+ print(f"🗑️ Purged {len(job_ids)} local job dir(s) for erased user {uid}.")
+ return len(job_ids)
+
+
@asynccontextmanager
async def lifespan(app: FastAPI):
# Rehydrate finished jobs from disk before serving (survives restarts).
@@ -1230,6 +1271,9 @@ async def lifespan(app: FastAPI):
cleanup_task = asyncio.create_task(cleanup_jobs())
if BILLING_ENABLED:
await cloud.setup_async(app, keep_reservation_ids=_resumed_reservation_ids)
+ # Account erasure lives in cloud/, which can't import app.py; hand it the
+ # one thing only this module can do — wipe the local working files.
+ cloud.account.register_local_purge(_purge_local_jobs_for_user)
# Nag on Telegram while the residential proxy is down/out of credits —
# a single job-failure alert is easy to miss and ingest stays broken
# until someone tops the balance up.
diff --git a/cloud/__init__.py b/cloud/__init__.py
index e59665a..8be2a51 100644
--- a/cloud/__init__.py
+++ b/cloud/__init__.py
@@ -26,7 +26,7 @@ def setup_sync(app):
from starlette.middleware.sessions import SessionMiddleware
app.add_middleware(SessionMiddleware, secret_key=settings.jwt_secret)
- from . import auth, oauth, billing, social_profiles, videos, api_keys
+ from . import auth, oauth, billing, social_profiles, videos, api_keys, account
oauth.register()
billing._init_stripe()
app.include_router(auth.router)
@@ -35,6 +35,7 @@ def setup_sync(app):
app.include_router(social_profiles.router)
app.include_router(videos.router)
app.include_router(api_keys.router)
+ app.include_router(account.router)
async def setup_async(app, keep_reservation_ids=None):
diff --git a/cloud/account.py b/cloud/account.py
new file mode 100644
index 0000000..c83c0d3
--- /dev/null
+++ b/cloud/account.py
@@ -0,0 +1,312 @@
+"""Account erasure: the GDPR Art. 17 "right to be forgotten", self-service.
+
+The privacy policy already promises that "deleting your account from the
+dashboard removes your content on the schedule above" — this is the code that
+makes that sentence true. It is one endpoint, ``DELETE /api/account``, and it
+is immediate and irreversible: erasure has to happen "without undue delay", and
+once the account is gone there is no way left to authenticate whoever asks for
+it back, so a recovery window would be a window nobody could safely use.
+
+Two rules shape the order of operations below, and both come from asking what
+happens when a step fails halfway:
+
+1. **Stripe first, and abort if it refuses.** Deleting the user row while a
+ live subscription keeps charging a card we can no longer map to anyone turns
+ a privacy fix into a billing incident nobody can unwind. Cancelling first
+ means the worst case is a cancelled subscription on an account that still
+ exists — annoying, retryable, harmless.
+2. **R2 before the database.** Those DB rows are the only index of which
+ objects belong to this user. Drop them first and a failed R2 delete leaves
+ objects that nothing in the system can ever find again; the bucket already
+ carries orphans from an earlier version of this reasoning.
+
+What deliberately survives: the Stripe customer and its invoices (six-year
+retention under Spanish commercial law, privacy policy §5) and one
+[AccountDeletion] row holding a sha256 of the email — proof the erasure
+happened, with no readable identity in it.
+"""
+import asyncio
+import hashlib
+from datetime import datetime, timezone, timedelta
+from typing import Optional
+
+from fastapi import APIRouter, HTTPException, Request
+from pydantic import BaseModel
+from sqlalchemy import select, delete, func
+
+from .config import settings, DELETION_LOG_RETENTION_DAYS
+from . import database, email_policy, storage
+from .models import (
+ User, Subscription, CreditTopup, UsageLedger, MagicLinkToken,
+ SignupAttribution, ApiKey, UploadPostProfile, UserVideo, ClipExpiryWarning,
+ Project, AccountDeletion,
+)
+
+# Every table that holds rows belonging to a user, child-first (clip_expiry_
+# warnings points at user_videos as well as at users).
+#
+# These are all declared ON DELETE CASCADE, so in theory deleting the user row
+# is enough. We delete them by hand anyway: the schema is bootstrapped with
+# ``create_all``, which never ALTERs an existing table, so a constraint added
+# after a table first appeared in production exists in the models and not in
+# the database. Trusting the cascade would mean the difference shows up as a
+# foreign-key violation the first time a real user tries to leave.
+USER_OWNED_TABLES = (
+ ClipExpiryWarning, UserVideo, Project, UsageLedger, CreditTopup,
+ Subscription, ApiKey, SignupAttribution, UploadPostProfile,
+)
+
+router = APIRouter()
+
+# Job dirs on the API's own disk belong to app.py, which cannot be imported from
+# here (the dependency runs the other way). It registers a purge callback at
+# startup instead; when it hasn't, local files simply age out on their usual
+# one-hour cleanup.
+_local_purge = None
+
+
+def register_local_purge(fn):
+ """Let app.py hand us a ``(user_id) -> int`` local-file purge."""
+ global _local_purge
+ _local_purge = fn
+
+
+def _now():
+ return datetime.now(timezone.utc)
+
+
+def email_fingerprint(email: str) -> str:
+ """The only trace of an address that outlives the account."""
+ return hashlib.sha256(email_policy.normalize_email(email).encode()).hexdigest()
+
+
+async def _session_user(request: Request):
+ """The signed-in user, refusing API-key auth.
+
+ Same reasoning as key management in cloud/api_keys.py: a leaked ``osk_``
+ token must not be able to destroy the account it was issued from.
+ """
+ from . import api_keys
+ from .auth import get_current_user_required
+
+ auth = request.headers.get("Authorization", "")
+ if api_keys.looks_like_key(auth[7:].strip()) or api_keys.looks_like_key(
+ request.headers.get("X-API-Key", "")):
+ raise HTTPException(status_code=403, detail=(
+ "API keys cannot delete an account. Sign in to the dashboard."))
+ return await get_current_user_required(request)
+
+
+# --------------------------------------------------------------------------- #
+# The steps
+# --------------------------------------------------------------------------- #
+async def _cancel_subscriptions(user_id) -> Optional[str]:
+ """Cancel every Stripe subscription on the account, immediately.
+
+ Returns the plan that was live (for the deletion record), or None. Raises
+ on a Stripe error so the caller can abort before anything is erased — see
+ rule 1 in the module docstring.
+ """
+ import stripe
+
+ async with database.session() as session:
+ rows = list((await session.execute(
+ select(Subscription).where(Subscription.user_id == user_id)
+ )).scalars())
+
+ live = [r for r in rows if r.status not in ("canceled", "incomplete_expired")]
+ plan = live[0].plan if live else (rows[0].plan if rows else None)
+ for row in live:
+ try:
+ # cancel(), not cancel_at_period_end: the user is leaving now, and
+ # billing them again for a service whose data we just erased would
+ # be indefensible. Unused time is refunded as it always is.
+ await asyncio.to_thread(lambda sid=row.stripe_subscription_id:
+ stripe.Subscription.cancel(sid))
+ except stripe.InvalidRequestError as e:
+ # Stripe says this subscription is gone or already cancelled. Our
+ # row can be stale — a cancellation made in the portal whose webhook
+ # never landed leaves it reading "active" forever. Treating that as
+ # a hard error would trap the user: the one account that cannot be
+ # deleted is the one Stripe already stopped billing.
+ print(f"ℹ️ Subscription {row.stripe_subscription_id} already gone at Stripe: {e}")
+ return plan
+
+
+async def _delete_upload_post_profile(user_id):
+ """Remove the user's white-label profile (and its connected socials) at
+ Upload-Post. Best effort: a stale empty profile there holds no content of
+ ours, and failing the whole erasure over a third-party 500 would be worse.
+ """
+ import httpx
+ from .social_profiles import API_BASE, _auth_headers
+
+ async with database.session() as session:
+ prof = await session.get(UploadPostProfile, user_id)
+ if prof is None:
+ return
+ username = prof.profile_username
+
+ try:
+ async with httpx.AsyncClient(timeout=20) as client:
+ resp = await client.request(
+ "DELETE", f"{API_BASE}/uploadposts/users",
+ headers={**_auth_headers(), "Content-Type": "application/json"},
+ json={"username": username},
+ )
+ if resp.status_code not in (200, 204, 404):
+ print(f"⚠️ Upload-Post profile delete returned {resp.status_code} for {username}")
+ except Exception as e:
+ print(f"⚠️ Upload-Post profile delete failed for {username}: {e}")
+
+
+async def _erase_rows(user_id, email, stripe_customer_id, plan, r2_deleted, reason):
+ """Swap the account for its erasure record, in one transaction.
+
+ All-or-nothing on purpose: a half-erased account is worse than an un-erased
+ one, because the user is told they are gone while some of their rows are
+ not. Magic-link tokens are keyed by email rather than user id, so they need
+ their own statement on top of [USER_OWNED_TABLES].
+ """
+ async with database.session() as session:
+ async with session.begin():
+ session.add(AccountDeletion(
+ former_user_id=str(user_id),
+ email_sha256=email_fingerprint(email),
+ stripe_customer_id=stripe_customer_id,
+ plan_at_deletion=plan,
+ r2_objects_deleted=r2_deleted,
+ reason=reason,
+ ))
+ for model in USER_OWNED_TABLES:
+ await session.execute(
+ delete(model).where(model.user_id == user_id))
+ await session.execute(
+ delete(MagicLinkToken).where(MagicLinkToken.email == email))
+ await session.execute(delete(User).where(User.id == user_id))
+
+
+# --------------------------------------------------------------------------- #
+# Endpoint
+# --------------------------------------------------------------------------- #
+class DeleteAccountRequest(BaseModel):
+ # Typing the address is the confirmation step. Sessions last 30 days and
+ # there is no password to re-enter, so this is the strongest thing we can
+ # ask for without mailing a second token to a user who is leaving anyway.
+ confirm_email: str
+ reason: Optional[str] = None
+
+
+@router.delete("/api/account")
+async def delete_account(payload: DeleteAccountRequest, request: Request):
+ user = await _session_user(request)
+
+ if email_policy.normalize_email(payload.confirm_email) != \
+ email_policy.normalize_email(user.email):
+ raise HTTPException(status_code=400, detail=(
+ "That doesn't match the email on this account."))
+
+ async with database.session() as session:
+ row = await session.get(User, user.id)
+ if row is None:
+ raise HTTPException(status_code=404, detail="Account not found.")
+ email, stripe_customer_id = row.email, row.stripe_customer_id
+ # A reserved ledger row means a render is in flight. Erasing now would
+ # delete the output from under a job that is still writing it, and the
+ # reservation would never settle. Minutes are refunded on failure, so
+ # waiting costs the user nothing.
+ in_flight = (await session.execute(
+ select(func.count(UsageLedger.id)).where(
+ UsageLedger.user_id == user.id, UsageLedger.status == "reserved")
+ )).scalar_one()
+ if in_flight:
+ raise HTTPException(status_code=409, detail=(
+ "A video is still processing. Wait for it to finish, then delete "
+ "your account."))
+
+ try:
+ plan = await _cancel_subscriptions(user.id)
+ except Exception as e:
+ print(f"⚠️ Account deletion aborted, Stripe cancel failed for {user.id}: {e}")
+ raise HTTPException(status_code=502, detail=(
+ "We couldn't cancel your subscription, so nothing was deleted. "
+ "Please try again, or email info@openshorts.app."))
+
+ # Storage before the third party: if the bucket refuses, the only thing that
+ # has changed so far is the cancelled subscription, and the error below can
+ # say so truthfully.
+ r2_deleted = None
+ if settings.r2_configured:
+ try:
+ r2_deleted = await asyncio.to_thread(
+ storage.delete_prefix, storage.user_prefix(user.id))
+ except Exception as e:
+ print(f"⚠️ Account deletion aborted, R2 purge failed for {user.id}: {e}")
+ raise HTTPException(status_code=502, detail=(
+ "We couldn't reach the storage that holds your clips, so your "
+ "account was not deleted. Your subscription has already been "
+ "cancelled. Please try again, or email info@openshorts.app."))
+
+ if _local_purge is not None:
+ try:
+ _local_purge(user.id)
+ except Exception as e:
+ print(f"⚠️ Local job purge failed for {user.id}: {e}")
+
+ await _delete_upload_post_profile(user.id)
+
+ reason = (payload.reason or "").strip()[:500] or None
+ try:
+ await _erase_rows(user.id, email, stripe_customer_id, plan, r2_deleted, reason)
+ except Exception as e:
+ # The content is already gone; only the account row survived. Say that
+ # rather than a bare 500 — the user needs to know a retry is safe and
+ # that the account they can still sign into is now empty.
+ print(f"⚠️ Account row delete failed for {user.id} after purge: {e}")
+ raise HTTPException(status_code=500, detail=(
+ "Your clips were deleted but we couldn't close the account itself. "
+ "Please try again, or email info@openshorts.app."))
+ # ``email`` was read before the delete on purpose: from here on the address
+ # exists nowhere in our systems, and the goodbye email still has to go out.
+
+ print(f"🗑️ Account erased: {user.id} (plan={plan}, r2_objects={r2_deleted})")
+
+ # Everything below is after-the-fact and must never fail the deletion.
+ try:
+ # OpenPanel only ever received the account uuid, never the address (see
+ # cloud/analytics.py), and it expires those identifiers on its own
+ # 13-month schedule — so this event adds no identity, it just makes the
+ # one churn signal we cannot otherwise see countable.
+ from . import analytics
+ analytics.track("AccountDeleted", user_id=user.id, plan=plan)
+ except Exception:
+ pass
+ try:
+ from .emails import send_account_deleted_email
+ await send_account_deleted_email(email)
+ except Exception as e:
+ print(f"⚠️ Goodbye email failed: {e}")
+ try:
+ from .alerts import send_telegram
+ await send_telegram(f"🗑️ Account deleted (plan: {plan or 'free'})")
+ except Exception:
+ pass
+
+ return {"deleted": True, "r2_objects_deleted": r2_deleted}
+
+
+# --------------------------------------------------------------------------- #
+# Retention
+# --------------------------------------------------------------------------- #
+async def purge_stale_deletion_records():
+ """Drop erasure records past their own retention window.
+
+ The log exists to answer a complaint; once claims are time-barred it is
+ just a hashed address we have no reason to hold. Called from the video
+ retention sweeper.
+ """
+ cutoff = _now() - timedelta(days=DELETION_LOG_RETENTION_DAYS)
+ async with database.session() as session:
+ async with session.begin():
+ await session.execute(
+ delete(AccountDeletion).where(AccountDeletion.deleted_at < cutoff))
diff --git a/cloud/config.py b/cloud/config.py
index 99ffbd3..b0c056f 100644
--- a/cloud/config.py
+++ b/cloud/config.py
@@ -277,6 +277,11 @@ class Settings:
# Days a user's videos survive after their subscription ends (grace period).
VIDEO_RETENTION_GRACE_DAYS = 7
+# How long the erasure log (cloud/models.AccountDeletion) is kept. Matches the
+# "rights declarations and related logs: up to 5 years" line in the privacy
+# policy, which in turn matches the statute of limitations for civil claims.
+DELETION_LOG_RETENTION_DAYS = 5 * 365
+
settings = Settings()
diff --git a/cloud/emails.py b/cloud/emails.py
index 3d4cd08..12612d0 100644
--- a/cloud/emails.py
+++ b/cloud/emails.py
@@ -140,3 +140,31 @@ async def send_out_of_minutes_email(email: str, upgrade_url: str):
"""
print(f"✉️ Out-of-minutes upsell email → {email}")
await send_email(email, "Your video is waiting — you're out of free minutes", html)
+
+
+async def send_account_deleted_email(email: str):
+ """Confirmation that an account was erased. Sent last, to an address we no
+ longer hold: this is the only notice the user will ever get, and it is also
+ the only signal they would have if the deletion had not been theirs.
+ """
+ html = """
+
+
Your OpenShorts account has been deleted
+
Everything is gone: your account, your projects, your clips and their
+ transcripts, your API keys, and the connection to any social accounts
+ you had linked. Any active subscription was cancelled.
+
Two things we keep, and why:
+
+
Your invoices, for six years — Spanish
+ commercial law requires it.
+
A record that this deletion happened, holding a
+ one-way hash of your email address and nothing else.
+
+
You can sign up again any time with the same address; it will be a
+ brand-new, empty account.
+
If this wasn't you, reply to this
+ email straight away — info@openshorts.app.
+
+ """
+ print(f"✉️ Account-deleted confirmation → {email}")
+ await send_email(email, "Your OpenShorts account has been deleted", html)
diff --git a/cloud/models.py b/cloud/models.py
index 1fe0073..4e6705b 100644
--- a/cloud/models.py
+++ b/cloud/models.py
@@ -221,3 +221,33 @@ class StripeEvent(Base):
type = Column(Text, nullable=True)
created = Column(DateTime(timezone=True), nullable=True)
processed_at = Column(DateTime(timezone=True), server_default=func.now())
+
+
+class AccountDeletion(Base):
+ """Proof that an account was erased, kept after the user row is gone.
+
+ GDPR Art. 17 erasure has an accountability twin (Art. 5.2): if a former user
+ later claims we never deleted their account, the only way to answer is a
+ record that outlives the deletion. So this holds no readable identity — a
+ sha256 of the account email, which can confirm "yes, this address was
+ deleted on this date" without storing the address itself.
+
+ ``stripe_customer_id`` is the one exception and it is deliberate: the
+ invoices behind it must be kept for six years under Spanish commercial law,
+ so the reference that lets us find them survives too (privacy policy §5).
+ There is no FK to ``users`` — the whole point is that the row it would
+ reference no longer exists.
+
+ Rows are dropped after DELETION_LOG_RETENTION_DAYS by the retention sweeper,
+ matching the "rights declarations and related logs: up to 5 years" line in
+ the privacy policy.
+ """
+ __tablename__ = "account_deletions"
+ id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid)
+ former_user_id = Column(Text, nullable=False) # the old uuid, resolves to nothing now
+ email_sha256 = Column(Text, nullable=False, index=True)
+ stripe_customer_id = Column(Text, nullable=True)
+ plan_at_deletion = Column(String(20), nullable=True)
+ r2_objects_deleted = Column(Integer, nullable=True)
+ reason = Column(Text, nullable=True) # optional free-text the user typed
+ deleted_at = Column(DateTime(timezone=True), server_default=func.now())
diff --git a/cloud/videos.py b/cloud/videos.py
index 3db1ed4..0643ace 100644
--- a/cloud/videos.py
+++ b/cloud/videos.py
@@ -462,6 +462,8 @@ async def _sweeper_loop():
await purge_free_expired()
from .auth import purge_stale_magic_tokens
await purge_stale_magic_tokens()
+ from .account import purge_stale_deletion_records
+ await purge_stale_deletion_records()
except asyncio.CancelledError:
break
except Exception as e:
diff --git a/dashboard/seo/legal.js b/dashboard/seo/legal.js
index 261ea44..cab8b48 100644
--- a/dashboard/seo/legal.js
+++ b/dashboard/seo/legal.js
@@ -18,7 +18,7 @@
* service; AI labelling follows AI Act art. 50.
*/
-const PUBLISHED = '2026-08-19'
+const PUBLISHED = '2026-08-24'
const TERMS_EN = `
1. Who we are
@@ -608,10 +608,15 @@ of limitations for civil claims.
You can ask us for access, rectification, erasure, restriction, portability
of your data, and object to processing based on legitimate interest — just
email info@openshorts.app from your account address; we answer within one
-month. Deleting your account from the dashboard removes your content on the
-schedule above. If you believe we are mishandling your data, you can complain
-to the Spanish supervisory authority (AEPD, aepd.es) or to the authority of
-your own EU country.
+month. You do not need to ask us to erase your account: Account →
+Delete account in the dashboard does it yourself, immediately and
+permanently, taking your projects, clips, transcripts, API keys and social
+connections with it and cancelling any active subscription. Two things survive
+it, both listed in section 5: your invoices, which tax law requires us to keep,
+and a one-way hash of your email address recording that the deletion happened.
+If you believe we are mishandling your data, you can complain to the Spanish
+supervisory authority (AEPD, aepd.es) or to the authority of your own EU
+country.
7. Age
The service is not directed at children. You must be at least 16, or the
@@ -739,10 +744,16 @@ meses.
Puedes pedirnos acceso, rectificación, supresión, limitación y portabilidad
de tus datos, y oponerte a los tratamientos basados en interés legítimo —
basta un email a info@openshorts.app desde la dirección de tu cuenta;
-respondemos en el plazo de un mes. Eliminar tu cuenta desde el panel elimina tu
-contenido con el calendario indicado arriba. Si crees que tratamos mal tus
-datos, puedes reclamar ante la Agencia Española de Protección de Datos (AEPD,
-aepd.es) o ante la autoridad de tu país de la UE.
+respondemos en el plazo de un mes. Para la supresión no necesitas pedírnosla:
+Cuenta → Eliminar cuenta en el panel la ejecuta tú mismo, de
+forma inmediata y permanente, y se lleva por delante tus proyectos, clips,
+transcripciones, claves de API y conexiones con redes sociales, además de
+cancelar cualquier suscripción activa. Solo sobreviven dos cosas, ambas
+recogidas en el apartado 5: tus facturas, que la normativa fiscal nos obliga a
+conservar, y un hash irreversible de tu dirección de email que acredita que la
+eliminación se produjo. Si crees que tratamos mal tus datos, puedes reclamar
+ante la Agencia Española de Protección de Datos (AEPD, aepd.es) o ante la
+autoridad de tu país de la UE.
7. Edad
El servicio no está dirigido a menores. Para crear una cuenta debes tener al
diff --git a/dashboard/src/Legal.jsx b/dashboard/src/Legal.jsx
index 266dbc0..6239c46 100644
--- a/dashboard/src/Legal.jsx
+++ b/dashboard/src/Legal.jsx
@@ -6,7 +6,7 @@ import { ArrowLeft, FileText, Shield, Landmark } from 'lucide-react';
// versions). This in-app view is a hub with the plain-language summary and
// links, so the SPA route (#legal) and the crawlable pages never drift: the
// full text lives in exactly one place.
-const LAST_UPDATED = '2026-08-19';
+const LAST_UPDATED = '2026-08-24';
const SUPPORT_EMAIL = 'info@openshorts.app';
const DOCS = [
@@ -59,6 +59,7 @@ export default function Legal() {
You must have the rights to every video you upload or link, and you are the publisher of what you post.
No third-party trackers. Analytics is self-hosted; free-plan clips are deleted after 7 days.
Cancel anytime from your account. EU consumers keep their 14-day withdrawal right.
+
Delete everything anytime. Account → Delete account erases your projects, clips and keys on the spot. No email to us, no waiting.
The full documents (English, with Spanish versions that prevail for consumers in Spain):
diff --git a/dashboard/src/components/AccountPage.jsx b/dashboard/src/components/AccountPage.jsx
index 414bd95..af44189 100644
--- a/dashboard/src/components/AccountPage.jsx
+++ b/dashboard/src/components/AccountPage.jsx
@@ -4,6 +4,7 @@ import { useAuth } from '../contexts/AuthContext';
import { apiJson } from '../lib/api';
import { track } from '../lib/analytics';
import ApiKeysCard from './ApiKeysCard';
+import DeleteAccountCard from './DeleteAccountCard';
import SocialAnalyticsCard from './SocialAnalyticsCard';
const fmt1 = (n) => Math.round((n || 0) * 10) / 10;
@@ -203,6 +204,8 @@ export default function AccountPage() {
)}
+
+
);
}
diff --git a/dashboard/src/components/DeleteAccountCard.jsx b/dashboard/src/components/DeleteAccountCard.jsx
new file mode 100644
index 0000000..f738aea
--- /dev/null
+++ b/dashboard/src/components/DeleteAccountCard.jsx
@@ -0,0 +1,124 @@
+import React, { useState, useCallback } from 'react';
+import { Trash2, AlertTriangle, Loader2 } from 'lucide-react';
+import { useAuth } from '../contexts/AuthContext';
+import { apiJson } from '../lib/api';
+
+// GDPR Art. 17 erasure, self-service (backend: cloud/account.py). The privacy
+// policy tells users they can delete their account from the dashboard, so this
+// has to be findable — but it is also irreversible, hence: collapsed by
+// default, an itemised list of what actually goes, and typing the account email
+// as the confirmation step (there is no password to re-enter; sign-in is a
+// magic link).
+export default function DeleteAccountCard() {
+ const { me, logout } = useAuth();
+ const [open, setOpen] = useState(false);
+ const [confirm, setConfirm] = useState('');
+ const [reason, setReason] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState('');
+
+ const email = me?.user?.email || '';
+ const matches = confirm.trim().toLowerCase() === email.toLowerCase();
+
+ const remove = useCallback(async () => {
+ setBusy(true);
+ setError('');
+ try {
+ await apiJson('/api/account', {
+ method: 'DELETE',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ confirm_email: confirm.trim(), reason: reason.trim() || undefined }),
+ });
+ // The session token now points at nothing. Drop it before navigating, or
+ // the landing page spends a request discovering that for itself. The
+ // funnel flags go too: they are the only reason a re-signup with the same
+ // address would behave like a returning user rather than a fresh one.
+ logout();
+ try {
+ localStorage.removeItem('os_socials_prompted');
+ localStorage.removeItem('os_pending_checkout');
+ } catch (_) { /* ignore */ }
+ window.location.hash = '#/deleted';
+ window.location.reload();
+ } catch (e) {
+ setError(e?.detail || 'Could not delete your account. Please try again or email info@openshorts.app.');
+ setBusy(false);
+ }
+ }, [confirm, reason, logout]);
+
+ return (
+
+
+ Delete account
+
+
+ Close your OpenShorts account and erase everything we hold about you. This
+ cannot be undone.
+
+
+ {!open ? (
+
+ ) : (
+
+
+
+
+ This is permanent. There is no recovery.
+
+
Deleted immediately:
+
+
your account and sign-in
+
every project, clip and transcript, here and in our storage
+
your API keys, so anything using them stops working
+
the link to any social accounts you connected
+
+
+ Any active subscription is cancelled as part of this. We keep your
+ invoices for six years because Spanish law requires it, plus a
+ one-way hash of your email as proof the deletion happened.
+
+
+
+
+
+
+
+ {error &&
{error}
}
+
+
+
+
+
+
+ )}
+
+ );
+}
diff --git a/dashboard/src/main.jsx b/dashboard/src/main.jsx
index 65fe03c..825a23c 100644
--- a/dashboard/src/main.jsx
+++ b/dashboard/src/main.jsx
@@ -43,11 +43,35 @@ function AccountView() {
return ;
}
+// Landing spot after an account is erased. Its own view because the session is
+// gone: sending the user to #/account would bounce them to pricing with no
+// explanation, and "openshorts_skip_landing" would send them into the app.
+function DeletedView() {
+ return (
+
+
+
Your account is deleted
+
+ Your projects, clips and transcripts are gone, any subscription is
+ cancelled, and your API keys no longer work. We've emailed you a
+ confirmation with the details.
+
+
+ You're welcome back any time — signing up again with the same address
+ starts a brand-new, empty account.
+
+ );
+}
+
function Root() {
const resolveView = () => {
const hash = window.location.hash || '';
if (hash.startsWith('#/auth/')) return 'auth'; // AuthContext consumes then redirects
if (hash.startsWith('#/account')) return 'account';
+ if (hash.startsWith('#/deleted')) return 'deleted';
if (hash.startsWith('#/pricing')) return 'pricing';
if (hash === '#legal') return 'legal';
// #landing = explicit landing view (app logo); section anchors keep the landing mounted
@@ -73,6 +97,7 @@ function Root() {
if (view === 'legal') return ;
if (view === 'pricing') return ;
if (view === 'account') return ;
+ if (view === 'deleted') return ;
if (view === 'auth') {
return
Signing you in…
;
}
diff --git a/tests/test_account_erasure.py b/tests/test_account_erasure.py
new file mode 100644
index 0000000..8cdd2cc
--- /dev/null
+++ b/tests/test_account_erasure.py
@@ -0,0 +1,64 @@
+"""Account erasure (cloud/account.py): the GDPR Art. 17 delete.
+
+The one thing worth testing without a database is coverage. The endpoint tells
+the user everything is gone, so any table holding their rows that the delete
+list forgets turns that sentence into a false statement — and a table added a
+year from now is exactly the kind of thing nobody remembers to add here.
+"""
+import hashlib
+
+from cloud import account
+from cloud.database import Base
+from cloud.models import AccountDeletion, User
+
+
+def _tables_referencing_users():
+ """Every table with a foreign key into ``users`` — the ground truth the
+ delete list has to keep up with."""
+ found = set()
+ for table in Base.metadata.tables.values():
+ for fk in table.foreign_keys:
+ if fk.column.table.name == User.__tablename__:
+ found.add(table.name)
+ return found
+
+
+class TestCoverage:
+ def test_every_user_owned_table_is_erased(self):
+ listed = {m.__tablename__ for m in account.USER_OWNED_TABLES}
+ missing = _tables_referencing_users() - listed
+ assert not missing, (
+ f"{missing} reference users.id but are not erased on account "
+ f"deletion — add them to account.USER_OWNED_TABLES")
+
+ def test_children_are_deleted_before_their_parents(self):
+ # clip_expiry_warnings has an FK into user_videos, so deleting the
+ # videos first would trip that constraint.
+ order = [m.__tablename__ for m in account.USER_OWNED_TABLES]
+ assert order.index("clip_expiry_warnings") < order.index("user_videos")
+
+ def test_the_erasure_record_itself_is_not_erased(self):
+ # It has no FK to users on purpose (the row it would point at is gone),
+ # so it must not appear in the delete list either.
+ assert AccountDeletion not in account.USER_OWNED_TABLES
+ assert AccountDeletion.__tablename__ not in _tables_referencing_users()
+
+
+class TestEmailFingerprint:
+ def test_is_a_plain_sha256_of_the_normalised_address(self):
+ assert account.email_fingerprint("user@example.com") == \
+ hashlib.sha256(b"user@example.com").hexdigest()
+
+ def test_does_not_contain_the_address(self):
+ assert "user@example.com" not in account.email_fingerprint("user@example.com")
+
+ def test_survives_the_aliasing_the_account_key_ignores(self):
+ # Sign-up normalises Gmail dots and +tags, so the fingerprint has to
+ # match the same way or a deleted user could not be found by the
+ # address they actually typed.
+ assert account.email_fingerprint("Foo.Bar+news@gmail.com") == \
+ account.email_fingerprint("foobar@gmail.com")
+
+ def test_different_addresses_differ(self):
+ assert account.email_fingerprint("a@example.com") != \
+ account.email_fingerprint("b@example.com")