Deep-review round 4, targeted at round 3's changes (f569b19c..e7f38396). Accounts - Switching, adding or signing out an account moved the tab's pin before the page unloaded, so the players' resume beacons fired on the way out under the NEW account: one account's playback position saved into the other. The pin is now handed to the next page (pinOnNextPage) and taken over at import; clearActiveAccount is gone. - Switching to a suspended account was refused but left it in the switcher, refused on every click; a deactivated one was not refused at all, and made the default it signed every account in the browser out on the next request. Every account _session_user would refuse — gone, deactivated, suspended, revoked — is refused and dropped from the list. Share page (/watch) - An IPv6 client is limited by its /64 (client_ip becomes client_key, for every limiter): keyed on the full address, one subscriber could rotate through endless identities. The comments now state what the per-link ceiling costs: guessing from five networks can keep a link shut for its window, and guesses already running when it fills are still checked. - The link is looked up before the limiter records the attempt, so made-up tokens no longer grow it by an entry each. Forms - Failing the same way twice is announced again: the sign-in, passphrase and setup errors are keyed on the attempt (a clear and a set in one handler left the alert node untouched). - The install wizard's own validation showed the generic error — it threw plain objects its catch did not read. It sets the step's message. Tests: a re-pin leaving the previous account's notices behind; the pin hand-over; switching to an ended account; the /64 viewer; made-up tokens; the repeated alerts. Each mutation-checked RED for its own reason.
174 lines
8.3 KiB
Python
174 lines
8.3 KiB
Python
"""Public, login-free surface for shared download links (the `/watch/{token}` player page).
|
|
|
|
These routes are deliberately OUTSIDE the auth/`require_human` gate — the unguessable token IS the
|
|
credential (a capability URL). They only ever expose one file's stream + minimal metadata, never
|
|
the app or any account data. Password-protected links exchange the password once at `/unlock` for
|
|
a short-lived signed grant that the media URL carries (a `<video src>` can't send a header).
|
|
"""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request
|
|
from fastapi.responses import FileResponse
|
|
from pydantic import BaseModel
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.config import settings
|
|
from app.db import get_db
|
|
from app.downloads import links as linksmod
|
|
from app.downloads import storage
|
|
from app.models import DownloadJob, DownloadLink, MediaAsset
|
|
from app.ratelimit import RateLimiter, client_key
|
|
from app.security import verify_password
|
|
|
|
router = APIRouter(prefix="/api/public", tags=["public"])
|
|
|
|
# Slow password guessing on a link (the token itself is 192-bit, so it needs no throttle). Counted per
|
|
# viewer — the link AND the client (`client_key`) — so a client guessing wrong shuts out only itself, and a
|
|
# busy link's own unlocks don't count against its next viewer.
|
|
_unlock_limit = RateLimiter(max_events=10, window_seconds=300)
|
|
# ...under a ceiling on WRONG passwords for the link from every client together, so guessing spread over
|
|
# many addresses stays slow too; unlocking with the password never adds to it. The price of the ceiling:
|
|
# someone with the link but not its password, guessing from 50 / 10 = 5 networks, can keep the link shut
|
|
# for everyone until the window passes. It is checked before the password and counted after it, so guesses
|
|
# already running when it fills are still checked — as many as the route's threadpool runs at once.
|
|
_unlock_failures = RateLimiter(max_events=50, window_seconds=300)
|
|
|
|
|
|
def _link_or_404(db: Session, token: str) -> DownloadLink:
|
|
link = db.execute(select(DownloadLink).where(DownloadLink.token == token)).scalar_one_or_none()
|
|
if link is None or linksmod.is_expired(link):
|
|
raise HTTPException(status_code=404, detail="This link is no longer available.")
|
|
return link
|
|
|
|
|
|
def _ready_target(db: Session, link: DownloadLink) -> tuple[DownloadJob, MediaAsset]:
|
|
job = db.get(DownloadJob, link.job_id)
|
|
asset = db.get(MediaAsset, job.asset_id) if job and job.asset_id else None
|
|
if job is None or asset is None or asset.status != "ready" or not asset.rel_path:
|
|
raise HTTPException(status_code=404, detail="This video is no longer available.")
|
|
# Verify the file is actually on disk here (not just flagged ready), so the watch page never
|
|
# loads a player for a missing file — meta and file agree.
|
|
path = storage.safe_abs_path(settings.download_root, asset.rel_path)
|
|
if path is None:
|
|
raise HTTPException(status_code=404, detail="This video is no longer available.")
|
|
return job, asset
|
|
|
|
|
|
def _ready_asset(db: Session, link: DownloadLink) -> MediaAsset:
|
|
return _ready_target(db, link)[1]
|
|
|
|
|
|
def _file_url(token: str, grant: str | None = None) -> str:
|
|
base = f"/api/public/watch/{token}/file"
|
|
return f"{base}?g={grant}" if grant else base
|
|
|
|
|
|
def _poster_url(token: str, asset, grant: str | None = None) -> str | None:
|
|
if not asset.poster_path:
|
|
return None
|
|
base = f"/api/public/watch/{token}/poster.jpg"
|
|
return f"{base}?g={grant}" if grant else base
|
|
|
|
|
|
@router.get("/watch/{token}")
|
|
def watch_meta(token: str, db: Session = Depends(get_db)) -> dict:
|
|
"""Public metadata for the watch page. For a password link, returns only `needs_password`
|
|
until the viewer unlocks it (no title/thumbnail leak)."""
|
|
link = _link_or_404(db, token)
|
|
if link.password_hash:
|
|
return {"needs_password": True}
|
|
job, asset = _ready_target(db, link)
|
|
link.view_count += 1
|
|
db.commit()
|
|
return {
|
|
"needs_password": False,
|
|
**linksmod.public_meta(link, job, asset, _file_url(token), _poster_url(token, asset)),
|
|
}
|
|
|
|
|
|
class WatchUnlockIn(BaseModel):
|
|
password: str = ""
|
|
|
|
|
|
@router.post("/watch/{token}/unlock")
|
|
def watch_unlock(
|
|
token: str, body: WatchUnlockIn, request: Request, db: Session = Depends(get_db)
|
|
) -> dict:
|
|
"""Exchange the link password for a signed grant carried by the media URL."""
|
|
# The link first: a token naming none must leave no limiter entry behind, or posting made-up tokens
|
|
# would grow the limiter without bound.
|
|
link = _link_or_404(db, token)
|
|
viewer = f"{token}|{client_key(request)}"
|
|
if _unlock_failures.exhausted(token) or not _unlock_limit.allow(viewer):
|
|
raise HTTPException(status_code=429, detail="Too many attempts. Try again later.")
|
|
if not link.password_hash:
|
|
# Not a password link — nothing to unlock; just hand back the plain meta.
|
|
job, asset = _ready_target(db, link)
|
|
return {
|
|
"needs_password": False,
|
|
**linksmod.public_meta(link, job, asset, _file_url(token), _poster_url(token, asset)),
|
|
}
|
|
if not verify_password(body.password, link.password_hash):
|
|
_unlock_failures.allow(token)
|
|
raise HTTPException(status_code=403, detail="Wrong password.")
|
|
job, asset = _ready_target(db, link)
|
|
link.view_count += 1
|
|
db.commit()
|
|
grant = linksmod.make_grant(token, link.password_version)
|
|
return {
|
|
"needs_password": False,
|
|
**linksmod.public_meta(
|
|
link, job, asset, _file_url(token, grant), _poster_url(token, asset, grant)
|
|
),
|
|
}
|
|
|
|
|
|
@router.get("/watch/{token}/file")
|
|
def watch_file(token: str, g: str | None = None, db: Session = Depends(get_db)):
|
|
"""Range-aware stream of the shared file. Inline by default (plays in the page); an
|
|
`allow_download` link serves it as an attachment. Password links require a valid grant."""
|
|
link = _link_or_404(db, token)
|
|
if link.password_hash and not linksmod.check_grant(token, g, link.password_version):
|
|
raise HTTPException(status_code=403, detail="This link needs a password.")
|
|
asset = _ready_asset(db, link)
|
|
path = storage.safe_abs_path(settings.download_root, asset.rel_path)
|
|
if path is None:
|
|
raise HTTPException(status_code=404, detail="This video is no longer available.")
|
|
|
|
filename = storage.download_filename(asset.title or "video", asset.container, path)
|
|
# The served Content-Type comes from the asset's ffprobe-verified media_kind + a container
|
|
# allow-list (storage.served_media_type) — NEVER guessed from the file's own extension. A generic
|
|
# 'file' (and any media whose container we don't positively recognise, e.g. a media/HTML polyglot
|
|
# named "evil.html") returns None → a neutral force-download attachment, so arbitrary uploaded
|
|
# HTML/SVG can't execute inline on this login-free public origin. A recognised media container is
|
|
# served with its real audio/video type, inline unless the link forces a download so it can play
|
|
# in the watch page. Both are range-aware (FileResponse → 206) for seeking/resume.
|
|
media_type = storage.served_media_type(asset.media_kind, asset.container)
|
|
if media_type is None:
|
|
return FileResponse(
|
|
path,
|
|
filename=filename,
|
|
media_type="application/octet-stream",
|
|
content_disposition_type="attachment",
|
|
)
|
|
disposition = "attachment" if link.allow_download else "inline"
|
|
return FileResponse(
|
|
path, filename=filename, media_type=media_type, content_disposition_type=disposition
|
|
)
|
|
|
|
|
|
@router.get("/watch/{token}/poster.jpg")
|
|
def watch_poster(token: str, g: str | None = None, db: Session = Depends(get_db)):
|
|
"""The generated poster frame for a shared thumbnail-less video (used as the page/video poster
|
|
and the link-preview image). Password links require a valid grant, like the file."""
|
|
link = _link_or_404(db, token)
|
|
if link.password_hash and not linksmod.check_grant(token, g, link.password_version):
|
|
raise HTTPException(status_code=403, detail="This link needs a password.")
|
|
job, asset = _ready_target(db, link)
|
|
if not asset.poster_path:
|
|
raise HTTPException(status_code=404, detail="No poster.")
|
|
path = storage.safe_abs_path(settings.download_root, asset.poster_path)
|
|
if path is None:
|
|
raise HTTPException(status_code=404, detail="No poster.")
|
|
return FileResponse(path, media_type="image/jpeg")
|