okayus/okayus-skills/cloudflare-r2-private-image-upload

Claude Code and agent skill by okayus/okayus-skills

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Store user-uploaded photos in a PRIVATE Cloudflare R2 bucket and serve them through the Worker only after session + space-membership authorization, with client-side downscaling (EXIF/GPS stripped) before upload. Use when a Workers + Hono + D1 app needs image upload where photos must stay private to the family/space (no public bucket, no r2.dev URL), when an uploaded image returns 404 after switching between `vite dev` and `wrangler dev`, when `wrangler deploy` fails with `Authentication error` (code 10000) on `/r2/buckets` after adding `r2_buckets`, or when an iPhone HEIC photo won't display on Android. Covers the decision matrix with pricing verified 2026-08 (R2 free tier, Images 5,000 free transformations and the Free-plan 9422 error), the no-extension key scheme `<prefix>/<spaceId>/<parentId>/<id>`, magic-bytes validation, the authorize-before-R2 serve route with conditional GET, delete ordering, thumbnails (client variants vs Images binding cached into R2), e2e, and the no-PITR backup decision.

Install

npx vskill@latest install okayus/okayus-skills/cloudflare-r2-private-image-upload

SKILL.md

The same SKILL.md was published earlier as okayus/okayus-skills/cloudflare-r2-private-image-upload.

Private R2 image upload, served through the Worker

