Handle file uploads with object storage
A private file drop: a web page with an upload form, files stored in an object storage bucket, and a download link for each one. Uploading needs a password you set; downloading needs only the link. One JavaScript file, one bucket, deployed to a live URL.
It takes about fifteen minutes. If you haven't installed the CLI yet, do steps 1 and 2 of the quick start first (ribo install and ribo login).
How it fits together
The browser posts the form to your Cell. The Cell checks the password and the size, then writes the file to a g7 bucket through a binding, with no S3 keys in your code. Downloads go back through the Cell too, so the bucket stays private and the Cell decides who gets what.
1. Create the bucket and the password
mkdir file-drop && cd file-drop
ribo bucket create drop-filesBucket names are 3 to 49 characters: lowercase letters, digits and hyphens. Buckets are private unless you pass --public, and this one should stay private.
Now the upload password. Pick one, or generate one, and store it in the Cell's vault:
openssl rand -base64 18
ribo vault set file-drop UPLOAD_TOKENribo vault set prompts for the value with hidden input. Do this before the first deploy: a vault value that's missing at deploy time reaches the Cell as a placeholder string instead of your password, and the code below refuses uploads in that case.
2. Write the config
ribo.toml
[cell]
name = "file-drop"
js = "./cell.js"
[[bindings]]
type = "g7"
binding = "FILES"
bucket = "drop-files"
[[bindings]]
type = "vault"
binding = "UPLOAD_TOKEN"3. Write the Cell
cell.js
// The binding accepts up to 100 MiB per put. This drop takes less.
const MAX_BYTES = 25 * 1024 * 1024;
// A vault value that was never set arrives as this placeholder.
const VAULT_UNSET = "***REMOVED***";
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (request.method === "GET" && url.pathname === "/") {
return html(formPage());
}
if (request.method === "POST" && url.pathname === "/upload") {
return upload(request, env, url);
}
if (request.method === "GET" && url.pathname.startsWith("/f/")) {
return download(env, url.pathname.slice(3));
}
return new Response("Not found", { status: 404 });
},
};
async function upload(request, env, url) {
let form;
try {
form = await request.formData();
} catch {
return html(formPage("That upload didn't come through as a form."), 400);
}
if (!(await tokenMatches(form.get("token"), env.UPLOAD_TOKEN))) {
return html(formPage("Wrong password."), 401);
}
const file = form.get("file");
if (!(file instanceof File) || file.size === 0) {
return html(formPage("Choose a file first."), 400);
}
if (file.size > MAX_BYTES) {
return html(formPage("That file is over 25 MB."), 413);
}
// A random folder per upload keeps two files with the same name apart and
// makes the link unguessable.
const id = crypto.randomUUID();
const key = `${id}/${safeName(file.name)}`;
await env.FILES.put(key, file.stream(), {
contentType: file.type || "application/octet-stream",
});
const link = `${url.origin}/f/${key}`;
return html(formPage(`Uploaded. Link: <a href="${esc(link)}">${esc(link)}</a>`), 201);
}
async function download(env, key) {
const obj = await env.FILES.get(key);
if (!obj) return new Response("Not found", { status: 404 });
const name = key.split("/").pop();
const headers = new Headers({
"content-type": obj.headers.get("content-type") ?? "application/octet-stream",
// Download rather than display, so an uploaded HTML file can't run as a
// page on this Cell's domain.
"content-disposition": `attachment; filename="${name}"`,
"x-content-type-options": "nosniff",
});
const length = obj.headers.get("content-length");
if (length) headers.set("content-length", length);
return new Response(obj.body, { headers });
}
async function tokenMatches(given, secret) {
if (typeof secret !== "string" || secret === "" || secret === VAULT_UNSET) return false;
if (typeof given !== "string" || given === "") return false;
// Compare SHA-256 digests byte by byte, so the time taken doesn't depend on
// how much of the password was right.
const enc = new TextEncoder();
const [a, b] = await Promise.all(
[given, secret].map((v) => crypto.subtle.digest("SHA-256", enc.encode(v)))
);
const x = new Uint8Array(a);
const y = new Uint8Array(b);
let diff = 0;
for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i];
return diff === 0;
}
// Keys keep to letters, digits, dot, dash and underscore; anything else becomes "_".
function safeName(name) {
const cleaned = String(name).replace(/[^A-Za-z0-9._-]/g, "_").replace(/^\.+/, "");
return cleaned.slice(-100) || "file";
}
function formPage(message = "") {
return `<!doctype html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>File drop</title>
<style>
body { font: 16px/1.5 system-ui, sans-serif; margin: 2rem; max-width: 36rem; }
label { display: block; margin: 1rem 0 0.25rem; }
button { margin-top: 1rem; }
</style>
<h1>File drop</h1>
${message ? `<p>${message}</p>` : ""}
<form method="post" action="/upload" enctype="multipart/form-data">
<label for="file">File (up to 25 MB)</label>
<input id="file" name="file" type="file" required>
<label for="token">Password</label>
<input id="token" name="token" type="password" required autocomplete="current-password">
<button type="submit">Upload</button>
</form>`;
}
function html(body, status = 200) {
return new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8" } });
}
function esc(s) {
return String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
}What the important lines do:
env.FILES.put(key, file.stream(), { contentType })writes the object. A stream from aFilecarries its length, which the binding needs up front; a stream of unknown length is refused with411.env.FILES.get(key)returns a standardResponse(ornull), withcontent-typeandcontent-lengthheaders from the stored object, so the download handler can pass the body straight through without loading it into memory.content-disposition: attachmentmakes the browser save the file instead of opening it. Without it, someone could upload an HTML page with a script in it and send people a link that runs it on your Cell's domain.
4. Deploy
ribo deploydeployed file-drop
address 33ed412f5c1vn
kind js
url https://file-drop.strand-9c.tissue.dev
vault UPLOAD_TOKEN
g7 FILES→drop-files5. Upload something
Open the url in a browser, choose a file, type the password and press Upload. The page comes back with the download link.
The same thing works from a terminal. -F file=@report.pdf attaches a local file; --form-string sends the password as literal text, so a password starting with @ or < isn't read as a filename:
curl -s https://file-drop.strand-9c.tissue.dev/upload \
-F file=@report.pdf --form-string token='your-password'And you can see what's in the bucket from the CLI:
ribo bucket ls drop-filesWhat you have
A password-protected upload page on HTTPS, files in private object storage, and a shareable link per file that downloads it. Nothing is publicly listable: a file can only be fetched by someone who has its link.
To remove a file, delete it by key with ribo bucket rm drop-files:<key>, where the key is the part of the link after /f/. Add a DELETE route that calls env.FILES.delete(key) if you'd rather do it over HTTP.
For uploads from a script or another service that shouldn't go through the Cell, the management API can mint a short-lived signed URL for one object (POST /v1/buckets/:bucket/presign), and the bucket also speaks the S3 API. g7 buckets covers both.
Next steps
- g7 binding API:
get,head,put,deleteandlist - What is object storage?: buckets, keys, and S3-compatible storage
- What is a presigned URL?: one-off access to a single object
- g7 limitations: sizes, metadata and what the binding leaves out