Skip to content

gitflarePublicPartly agent-ready50

cf-r2-drop

Drag-and-drop file sharing on Cloudflare R2: multipart uploads, expiring share links, previews, download counts, lifecycle expiry.

main
Serve the share page from the extensionless asset path0e4544f
Markdown28 lines2.1 KB

Architecture

Signed tokens

A share token is base64url(objectKey.expiresAt.limit) plus an HMAC-SHA256 signature made with LINK_SECRET through Web Crypto. Every request verifies the signature, so a tampered token gets 403. A token past expiresAt gets 410. The signature comparison is constant-time. The code is in src/lib/token.ts.

The link id used by the Durable Object is derived from the token. The token never stores counts, because counts change after signing.

Multipart flow

  1. POST /api/uploads declares name, size and type. Small files get an id. Large files (10 MB or more) start createMultipartUpload and return the uploadId, the key and the 8 MiB part size.
  2. The browser sends PUT /api/uploads/:id/parts/:n for each part, 4 in parallel. Each failed part is retried 3 times with backoff. Pause stops scheduling new parts. Resume continues with the missing ones.
  3. POST /api/uploads/:id/complete sends the part etags, and R2 assembles the object.
  4. DELETE /api/uploads/:id aborts the upload (cancel).

Objects are written with customMetadata.expiresAt. Part planning is in src/lib/parts.ts, and size limits are in src/lib/limits.ts.

Range downloads

/d/<token> parses Range (src/lib/range.ts) and passes it to R2. It answers 206 with Content-Range, or 416 if the range is unsatisfiable. It sends ETag and Accept-Ranges: bytes, and streams object.body. ?inline=1 uses Content-Disposition: inline for previews. Otherwise it uses attachment.

Links Durable Object

One SQLite-backed Links object per link id. increment() runs atomically inside the object. It refuses when the link is revoked or the limit is reached, before any bytes stream. Metadata reads do not count as downloads.

Lifecycle

  • Expiry is checked on every request from the signed token.
  • A daily cron (0 3 * * *) lists objects and deletes those whose customMetadata.expiresAt has passed.
  • The R2 lifecycle rule (scripts/lifecycle.json) deletes after 7 days and aborts incomplete multipart uploads after 1 day, as a backstop.

See docs/API.md for the HTTP contract.