# Mantle Cloud media (public and private R2)

Every Mantle Cloud site has **two Cloudflare R2 buckets** provisioned and wired automatically through `src/media.ts` (`cloudMedia(env)` → `{ public, private }`):

| Bucket | Worker binding | Delivery | Use for |
| --- | --- | --- | --- |
| **Public R2** | `MEDIA` + `MEDIA_PUBLIC_URL_BASE` | Organization media host CDN URL (`https://<media-host>/<tenant>/...`). Only JPEG, PNG, WebP, GIF and AVIF render inline; all other types download as `attachment`. | Public cover images, product photos, brochures, assets referenced on public visitor pages. |
| **Private R2** | `PRIVATE_MEDIA` | **No public URL.** Reads go through short-lived presigned R2 GET URLs (`<= 60 s`) issued by your site after checking **Mantle Access** identity and authorization. | Invoices, quotations, internal prep sheets, customer documents, team- or department-scoped files. |

You do **not** create an R2 bucket, configure Wrangler `r2_buckets`, or add S3 credentials. Both `MEDIA` and `PRIVATE_MEDIA` are host `TenantMedia` bindings scoped to this site (max 25 MiB per object; every upload stages in the private bucket before commit; HTML, SVG, XML and JavaScript uploads are refused by Core).

## 1. Declare public and private purposes in `src/site-config.ts`

Purposes live in `src/site-config.ts` and require **no database migration** when added or narrowed. Omit `visibility` for public R2 (`MEDIA`); set `visibility: 'private'` for private R2 (`PRIVATE_MEDIA`).

Each entry in `required` is a **slot** of comma-separated allowed MIME types (e.g. `'image/jpeg,image/png,image/webp'` means one file in any of those image formats), and `maxBytes` must include a limit key for every allowed MIME type (from Core 0.2.2-alpha.5, any non-executable MIME type, `type/*`, or `*/*` is supported):

```ts
// src/site-config.ts
import type { SiteDefaults } from "@aotter/mantle/site";

const imageBytes = { "image/jpeg": 5_000_000, "image/png": 5_000_000, "image/webp": 5_000_000 };
const docBytes = { "application/pdf": 10_000_000, "text/plain": 2_000_000 };

export const siteDefaults: SiteDefaults = {
  media: {
    purposes: [
      // Public R2 (MEDIA): gets a stable publicUrl under MEDIA_PUBLIC_URL_BASE.
      { name: "cover", required: ["image/jpeg,image/png,image/webp"], maxBytes: imageBytes },
      // Private R2 (PRIVATE_MEDIA): no publicUrl; reads require MediaLibrary.signRead(mediaId, expiresIn).
      { name: "quote", visibility: "private", required: ["application/pdf,text/plain"], maxBytes: docBytes },
    ],
  },
};
```

Once at least one purpose is declared, `src/service.ts` wires `cloudMedia(env)` into Admin (`/admin`) and MCP automatically:
- **Staff upload & manage** both public and private purposes in Admin's Media Library (upload, list, view/edit metadata, delete). Through the organization MCP gateway, sites expose `upload_media` (the one built-in opaque media write) and the read-only `find_media` tool (plus deprecated aliases `create_media_upload`, `commit_media_upload`, `list_media_assets`, `get_media_asset`, `get_media_upload_policy`); metadata edits and deletes stay in Admin UI.
- **Members**: built-in Admin and MCP media endpoints are staff-only (`site(db, caller).media()` accepts only verified admin callers). Member uploads and member-scoped private downloads are not available yet.
- **Admin Media Library does not auto-mint private read URLs**: `GET /admin/api/media/:id` returns metadata only (`primaryUrl: null`) for private assets. Your site decides who may download a private object and calls `signRead`.

## 2. Serving private R2 with Mantle Access

Mantle Access runs in **gateway mode**: it authenticates people and forwards `ctx.props.mantle`, while **your site enforces who can read which private object**. Never serve a private asset without checking Access identity and row/attribute ownership first.

