# Images, PDFs & upload safety

> Separate public catalog media from private user PDFs, enforce server-side MIME and size checks, and serve fast images without leaking sensitive files.

- Canonical: https://exaspark.ai/docs/media-uploads-and-limits/

## Threat model: why user uploads need strict boundaries

Accepting files from real users introduces security and performance risks that plain form inputs never trigger. Once a live app accepts profile photos, product shots, tax invoices, or client PDFs, five predictable failure modes emerge if storage boundaries stay loose:

- **Leaked private documents.** Saving invoices or resumes in a public path under a random URL means anyone who forwards, bookmarks, or logs that URL can download the file indefinitely without signing in.
- **Executable file injection.** Accepting untrusted `.svg` or `.html` files and rendering them inline on your app domain lets attackers execute arbitrary JavaScript inside a logged-in admin's browser.
- **Filename collisions and overwrites.** Storing uploads under raw client filenames (`receipt.pdf`) causes one user's upload to overwrite another customer's file or break URLs with unsafe characters.
- **Unbounded mobile camera uploads.** Modern phones shoot 15–40 MB photos; rendering uncompressed originals inside product grids stalls mobile page loads and inflates storage consumption.
- **Orphaned storage files.** Deleting a product or replacing an avatar in your database without deleting the underlying binary object leaves unused files accumulating silently.

ExaSpark keeps **Preview** and **Live** storage buckets strictly isolated, so testing upload guards and cleanup flows in Preview never risks exposing or altering live customer files.

## Public catalog media vs private user documents

Every upload type in your app belongs in one of two explicit visibility tiers. Never mix public catalog images and private customer PDFs inside the same access pattern or folder prefix.

| Architecture aspect | Public media (`public/...`) | Private documents (`private/...`) |
| --- | --- | --- |
| **Typical files** | Product photos, hero banners, blog covers, venue galleries | Tax invoices, payment receipts, signed waivers, resumes, client briefs |
| **Read authorization** | Open to all visitors; write access restricted to Admins | Strictly authenticated — server checks `owner_id === session.user.id` or `role === 'admin'` |
| **Delivery mechanism** | Direct cacheable CDN URLs for fast page loads | Authenticated backend stream or short-lived signed download URL (60–300 seconds) |
| **Cache headers** | Long-lived public cache (`max-age=31536000, immutable`) | `Cache-Control: private, no-store` so shared browsers never cache sensitive PDFs |
| **Database metadata** | `storage_key`, `alt_text`, `width`, `height`, `sort_order` | `storage_key`, `owner_id`, `original_filename`, `mime_type`, `size_bytes` |

### Why short-lived signed URLs protect private PDFs

When a logged-in customer clicks **Download invoice PDF**, your app backend first authenticates the session cookie and checks ownership against your Cloud database (`invoice.user_id === session.user.id`).

Only after that authorization check passes does your server either stream the file directly with safe download headers or mint a temporary signed URL valid for **60 to 300 seconds**. Even if the customer pastes that link into an email thread later, the signature expires automatically.

## Enforcing MIME type, magic-byte, and file size rules

Browser `<input type="file" accept=".pdf,image/*">` attributes improve usability, but they provide zero security. Any visitor can bypass client-side filters using browser developer tools or direct HTTP requests.

### Server-side MIME allowlists and magic bytes

Always re-validate uploaded files **on the server** before saving them to storage. Never trust the filename extension or browser `Content-Type` header alone.

Inspect the file's leading **magic bytes** (`%PDF-` for PDFs, `FF D8 FF` for JPEG, `89 50 4E 47` for PNG, `RIFF....WEBP` for WebP) so a renamed `.html` payload cannot pass as a `.jpg`.

| Upload type | Server MIME allowlist | Max size | Safe delivery rule |
| --- | --- | --- | --- |
| **Avatar** | `image/jpeg`, `image/png`, `image/webp` | **2–5 MB** | Resized WebP/JPEG; strip EXIF GPS data |
| **Product photo** | `image/jpeg`, `image/png`, `image/webp` | **5–10 MB** | Public immutable URL; set aspect ratio and `alt_text` |
| **PDF document** | `application/pdf` | **10–20 MB** | Private signed download with `Content-Disposition: attachment` |
| **CSV import** | `text/csv` | **5–10 MB** | Parse server-side; reject formula-injection cells |
| **SVG / HTML** | **Blocked unconditionally** | `0` | Reject `image/svg+xml`, `text/html`, `.exe`, and `.js` |

### Safe response headers for private downloads

When streaming user-uploaded documents through your backend, send defensive headers so browsers download files safely instead of executing embedded scripts:

