pages-upload.worker.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. export default {
  2. async fetch(request, env) {
  3. const method = request.method;
  4. // Allow only POST (upload) and DELETE
  5. if (method !== "POST" && method !== "DELETE") {
  6. return new Response("Method Not Allowed", { status: 405 });
  7. }
  8. const contentType = request.headers.get("content-type") || "";
  9. let site, path, file;
  10. // Handle DELETE
  11. if (method === "DELETE") {
  12. const url = new URL(request.url);
  13. site = url.searchParams.get("site");
  14. path = url.searchParams.get("path");
  15. if (!site || !path) {
  16. return new Response("Missing site or path", { status: 400 });
  17. }
  18. }
  19. // Handle POST (upload)
  20. if (method === "POST") {
  21. if (!contentType.includes("multipart/form-data")) {
  22. return new Response("Invalid Content-Type", { status: 400 });
  23. }
  24. const form = await request.formData();
  25. site = form.get("site");
  26. path = form.get("path");
  27. file = form.get("file");
  28. if (!site || !path || !file) {
  29. return new Response("Missing site, path, or file", { status: 400 });
  30. }
  31. }
  32. // Validate inputs
  33. if (!isValidSite(site) || !isValidPath(path)) {
  34. return new Response("Invalid site or path", { status: 400 });
  35. }
  36. const key = `site:${site}:${path}`;
  37. // DELETE logic
  38. if (method === "DELETE") {
  39. await env.PAGES_KV.delete(key);
  40. return new Response("Deleted", { status: 200 });
  41. }
  42. // POST logic (upload / redeploy)
  43. const data = await file.arrayBuffer();
  44. await env.PAGES_KV.put(key, data);
  45. return new Response("Uploaded", { status: 200 });
  46. },
  47. };
  48. function isValidSite(site) {
  49. return /^[a-z0-9-]{1,50}$/.test(site);
  50. }
  51. function isValidPath(path) {
  52. return (
  53. typeof path === "string" &&
  54. !path.includes("..") &&
  55. !path.startsWith("/") &&
  56. path.length <= 200
  57. );
  58. }