**Hard rules for `signRead`:**
- Call `MediaLibrary.signRead(mediaId, 60)` — pass positional `(mediaId, expiresIn)` with `expiresIn <= 60` (Cloud caps presigned read URLs at 60 s regardless of what `expiresAt` says; a download already started finishes, and on `403` the UI requests a fresh URL).
- **Never put a presigned URL in an MCP tool result** (neither `content` nor `structuredContent`): presigned URLs are short-lived credentials meant for a signed-in person's browser, not an LLM prompt. In addition, the organization MCP gateway only forwards `structuredContent`/`content` (it strips `_meta`).
- **Never authenticate staff on custom `src/routes.tsx` paths**: Mantle Access only forwards `layer: "admin"` (`caller.kind === "host"`, `caller.roles`, `caller.fields`) to manifest-pinned targets under `/admin/api/*` and `/mcp/admin`. Custom `src/routes.tsx` paths receive `{ kind: "anonymous" }` for staff.
- Always return `Cache-Control: private, no-store` on any response that carries or redirects to a presigned URL (default `src/service.ts` adds it when no `Cache-Control` header is set).

### Staff private download — Admin `POST /admin/api/operations/<name>` (`db: native` `ref` Procedure)

Use a manifest-declared `Procedure` with `requires: { auth: { all: [ctx.admin] } }`, `db: native`, `handler: { ref }`, and an admin Trigger (`source: { kind: mcp, surface: admin }`) whenever staff roles (`maintainer`, `owner`, `viewer`), Access teams/attributes (`caller.fields`), or row-level rules govern private R2 reads:

- **Why the admin Trigger is required**: Core mounts `POST /admin/api/operations/<name>` (pinned in `mantle describe` as `admin:POST /operations/:name`) only for Procedures carrying `source: { kind: mcp, surface: admin }`. Mantle Access verifies the staff session, enforces the same-origin CSRF check, writes an audit record, and forwards `caller.roles` plus every user field declared in the site's manifests (`scope`/`restrict` `auth.user(...)` or `kind: UserField`).
- **Why presigned URLs never reach MCP**: the organization MCP does not offer native database access today, so it does not expose a `db: native` Procedure; `db: native` also hands `db` directly to the handler context. As defense-in-depth, the handler also requires `caller.kind === "host" && caller.credential === "session"` (Admin browser requests arrive with `"session"`, while MCP requests arrive with `"oauth"`).

1. Declare any staff user fields (via `kind: UserField` when not already inferred from a `scope`/`restrict`), the `Procedure`, and its admin Trigger in `manifests/site.yaml` (storing the committed `mediaId` on the owning row, e.g. `quote_media_id` on `requests`):

```yaml
apiVersion: cms.mantle.aotter.net/v2
kind: UserField
metadata: { name: departments }
spec: { type: string, multiple: true, description: Departments whose vendor quotes this staff member may download }
---
apiVersion: cms.mantle.aotter.net/v2
kind: UserField
metadata: { name: allDepartments }
spec: { type: boolean, description: True when the staff member may read quotes for every department }
---
apiVersion: cms.mantle.aotter.net/v2
kind: Procedure
metadata: { name: read-vendor-quote }
spec:
  title: Read vendor quote PDF
  requires: { auth: { all: [ctx.admin] } }
  db: native
  input:
    type: object
    additionalProperties: false
    required: [requestId]
    properties: { requestId: { type: string } }
  output:
    type: object
    additionalProperties: false
    required: [requestId, mediaId, url, expiresAt]
    properties:
      requestId: { type: string }
      mediaId: { type: string }
      url: { type: string }
      expiresAt: { type: integer }
  handler: { ref: read-vendor-quote }
---
apiVersion: cms.mantle.aotter.net/v2
kind: Trigger
metadata: { name: read-vendor-quote-admin }
spec:
  source: { kind: mcp, surface: admin }
  target: { procedure: read-vendor-quote }
```

2. In `src/service.ts`, replace the top-level `import { handlers } from "./handlers.js"` with `import { createHandlers } from "./handlers.js"`, and build `const handlers = createHandlers(env);` inside `serve(request, env, context)` before `options` (passing that `handlers` into `options`, `adminBindings({ handlers })`, and `webmcpRoutes(..., handlers)`). Cloudflare Worker bindings (`MEDIA`, `PRIVATE_MEDIA`, `MEDIA_PUBLIC_URL_BASE`) stay stable on the isolate across requests, while `db` in the handler context is the current request's database handle.

3. Implement the handler in `src/handlers.ts` to verify session credential and row/attribute scope, then call `site(db, caller).media(cloudMedia(env)).signRead(...)`:

