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.

Serve the share page from the extensionless asset path0e4544f
TypeScript197 lines10.1 KB
import { Links } from "./links";import { signToken, verifyToken } from "./lib/token";import { parseRange } from "./lib/range";import { MAX_SINGLE_PUT, MAX_FILE, EXPIRIES } from "./lib/limits";import { PART_SIZE, needsMultipart } from "./lib/parts";import { expiredKeys } from "./lib/cleanup";import { withSecurity, errorResponse, safeFilename, contentDisposition, log } from "./lib/http"; export { Links }; export interface Env {  FILES: R2Bucket;  LINKS: DurableObjectNamespace<Links>;  ASSETS: Fetcher;  LINK_SECRET?: string;} const json = (d: unknown, status = 200) => Response.json(d, { status });const fail = errorResponse;const secret = (env: Env) => env.LINK_SECRET ?? "dev-only-secret";const stub = (env: Env, id: string) => env.LINKS.get(env.LINKS.idFromName(id)); async function createLink(req: Request, env: Env): Promise<Response> {  const b = (await req.json().catch(() => null)) as { key?: string; expiry?: string; limit?: number } | null;  if (!b?.key || !(await env.FILES.head(b.key))) return fail(404, "unknown_object", "Unknown object");  const ttl = EXPIRIES[b.expiry ?? "24h"];  const limit = Number.isInteger(b.limit) && b.limit! > 0 ? b.limit! : 0;  if (!ttl) return fail(400, "bad_expiry", "Expiry must be 1h, 24h or 7d");  const expiresAt = Date.now() + ttl;  const token = await signToken({ key: b.key, expiresAt, limit }, secret(env));  const id = (await verifyToken(token, secret(env))).ok ? token.split(".")[1].slice(0, 22) : "";  log("link.created", { id, key: b.key, expiresAt, limit });  return json({ token, id, url: `${new URL(req.url).origin}/d/${token}`, expiresAt, limit });} async function putObject(req: Request, env: Env, id: string): Promise<Response> {  const len = Number(req.headers.get("content-length") ?? NaN);  if (!Number.isFinite(len)) return fail(411, "length_required", "Content-Length required");  if (len > MAX_SINGLE_PUT) return fail(413, "too_large", "Single PUT exceeds 100 MB; use multipart");  const u = new URL(req.url);  const name = safeFilename(u.searchParams.get("name"));  const type = req.headers.get("content-type") || "application/octet-stream";  const expiresAt = String(Date.now() + EXPIRIES["7d"]);  await env.FILES.put(id, req.body, { httpMetadata: { contentType: type }, customMetadata: { name, expiresAt } });  return json({ key: id, name, size: len });} async function download(req: Request, env: Env, token: string): Promise<Response> {  const v = await verifyToken(token, secret(env));  if (!v.ok) return fail(v.reason === "expired" ? 410 : 403, v.reason, `Link ${v.reason}`);  const head = await env.FILES.head(v.payload.key);  if (!head) return fail(410, "gone", "File is gone");  const r = parseRange(req.headers.get("range"), head.size);  if (r.type === "invalid") return new Response(JSON.stringify({ error: { code: "bad_range", message: "Bad range" } }), { status: 416, headers: { "content-type": "application/json", "content-range": `bytes */${head.size}` } });  if (req.method !== "HEAD" && (r.type === "none" || r.start === 0)) {    const c = await stub(env, v.id).increment(v.payload.limit);    if (!c.ok) return fail(410, c.reason ?? "gone", `Link ${c.reason}`);  }  const obj = await env.FILES.get(v.payload.key, r.type === "range" ? { range: { offset: r.start, length: r.end - r.start + 1 } } : undefined);  if (!obj) return fail(410, "gone", "File is gone");  const name = safeFilename(head.customMetadata?.name);  const inline = new URL(req.url).searchParams.has("inline");  const h = new Headers({    "content-type": head.httpMetadata?.contentType ?? "application/octet-stream",    "content-disposition": contentDisposition(inline ? "inline" : "attachment", name),    etag: head.httpEtag, "accept-ranges": "bytes", "x-content-type-options": "nosniff",  });  if (r.type === "range") {    h.set("content-range", `bytes ${r.start}-${r.end}/${head.size}`);    h.set("content-length", String(r.end - r.start + 1));    return new Response((obj as R2ObjectBody).body, { status: 206, headers: h });  }  h.set("content-length", String(head.size));  return new Response((obj as R2ObjectBody).body, { headers: h });} async function createUpload(req: Request, env: Env): Promise<Response> {  const b = (await req.json().catch(() => null)) as { name?: string; size?: number; type?: string } | null;  const size = Number(b?.size ?? 0);  if (!Number.isFinite(size) || size < 0) return fail(400, "bad_size", "Invalid size");  if (size > MAX_FILE) return fail(413, "too_large", "File exceeds 5 GB");  const id = crypto.randomUUID();  const name = safeFilename(b?.name);  if (!needsMultipart(size)) return json({ id, key: id, multipart: false });  const type = b?.type || "application/octet-stream";  const mp = await env.FILES.createMultipartUpload(id, {    httpMetadata: { contentType: type },    customMetadata: { name, expiresAt: String(Date.now() + EXPIRIES["7d"]) },  });  log("upload.created", { id, size });  return json({ id, key: id, uploadId: mp.uploadId, partSize: PART_SIZE, multipart: true });} async function uploadPart(req: Request, env: Env, id: string, n: number): Promise<Response> {  const uploadId = new URL(req.url).searchParams.get("uploadId");  if (!uploadId) return fail(400, "missing_upload_id", "uploadId query parameter required");  if (!Number.isInteger(n) || n < 1 || n > 10000) return fail(400, "bad_part", "Part number must be 1-10000");  const len = Number(req.headers.get("content-length") ?? NaN);  if (!Number.isFinite(len)) return fail(411, "length_required", "Content-Length required");  if (len > PART_SIZE * 2) return fail(413, "too_large", "Part too large");  try {    const part = await env.FILES.resumeMultipartUpload(id, uploadId).uploadPart(n, req.body as ReadableStream);    return json({ partNumber: part.partNumber, etag: part.etag });  } catch (e) {    log("upload.part_failed", { id, n, error: String(e) });    return fail(404, "upload_not_found", "Upload not found");  }} async function completeUpload(req: Request, env: Env, id: string): Promise<Response> {  const b = (await req.json().catch(() => null)) as { uploadId?: string; parts?: { partNumber: number; etag: string }[] } | null;  const uploadId = b?.uploadId ?? new URL(req.url).searchParams.get("uploadId");  if (!uploadId || !Array.isArray(b?.parts) || !b!.parts.length) return fail(400, "bad_request", "uploadId and parts required");  try {    const parts = b!.parts.map((p) => ({ partNumber: p.partNumber, etag: p.etag }));    const o = await env.FILES.resumeMultipartUpload(id, uploadId).complete(parts);    log("upload.completed", { id, size: o.size });    return json({ key: id, size: o.size, name: o.customMetadata?.name ?? "file" });  } catch (e) {    log("upload.complete_failed", { id, error: String(e) });    return fail(400, "complete_failed", "Could not complete upload");  }} async function abortUpload(req: Request, env: Env, id: string): Promise<Response> {  const uploadId = new URL(req.url).searchParams.get("uploadId");  if (!uploadId) return fail(400, "missing_upload_id", "uploadId query parameter required");  try { await env.FILES.resumeMultipartUpload(id, uploadId).abort(); } catch { /* already gone */ }  return json({ ok: true });} async function linkMeta(env: Env, token: string): Promise<Response> {  const v = await verifyToken(token, secret(env));  if (!v.ok) return fail(v.reason === "expired" ? 410 : 403, v.reason, `Link ${v.reason}`);  const st = await stub(env, v.id).status();  if (st.revoked) return fail(410, "revoked", "Link revoked");  const head = await env.FILES.head(v.payload.key);  if (!head) return fail(410, "gone", "File is gone");  const l = v.payload.limit;  return json({    name: safeFilename(head.customMetadata?.name), size: head.size,    type: head.httpMetadata?.contentType ?? "application/octet-stream",    expiresAt: v.payload.expiresAt, limit: l, downloads: st.downloads,    remaining: l > 0 ? Math.max(0, l - st.downloads) : null, id: v.id,  });} async function route(req: Request, env: Env): Promise<Response> {  const p = new URL(req.url).pathname;  const M = req.method;  let m: RegExpExecArray | null;  if (p === "/health") return json({ ok: true });  if (p === "/api/uploads" && M === "POST") return createUpload(req, env);  if ((m = /^\/api\/uploads\/([\w-]+)\/parts\/(\d+)$/.exec(p)) && M === "PUT") return uploadPart(req, env, m[1], Number(m[2]));  if ((m = /^\/api\/uploads\/([\w-]+)\/complete$/.exec(p)) && M === "POST") return completeUpload(req, env, m[1]);  if ((m = /^\/api\/uploads\/([\w-]+)$/.exec(p))) {    if (M === "PUT") return putObject(req, env, m[1]);    if (M === "DELETE") return abortUpload(req, env, m[1]);  }  if (p === "/api/links" && M === "POST") return createLink(req, env);  if ((m = /^\/api\/links\/([\w.-]+)\/meta$/.exec(p)) && M === "GET") return linkMeta(env, m[1]);  if ((m = /^\/api\/links\/([\w-]+)$/.exec(p))) {    if (M === "GET") return json(await stub(env, m[1]).status());    if (M === "DELETE") { await stub(env, m[1]).revoke(); log("link.revoked", { id: m[1] }); return json({ ok: true }); }  }  if (/^\/api\//.test(p)) return fail(404, "not_found", "Not found");  if ((m = /^\/d\/([\w.-]+)$/.exec(p)) && (M === "GET" || M === "HEAD")) return download(req, env, m[1]);  if (/^\/s\/[\w.-]+$/.test(p)) {    const u = new URL(req.url); u.pathname = "/share";    return env.ASSETS.fetch(new Request(u, req));  }  return env.ASSETS.fetch(req);} export default {  async fetch(req: Request, env: Env): Promise<Response> {    try {      const res = await route(req, env);      log("request", { method: req.method, path: new URL(req.url).pathname, status: res.status });      return withSecurity(res);    } catch (e) {      log("error", { error: String(e) });      return withSecurity(fail(500, "internal", "Internal error"));    }  },  async scheduled(_e: ScheduledController, env: Env): Promise<void> {    let cursor: string | undefined, deleted = 0;    do {      const l = await env.FILES.list({ cursor, include: ["customMetadata"] });      const dead = expiredKeys(l.objects);      if (dead.length) { await env.FILES.delete(dead); deleted += dead.length; }      cursor = l.truncated ? l.cursor : undefined;    } while (cursor);    log("cleanup", { deleted });  },} satisfies ExportedHandler<Env>;