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):
// 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-onlyfind_mediatool (plus deprecated aliasescreate_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/:idreturns metadata only (primaryUrl: null) for private assets. Your site decides who may download a private object and callssignRead.
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)withexpiresIn <= 60(Cloud caps presigned read URLs at 60 s regardless of whatexpiresAtsays; a download already started finishes, and on403the UI requests a fresh URL). - Never put a presigned URL in an MCP tool result (neither
contentnorstructuredContent): 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 forwardsstructuredContent/content(it strips_meta). - Never authenticate staff on custom
src/routes.tsxpaths: Mantle Access only forwardslayer: "admin"(caller.kind === "host",caller.roles,caller.fields) to manifest-pinned targets under/admin/api/*and/mcp/admin. Customsrc/routes.tsxpaths receive{ kind: "anonymous" }for staff. - Always return
Cache-Control: private, no-storeon any response that carries or redirects to a presigned URL (defaultsrc/service.tsadds it when noCache-Controlheader 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 inmantle describeasadmin:POST /operations/:name) only for Procedures carryingsource: { kind: mcp, surface: admin }. Mantle Access verifies the staff session, enforces the same-origin CSRF check, writes an audit record, and forwardscaller.rolesplus every user field declared in the site's manifests (scope/restrictauth.user(...)orkind: UserField). - Why presigned URLs never reach MCP: the organization MCP does not offer native database access today, so it does not expose a
db: nativeProcedure;db: nativealso handsdbdirectly to the handler context. As defense-in-depth, the handler also requirescaller.kind === "host" && caller.credential === "session"(Admin browser requests arrive with"session", while MCP requests arrive with"oauth").
- Declare any staff user fields (via
kind: UserFieldwhen not already inferred from ascope/restrict), theProcedure, and its admin Trigger inmanifests/site.yaml(storing the committedmediaIdon the owning row, e.g.quote_media_idonrequests):
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 }In
src/service.ts, replace the top-levelimport { handlers } from "./handlers.js"withimport { createHandlers } from "./handlers.js", and buildconst handlers = createHandlers(env);insideserve(request, env, context)beforeoptions(passing thathandlersintooptions,adminBindings({ handlers }), andwebmcpRoutes(..., handlers)). Cloudflare Worker bindings (MEDIA,PRIVATE_MEDIA,MEDIA_PUBLIC_URL_BASE) stay stable on the isolate across requests, whiledbin the handler context is the current request's database handle.Implement the handler in
src/handlers.tsto verify session credential and row/attribute scope, then callsite(db, caller).media(cloudMedia(env)).signRead(...):
// 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 &
viewernotes:
- In the default
src/service.ts,authorizerestricts Procedures (includingread-vendor-quoteand MCP media tools such asfind_media) tomaintainerandowner. If aviewerwith matching Access attributes should also be allowed to runread-vendor-quote, allowtarget.kind === "procedure" && target.name === "read-vendor-quote"explicitly inauthorize.- Conversely,
guardWritesinsrc/service.tsletsviewerread AdminGETroutes (/admin/api/media,/admin/api/media/:idmetadata). Ifviewermust not see private media metadata in Admin's Media Library either, extendguardWritesto guardGETroutes whose path matches/\/media\b/.- If an organization MCP tool also needs to reference a private attachment, declare a separate Store-backed
refProcedure (withoutdb: native) that returns metadata only ({ requestId, mediaId, purpose }) and never callssignRead.
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 |