Provenance: extracted from nyalog (ADR-006 "medical images on R2 + Worker proxy", PRs #40–#42 — the attachment routes have run in production since 2026-05). Pricing and limits were re-verified against developers.cloudflare.com on 2026-08-22; nyalog's ADR quoted a "25 GB / 5K writes" R2 free tier that was wrong — the real numbers are in the table below. This skill was written ahead of its second consumer (matatabetai meal photos); that implementation landed 2026-09-01 (matatabetai PR #27, local dev + e2e — prod deploy pending R2 bucket creation) and confirmed several claims below.

Why this shape: a family photo is private data. The moment a photo has a URL that works without a cookie (public bucket, r2.dev, signed URL pasted into chat) you have lost revocation. Keeping the bucket private and routing every byte through the Worker means the same session + space-membership check that guards the JSON API guards the pixels — and <img src="/api/…"> on the same origin sends the session cookie for free, so nothing changes on the client, in the CSP, or in the auth model.

When to use this skill

  • Adding photo/image upload to a Workers + Hono + D1 app where the images belong to a space/family and must not be reachable without a session
  • You're deciding between R2, Cloudflare Images, /cdn-cgi/image transformations, and presigned S3 URLs and want the 2026-08 numbers, not folklore
  • Symptoms:
  • Authentication error [code: 10000] on /accounts/<id>/r2/buckets/<name> during wrangler deploy (or a Workers Builds build) right after adding an r2_buckets binding
  • An image uploaded under vite dev is 404 under wrangler dev (or in e2e) — or vice versa
  • TS2358: The left-hand side of an 'instanceof' expression must be of type 'any'… on file instanceof File in the Worker
  • A photo taken on an iPhone uploads fine but is a broken image on Android/Chrome (HEIC)
  • Portrait phone photos come out sideways after upload
  • Planning thumbnails and wondering whether the Images binding will cost money (Free plan: it won't — it errors with 9422 instead)

Do not use for: public marketing assets (put them in the Assets binding or a public bucket), video or multi-GB objects (multipart upload, different limits), third-party direct-to-bucket uploads at scale (presigned URLs — deliberately rejected here, see the matrix), or apps without the per-space authorization model.

Deliverables (completion criteria)

  • [ ] wrangler.jsonc has r2_buckets: [{ binding, bucket_name }]; the bucket exists (wrangler r2 bucket create); the deploy/build token has Account / Workers R2 Storage / Edit
  • [ ] Bucket is private (no public access, no r2.dev domain, no custom domain); every read goes through GET /api/<parent>/:id/attachments/:attachmentId
  • [ ] Keys follow <prefix>/<spaceId>/<parentId>/<attachmentId> with no extension; content type lives in R2 httpMetadata and the D1 row
  • [ ] Upload route: multipart guard → file narrowing → size cap (413) → magic-bytes allowlist (415) → put → INSERT, with a compensating delete if the INSERT throws
  • [ ] Serve route: session → space membership → parent row → attachment row, then get(key, { onlyIf }); headers Content-Type (DB), Content-Length (obj.size), ETag (obj.httpEtag), Cache-Control: private, max-age=3600, X-Content-Type-Options: nosniff; 304 on precondition failure; 404 when the object is missing
  • [ ] Delete: R2 delete before the DB delete (never the other way round); parent delete collects keys and uses the array form of delete
  • [ ] Client downscales to ≤ 1600 px JPEG (and a 320 px thumb) via canvas before upload — EXIF/GPS gone, ~200–400 KB per photo
  • [ ] HEIC policy decided and written down (default here: reject on the server with a clear message; the client converts what it can decode)
  • [ ] Backup decision recorded (default: accept — the phones keep the originals; see the matrix)
  • [ ] One e2e path: upload → <img> 200 → cross-user 404 → delete → 404
  • [ ] Every UNVERIFIED: bullet below was confirmed or corrected in the consuming project, and this skill was updated

The decision in one table

Numbers verified 2026-08-22 (sources and the full matrix in references/decision-matrix.md).

OptionAuthz possible?Cost at family scaleVerdict
Private R2 + Worker proxyYes — same middleware as the API$0: free tier is 10 GB-month, 1M Class A, 10M Class B ops/month, egress freeChosen
Public bucket / r2.dev / custom domainNo — URL = access$0Rejected: private photos
Cloudflare Images (stored)Signed URLs or binding$5 per 100k stored + $1 per 100k delivered, monthlyRejected: fixed cost for ~100 photos/month
/cdn-cgi/image/... URL transformationsNo — needs a public origin5,000 unique transformations/month freeUnusable behind authz
Images binding (transform in the Worker)Yes — it's just bytes in the Worker5,000 unique/month free; Free plan returns error 9422 beyond that (no charge); Paid $0.50 per 1,000Optional thumbnail path, see below
Presigned S3 URLs (browser → R2 direct)Per-URL, time-boxed$0 but a second token type (R2 API token)Rejected: nothing to gain at family scale

Platform ceilings that matter: request body ≤ 100 MB on Free/Pro (so a 10 MB app cap is a policy, not a limit); Workers Free allows 50 subrequests per invocation.

Wiring: binding, bucket, token, local state

jsonc
// wrangler.jsonc (and wrangler.local.jsonc if you keep a credential-free dev config — keep them in sync)
"r2_buckets": [
{ "binding": "PHOTOS_BUCKET", "bucket_name": "<app>-photos" }
]
  1. Create the bucket on the host (needs wrangler login; the sandbox has no credentials): pnpm exec wrangler r2 bucket create <app>-photos — optionally --location apac as a placement hint. Deploy performs an existence check, so the bucket must exist before the first deploy with the binding.
  2. Token permission: the r2_buckets binding needs Account / Workers R2 Storage / Edit on whatever token deploys — the GH Actions CLOUDFLARE_API_TOKEN (matrix in cloudflare-api-token-permissions) or the Workers Builds build token. The token Workers Builds generates via Create new token already carries Workers R2 Storage (edit) (docs + dashboard notice, 2026-08-23 — see cloudflare-workers-builds-keyless-deploy 0.3.0); only an older or hand-made token may lack it — then extend it in place, don't regenerate. Missing it → Authentication error [code: 10000] on /accounts/<id>/r2/buckets/<name>.
  3. Local dev is fully simulated (Miniflare) — unlike the AI binding, an R2 binding does not force a remote session, so uploads work credential-free in the sandbox. Objects live under .wrangler/state/v3/r2/<bucket_name>/ next to the D1 sqlite; the same --persist-to .wrangler/state rule from cloudflare-workers-e2e-playwright applies, otherwise vite dev and wrangler dev --config dist/… see two different buckets and uploads "disappear".
  4. Types: PHOTOS_BUCKET: R2Bucket in Bindings (global type via wrangler types).

Key scheme and the attachments row

photos/<spaceId>/<parentId>/<attachmentId> full-size (≤ 1600 px JPEG)
photos/<spaceId>/<parentId>/<attachmentId>/w320 thumbnail (client variant or Images-binding cache)
  • No extension. The content type is validated once at upload and stored in R2 httpMetadata.contentType and the D1 row; the serve route never guesses from the key
  • The spaceId prefix means list({ prefix: "photos/<spaceId>/" }) can audit or wipe one family's objects without touching another's
  • D1 row (attachments): id, record_id (FK → the parent that carries space_id, ON DELETE CASCADE), r2_key, thumb_key (nullable), content_type, size_bytes, width, height, original_filename, created_by, created_at. Schema and routes in references/worker-routes.md. For matatabetai: parent = meals, table = meal_photos

Upload route — validate before put, put before INSERT

Order of checks (each one returns before the next runs):

  1. Parent row resolved through memberSpaceIds (404 if it isn't in one of your spaces — existence-hiding, same rule as every other route)
  2. Content-Type header starts with multipart/form-data, else 400 — c.req.formData() throws on anything else and you'd get an opaque 500
  3. const file = form.get("file"); reject null and string (400). Don't write file instanceof File — the Worker tsconfig fails it with TS2358; excluding the other two members of FormDataEntryValue narrows to File
  4. file.size === 0 → 400; file.size > MAX_IMAGE_BYTES (10 MB) → 413 attachment_too_large
  5. Sniff the first 12 bytes (FF D8 FF JPEG, 89 50 4E 47 0D 0A 1A 0A PNG, RIFF….WEBP, ftyp + HEIF brand) and allow only image/jpeg / image/png / image/webp → 415 attachment_type_not_allowed otherwise. file.type is whatever the client said; store the sniffed type, not file.type
  6. PHOTOS_BUCKET.put(key, bytes, { httpMetadata: { contentType } }) — then the optional thumb field the same way
  7. INSERT the row. If the INSERT throws, delete the object(s) you just put and rethrow — an object without a row is an orphan nobody can ever delete through the app
  8. 201 with the row plus its serve URL

Serve route — authorize before touching R2

sessionMiddleware → parent ∈ memberSpaceIds → attachment.record_id === parent.id → PHOTOS_BUCKET.get(key, { onlyIf: request.headers })
  • The chain is N hops of "child row points at the row I already trusted"; only the first hop checks space membership. Every miss is 404, never 403
  • onlyIf: c.req.raw.headers lets R2 evaluate the browser's If-None-Match / If-Modified-Since; when the precondition fails R2 returns an R2Object without body → respond 304 with ETag + Cache-Control. (Documented R2 API; not yet exercised in the source projects — see UNVERIFIED)
  • Headers: Content-Type from the DB row, Content-Length: obj.size (not the DB value — they drift after a re-upload or a cached transform), ETag: obj.httpEtag, Cache-Control: private, max-age=3600, Content-Disposition: inline, X-Content-Type-Options: nosniff
  • null from get with a row present = DB/R2 inconsistency → 404 and console.error (it should never happen with the delete ordering below)
  • Never public and never the Cache API: the edge cache is keyed by URL, not by cookie — one cached public response is every family's photo for an hour

Delete — R2 first (best-effort), then D1

  • Single attachment: delete([r2Key, thumbKey]) → DB delete. If R2 throws, the row survives and the user retries; the reverse order turns a transient R2 failure into a permanent 404 row
  • Parent delete: SELECT r2_key, thumb_key WHERE record_id = ? → one delete(keys[]) call (array form, up to 1,000 keys — one call instead of N, which also matters under the Free plan's 50-subrequest cap) → delete the parent (rows cascade)
  • Orphans are acceptable at family scale; an optional weekly sweep (list({ prefix: "photos/" }) minus the rows, skipping objects uploaded in the last hour) is sketched in references/e2e-and-ops.md — cron plumbing per cloudflare-cron-to-discord

Client — downscale, strip EXIF, then FormData

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/okayus/okayus-skills/cloudflare-r2-private-image-upload/badge)](https://verified-skill.com/skills/okayus/okayus-skills/cloudflare-r2-private-image-upload)

Something wrong with this skill or its page? Tell us.