Functional Weave
Code in Rust

storage.signed-url@1.0.0

README.md

2,753 bytes · view raw

# storage.signed-url

Let a browser upload a file straight to the bucket, and download it again,
without the file passing through your server and without giving the browser
a credential: your server signs a URL that works for one object, one method
and a few minutes. `STORAGE_PROVIDER` picks the store:

- **s3**: Amazon S3, with SigV4 query signing (`X-Amz-*`). Set `S3_BUCKET`,
  `S3_REGION`, `S3_ACCESS_KEY_ID` and `S3_SECRET_ACCESS_KEY`. For an
  S3-compatible store, such as Cloudflare R2 or MinIO, set `S3_ENDPOINT` to
  its origin (`https://<account>.r2.cloudflarestorage.com`, region `auto`) and
  the URLs are path-style. A bucket with a dot in its name is path-style too,
  since S3's wildcard certificate cannot cover it.
- **gcs**: Google Cloud Storage, signed with an HMAC key (`GOOG4-HMAC-SHA256`,
  `X-Goog-*`) at `storage.googleapis.com`. Make an HMAC key for a service
  account that may write and read the bucket, and set `GCS_BUCKET`,
  `GCS_HMAC_ACCESS_ID` and `GCS_HMAC_SECRET`.

From a Next.js route handler:

```ts
// app/api/uploads/route.ts
import { signUpload } from "#fune/storage.signed-url@^1";

export async function POST(req: Request) {
  const { contentType } = await req.json();
  const key = `avatars/${crypto.randomUUID()}.png`; // your naming, never the browser's
  const signed = signUpload(key, contentType, 300);
  return Response.json({ key, ...signed });
}

// in the browser
await fetch(signed.url, { method: signed.method, headers: signed.headers, body: file });
```

An upload URL signs the content type: the browser must send exactly the
`headers` it was given, or the store refuses the upload. A download URL with a
`filename` makes the store answer with `Content-Disposition: attachment`, so
the browser saves the file under that name (a non-ASCII name gets an RFC 5987
`filename*` form too). URLs last 1 second to a week (604800 seconds), 15
minutes by default; `expiresAt` says when.

Keys are checked before anything is signed: not empty, no `..`, no leading
`/`, no control characters, at most 1024 bytes. Choose keys on the server;
a key the browser picked can overwrite someone else's file.

Signing is local: no request is made, so the contract tests have no
exchanges, only the environment and the clock. One of them is AWS's own
documented example ("Authenticating Requests: Using Query Parameters",
GET object, `examplebucket`, 2013-05-24), reproduced to the signature; the
others were cross-checked against an independent signer written with Node's
crypto. Out of scope: the bucket's CORS rules (allow PUT from your origin with
the content-type header), POST policy forms, multipart uploads and size
limits (a signed PUT cannot cap the size; check it after the upload, or use a
policy upload).