feat(files): preview attachments via short-lived signed URLs
Downloads require an Authorization header, which <iframe>/<img> cannot
send. The previous blob: workaround broke under download managers (IDM
hooks blob URLs, fails to resolve them, and leaves a 0-byte file) and in
Chrome's mobile emulation, which has no inline PDF plugin.
Backend:
- preview_token.py: HMAC-signed token bound to one (quote, kind, file)
with a 5-minute TTL, keyed off an existing secret
- GET /quotes/{id}/preview-url/{kind}/{attachment} mints the URL
- the two file GET routes accept a Bearer session OR the signed ?t= token
(they leave the global auth dep, so the other six file routes now carry
it explicitly — nothing is open by omission)
Frontend:
- api.files.previewUrl() replaces the blob helper
- shared FilePreviewModal + useFilePreview; FileList and the dashboard
quote card both use it
- PDFs render with the browser's native viewer on desktop and pdf.js on
canvas where no inline viewer exists (mobile); pdf.js is fed the bytes
in memory so no PDF URL is exposed for a download manager to intercept
- removed the per-attachment download buttons on the dashboard card and
the modal header
Ops:
- nginx: explicit MIME types (.mjs as text/javascript) — a module worker
served as octet-stream is refused and crashed the page
- frontend service bypasses the nginx entrypoint, whose apk manifest call
hangs when the package mirror is unreachable (502s)
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
"""Ephemeral, URL-safe file-preview tokens.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
File downloads require an ``Authorization: Bearer`` header, but a browser
|
||||
cannot attach headers to the requests made by ``<iframe src>`` / ``<img
|
||||
src>`` — which is what the preview modal uses. The previous workaround
|
||||
fetched the bytes with ``fetch`` and rendered a local ``blob:`` URL, but
|
||||
download managers (IDM et al.) hook ``blob:`` URLs, fail to resolve them
|
||||
outside the originating document, and hand the browser a 0-byte file under
|
||||
a bare UUID name — so the preview broke and a junk download appeared.
|
||||
|
||||
Instead we mint a short-lived HMAC token scoped to a single attachment and
|
||||
put it in the query string, giving the iframe a *real* URL that also
|
||||
carries its own authorization. The token is not a session credential: it
|
||||
authorises exactly one (quote_id, kind, attachment_id) triple and expires
|
||||
in minutes.
|
||||
|
||||
Format: ``<expiry-unix>.<hex-hmac>`` over ``"{quote_id}:{kind}:{attachment_id}:{expiry}"``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from app.config import settings
|
||||
|
||||
# پیشنمایش کوتاهعمر است — فقط برای باز شدن مودال، نه اشتراکگذاری لینک
|
||||
DEFAULT_TTL_SECONDS = 300
|
||||
|
||||
|
||||
def _secret() -> bytes:
|
||||
"""Key for the HMAC. Reuses existing secrets so no new config is needed."""
|
||||
base = (
|
||||
settings.CASDOOR_CLIENT_SECRET
|
||||
or settings.MINIO_SECRET_KEY
|
||||
or "procurement-preview-fallback"
|
||||
)
|
||||
return base.encode("utf-8")
|
||||
|
||||
|
||||
def _sign(quote_id: uuid.UUID, kind: str, attachment_id: uuid.UUID, expiry: int) -> str:
|
||||
msg = f"{quote_id}:{kind}:{attachment_id}:{expiry}".encode("utf-8")
|
||||
return hmac.new(_secret(), msg, hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def make_preview_token(
|
||||
quote_id: uuid.UUID, kind: str, attachment_id: uuid.UUID, ttl: int = DEFAULT_TTL_SECONDS
|
||||
) -> str:
|
||||
expiry = int(time.time()) + ttl
|
||||
return f"{expiry}.{_sign(quote_id, kind, attachment_id, expiry)}"
|
||||
|
||||
|
||||
def verify_preview_token(
|
||||
token: str, quote_id: uuid.UUID, kind: str, attachment_id: uuid.UUID
|
||||
) -> bool:
|
||||
"""True when the token is well-formed, unexpired and matches this file."""
|
||||
if not token or "." not in token:
|
||||
return False
|
||||
expiry_raw, signature = token.split(".", 1)
|
||||
try:
|
||||
expiry = int(expiry_raw)
|
||||
except ValueError:
|
||||
return False
|
||||
if expiry < int(time.time()):
|
||||
return False
|
||||
expected = _sign(quote_id, kind, attachment_id, expiry)
|
||||
return hmac.compare_digest(expected, signature)
|
||||
Reference in New Issue
Block a user