```ts
// src/handlers.ts
import { ContractError } from "@aotter/mantle/contracts";
import type { Handlers } from "../generated/generated.js";
import { site } from "../generated/site.js";
import { cloudMedia, type MediaEnv } from "./media.js";

export function createHandlers(env: Env): Handlers {
  return {
    "read-vendor-quote": async ({ db, store, caller }, { requestId }) => {
      // 1. Admin browser session only (never hand presigned URLs to OAuth/MCP callers).
      if (caller.kind !== "host" || caller.credential !== "session") {
        throw new ContractError("AUTH_DENIED", "Admin browser session required.", "procedures/read-vendor-quote", { status: 403 });
      }
      const row = await store.collection("requests").findById(requestId);
      if (!row) {
        throw new ContractError("NOT_FOUND", "Request not found.", "procedures/read-vendor-quote");
      }
      // 2. Check role / Access attributes before revealing whether an attachment exists.
      //    Only fields declared via scope/restrict or kind: UserField reach caller.fields.
      const roles = caller.roles ?? [];
      const isOwner = roles.includes("owner");
      const fields = caller.fields ?? {};
      // Boolean fields arrive as true | false; list fields arrive as string[] or { all: true } when granted "*".
      const deptField = fields.departments;
      const allDepts = fields.allDepartments === true
        || (typeof deptField === "object" && deptField !== null && !Array.isArray(deptField)
          && (deptField as { all?: unknown }).all === true);
      const allowedDepts = Array.isArray(deptField) ? deptField : [];
      if (!isOwner && !allDepts && !allowedDepts.includes(row.department)) {
        throw new ContractError("AUTH_DENIED", "Department is not authorized for this quote.", "procedures/read-vendor-quote", { status: 403 });
      }
      if (!row.quote_media_id) {
        throw new ContractError("NOT_FOUND", "Quote attachment not found.", "procedures/read-vendor-quote");
      }
      // 3. Mint a <= 60 s presigned R2 GET URL for the authenticated staff browser response.
      const mediaEnv = env as Partial<MediaEnv>;
      if (!mediaEnv.MEDIA || !mediaEnv.PRIVATE_MEDIA || !mediaEnv.MEDIA_PUBLIC_URL_BASE) {
        throw new ContractError("MEDIA_NOT_CONFIGURED", "Private media binding is unavailable.", "procedures/read-vendor-quote", { status: 503 });
      }
      const signed = await site(db, caller).media(cloudMedia(mediaEnv as MediaEnv)).signRead(row.quote_media_id, 60);
      const url = (signed.variants.find(v => v.role === "primary") ?? signed.variants[0])?.url;
      if (!url) throw new ContractError("MEDIA_ASSET_NOT_FOUND", "Media object missing.", "procedures/read-vendor-quote", { status: 404 });
      return { requestId: row.id, mediaId: row.quote_media_id, url, expiresAt: signed.expiresAt ?? Date.now() + 60_000 };
    },
  };
}
```

> **Role & `viewer` notes:**
> - In the default `src/service.ts`, `authorize` restricts Procedures (including `read-vendor-quote` and MCP media tools such as `find_media`) to `maintainer` and `owner`. If a `viewer` with matching Access attributes should also be allowed to run `read-vendor-quote`, allow `target.kind === "procedure" && target.name === "read-vendor-quote"` explicitly in `authorize`.
> - Conversely, `guardWrites` in `src/service.ts` lets `viewer` read Admin `GET` routes (`/admin/api/media`, `/admin/api/media/:id` metadata). If `viewer` must not see private media metadata in Admin's Media Library either, extend `guardWrites` to guard `GET` routes whose path matches `/\/media\b/`.
> - If an organization MCP tool also needs to reference a private attachment, declare a separate Store-backed `ref` Procedure (without `db: native`) that returns metadata only (`{ requestId, mediaId, purpose }`) and never calls `signRead`.

## 3. Choosing public vs private across Cloud presets

| Preset | Public R2 (`MEDIA`) | Private R2 (`PRIVATE_MEDIA`, `visibility: "private"`) |
| --- | --- | --- |
| `recipes` (runnable example) | `cover`: public recipe cover photos on `/recipes/...` | None by default; add a private purpose and the staff download above for staff-only prep sheets |
| `procurement` | Public catalog item thumbnails (if any) | Vendor quotes, invoices, approval memos gated by department/Finance Access rules (staff download above) |
| `intake` | Public FAQ screenshots | Requester-submitted diagnostic files gated by triage staff |
| `transaction` | Product photos on storefront | Receipts, shipping labels, tax invoices gated by fulfillment staff |
| `reservation` | Venue / room photos | Signed waivers or booking documents gated by host staff |