```http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename="invoice-ord-1042.pdf"
X-Content-Type-Options: nosniff
Cache-Control: private, no-store, max-age=0
```

## Keeping image-heavy pages fast on mobile

- **Prefer WebP or compressed JPEG.** Converting phone uploads to WebP cuts payload size by 50–75% with zero visible quality loss on product cards.
- **Lock image dimensions.** Set explicit `width`/`height` or CSS `aspect-ratio` on every card so layouts never jump while thumbnails load.
- **Eager-load heroes, lazy-load grids.** Load above-the-fold hero shots with `fetchpriority="high"` and apply `loading="lazy"` to below-the-fold cards.
- **Strip EXIF metadata.** Removing smartphone EXIF headers drops embedded home GPS coordinates automatically.

> **Note:** **Need crisp catalog shots fast?** On **Starter** and **Pro**, generate studio product photos and transparent cutouts inside Creative Studio before uploading them. See [Creative Studio media](https://exaspark.ai/docs/media/).

## Implementing a safe upload and signed-download flow

1. **Validate in UI, then re-verify on the server** — Give instant browser feedback, then enforce MIME allowlists, magic bytes, and byte caps server-side.
2. **Generate collision-free scoped keys** — Store files under paths like `public/products/<product_id>/<uuid>.webp` or `private/invoices/<user_id>/<uuid>.pdf`, never raw filenames.
3. **Record ownership metadata in Cloud** — Save `storage_key`, `owner_id`, `original_filename`, `mime_type`, `size_bytes`, and `visibility` in a relational table.
4. **Gate private downloads server-side** — Verify session and ownership before minting a 60–300 second signed URL or streaming with `Content-Disposition: attachment`.
5. **Delete replaced objects cleanly** — Remove old storage binaries inside the same authorized server handler whenever an item is replaced or deleted.

```json
{
  "id": "file_01JA2K9P4T",
  "visibility": "private",
  "owner_id": "usr_418",
  "record_type": "client_contract",
  "storage_key": "private/contracts/usr_418/9c2e4b11.pdf",
  "original_filename": "studio-retainer-signed.pdf",
  "mime_type": "application/pdf",
  "size_bytes": 418920
}
```

> **Example prompt (App):** Build two upload flows using managed storage and a `file_attachments` table: (1) Admin product gallery accepting up to 6 public JPEG/PNG/WebP images per product (max 5 MB each, saved under `public/products/<product_id>/<uuid>.<ext>`, rendered with `aspect-ratio`, `alt_text`, and `loading="lazy"`); (2) Client uploads accepting only verified `application/pdf` files up to 15 MB stored privately under `private/documents/<user_id>/<uuid>.pdf`. Reject SVGs and mismatched magic bytes server-side, serve private PDFs through an ownership-checked signed download route with `Content-Disposition: attachment` and `X-Content-Type-Options: nosniff`, and delete storage objects on removal.

## Troubleshooting upload and media security issues

| Symptom | Most likely root cause | Reliable fix |
| --- | --- | --- |
| **Private PDF opens in incognito** | Saved to public path or skipped session check | Move under `private/...` and verify `owner_id` or `admin` before signing |
| **Phone upload hits `413` error** | Uncompressed 20 MB photo exceeded byte cap | Resize client-side before upload and show max size clearly |
| **Broken product photos on Live** | Hard-coded Preview media URLs | Re-upload catalog images in Live admin or bundle static brand assets |
| **Slow mobile catalog LCP** | Raw 4000px PNGs rendered in small cards | Convert to WebP, size appropriately, and lazy-load off-screen cards |
| **SVG flags security review** | Untrusted SVG uploads allowed inline | Restrict user images strictly to `image/jpeg`, `image/png`, and `image/webp` |
| **Storage grows after deletes** | Delete route removed DB row only | Delete the storage object inside the same server delete handler |

## Next steps

- [File storage & uploads](https://exaspark.ai/docs/file-storage/) — Review managed object storage architecture and attachment table patterns.
- [Row-level data privacy](https://exaspark.ai/docs/row-level-data-privacy/) — Enforce strict server-side ownership checks across rows and downloads.
- [Page speed & Core Vitals](https://exaspark.ai/docs/page-speed-and-core-vitals/) — Optimize LCP, CLS, and mobile asset loading across every screen.

## From the blog

- [App security basics](https://exaspark.ai/blog/app-security-checklist/) — Audit private uploads, access rules, and sessions before launch.
- [Make a website load faster](https://exaspark.ai/blog/how-to-make-a-website-load-faster/) — Practical image sizing, WebP compression, and caching wins.
- [User roles and permissions](https://exaspark.ai/blog/user-roles-and-permissions/) — Keep private client documents restricted to owners and staff.
