Functional Weave
Code in TypeScript

storage.signed-url

Signed URLs for a browser to upload a file straight to S3 or Google Cloud Storage, and to download it.

Integration · does I/O It talks to s3 or gcs, reads 2 secrets from the environment, and is tested by contract tests on recorded exchanges, offline. Providers and environment.

TypeScript only A Python or Rust project cannot use it.

1.0.0 · published 2026-10-09 by charlie · Anterra

Pinned by 25 contract tests on recorded exchanges, offline, run in TypeScript · per provider: s3 13, gcs 10.signUpload 13 · signDownload 12

What it does

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`.

The functions

A group: 2 functions that work together, each in its own file, each pinned by its own tests. A project can install only the ones it calls.

  1. signUpload (key: string, contentType: string, expiresSeconds: int = 900) -> SignedUrl
  2. signDownload (key: string, expiresSeconds: int = 900, filename: string? = null) -> SignedUrl

The types it declares, generated into your project

export type HttpMethod = "GET" | "PUT";

/** A URL that works without credentials until it expires. */
export interface SignedUrl {
  /** PUT to upload, GET to download */
  readonly method: HttpMethod;
  /** the signed URL */
  readonly url: string;
  /** headers the request must send exactly as given (the upload's content-type) */
  readonly headers: Readonly<Record<string, string>>;
  /** when it stops working, ISO 8601 UTC */
  readonly expiresAt: string;
}

Once installed, your code imports each one from the group's module.

signUpload throws on bad input 13 tests

export function signUpload(key: string, contentType: string, expiresSeconds: number = 900): SignedUrl
keystringthe object's name in the bucket, such as avatars/u_42.png
contentTypestringthe file's type, such as image/png; the browser must send exactly this
expiresSecondsinthow long the URL works, 1 to 604800 (a week)
returnsSignedUrla PUT URL, and the headers the upload must carry

For example

  • signUpload(avatars/u_42.png, image/png) → method PUT, url https://acme-uploads.s3.eu-west-2.amazonaws.com/avatars/u_42.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260301%2Feu-west-2%2Fs3… s3: a PUT URL for an avatar, the content type signed
  • signUpload(invoices/2026/03/inv 001.pdf, application/pdf, 3,600) → method PUT, url https://storage.googleapis.com/acme-uploads/invoices/2026/03/inv%20001.pdf?X-Goog-Algorithm=GOOG4-HMAC-SHA256&X-Goog-Credential=GOOG1EXAMPLEACCESSIDFORCONTRACTTEST… gcs: an hour-long PUT URL, a space in the key
  • signUpload(docs/report.csv, text/csv; charset=utf-8) → method PUT, url https://accountid.r2.cloudflarestorage.com/acme-uploads/docs/report.csv?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=R2EXAMPLEACCESSKEY01%2F20260301%2Fauto%2F… s3: Cloudflare R2 through S3_ENDPOINT, path-style, region auto
import { signUpload } from "#fune/storage.signed-url@^1";
impl/typescript/sign_upload.ts · 42 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { chooseProvider } from "./funeio.ts";
import type { SignedUrl } from "./storage_signed_url_types.ts";
import { utf8Encode } from "./encoding_utf8.ts";  ← from encoding.utf8 ^1.0.0 · built alongside by fune
import { s3Presign } from "./storage_signed_url_adapter_s3.ts";
import { gcsPresign } from "./storage_signed_url_adapter_gcs.ts";

const PROVIDERS = ["s3", "gcs"];

/** An object key a URL may be signed for: no traversal, no leading slash, no control characters, 1024 bytes at most. */
export function checkKey(key: string): void {
  if (typeof key !== "string" || key === "") throw new Error("key is the object's name, such as avatars/u_42.png");
  if (key.startsWith("/")) throw new Error(`key ${JSON.stringify(key)} starts with "/"; name it from the bucket's root, without one`);
  if (key.includes("..")) throw new Error(`key ${JSON.stringify(key)} contains ".."`);
  if (/[\u0000-\u001f\u007f]/.test(key)) throw new Error("key contains a control character");
  if (utf8Encode(key).length > 1024) throw new Error("key is longer than 1024 bytes");
}

/** An expiry the stores accept: a whole number of seconds, 1 to 604800. */
export function checkExpiry(expiresSeconds: number): void {
  if (!Number.isInteger(expiresSeconds) || expiresSeconds < 1 || expiresSeconds > 604800) {
    throw new Error("expiresSeconds is a whole number from 1 to 604800 (a week)");
  }
}

/** The provider STORAGE_PROVIDER names. */
export function storageProvider(): string {
  return chooseProvider("STORAGE_PROVIDER", PROVIDERS);
}

/**
 * A URL the browser PUTs the file to, straight to the bucket, with the
 * content type it must send: it is signed, so another type is refused.
 */
export function signUpload(key: string, contentType: string, expiresSeconds: number = 900): SignedUrl {
  checkKey(key);
  if (typeof contentType !== "string" || !/^[A-Za-z0-9.+-]+\/[A-Za-z0-9.+-]+(\s*;\s*[A-Za-z0-9.+-]+=[A-Za-z0-9.+"-]+)*$/.test(contentType)) {
    throw new Error(`contentType ${JSON.stringify(contentType)} is not a media type such as image/png`);
  }
  checkExpiry(expiresSeconds);
  const request = { method: "PUT" as const, key, expiresSeconds, contentType, filename: null };
  return storageProvider() === "s3" ? s3Presign(request) : gcsPresign(request);
}

signDownload throws on bad input 12 tests

export function signDownload(key: string, expiresSeconds: number = 900, filename: string | null = null): SignedUrl
keystringthe object's name in the bucket
expiresSecondsinthow long the URL works, 1 to 604800 (a week)
filenamestring?when given, the browser saves the file under this name instead of showing it
returnsSignedUrla GET URL

For example

  • signDownload(test.txt, 86,400) → method GET, url https://examplebucket.s3.amazonaws.com/test.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request&X… s3: AWS's documented example, reproduced exactly
  • signDownload(avatars/u_42.png, 300, avatar.png) → method GET, url https://acme-uploads.s3.eu-west-2.amazonaws.com/avatars/u_42.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260301%2Feu-west-2%2Fs3… s3: saved as a file name
  • signDownload(invoices/2026/03/inv 001.pdf) → method GET, url https://storage.googleapis.com/acme-uploads/invoices/2026/03/inv%20001.pdf?X-Goog-Algorithm=GOOG4-HMAC-SHA256&X-Goog-Credential=GOOG1EXAMPLEACCESSIDFORCONTRACTTEST… gcs: a GET URL, the default fifteen minutes
import { signDownload } from "#fune/storage.signed-url@^1";
impl/typescript/sign_download.ts · 19 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import type { SignedUrl } from "./storage_signed_url_types.ts";
import { checkExpiry, checkKey, storageProvider } from "./storage_signed_url_sign_upload.ts";  ← signUpload, another function of this group · built into the same file, even by a slim install
import { s3Presign } from "./storage_signed_url_adapter_s3.ts";
import { gcsPresign } from "./storage_signed_url_adapter_gcs.ts";

/**
 * A URL the browser GETs the object from. With a filename the store answers
 * with Content-Disposition: attachment, so the browser saves it under that
 * name rather than showing it.
 */
export function signDownload(key: string, expiresSeconds: number = 900, filename: string | null = null): SignedUrl {
  checkKey(key);
  checkExpiry(expiresSeconds);
  if (filename !== null && (typeof filename !== "string" || filename === "" || /[\u0000-\u001f\u007f"\\/]/.test(filename))) {
    throw new Error("filename is a plain file name: no quotes, slashes, backslashes or control characters");
  }
  const request = { method: "GET" as const, key, expiresSeconds, contentType: null, filename };
  return storageProvider() === "s3" ? s3Presign(request) : gcsPresign(request);
}

Providers and environment

An integration is one interface with a provider behind it for each service it can use; each provider is an adapter file in the package. STORAGE_PROVIDER picks the provider at run time. Its code reaches the outside only through funeio, which fune build writes beside it. Values are never part of a package: set them in the environment.

ProviderWhat it is
s3Amazon S3, or any S3-compatible store (Cloudflare R2, MinIO) at S3_ENDPOINT: SigV4 query signing
gcsGoogle Cloud Storage, signed with an HMAC key (GOOG4-HMAC-SHA256)
VariableKindNeededRead byWhat it is
STORAGE_PROVIDERconfig · picks the providerrequiredevery providerwhere files are stored: s3 or gcs
S3_BUCKETconfigrequireds3 onlythe bucket
S3_REGIONconfigrequireds3 onlyits region, such as eu-west-2 (auto for R2)
S3_ACCESS_KEY_IDconfigrequireds3 onlythe access key id of a key that may put and get objects in the bucket
S3_SECRET_ACCESS_KEYsecretrequireds3 onlythat key's secret
S3_ENDPOINTconfigoptionals3 onlyan S3-compatible endpoint, such as https://<account>.r2.cloudflarestorage.com; path-style URLs when set
GCS_BUCKETconfigrequiredgcs onlythe bucket
GCS_HMAC_ACCESS_IDconfigrequiredgcs onlythe access id of an HMAC key for a service account that may write and read the bucket
GCS_HMAC_SECRETsecretrequiredgcs onlythat HMAC key's secret

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 4 dependencies, pins them in fune.lock, downloads only the TypeScript package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add storage.signed-url

That builds the whole group. To build only what you call, and whatever it uses inside the group:

fune add storage.signed-url --only signUpload

An integration reads its settings and secrets from the environment. fune build writes every variable it reads, with what each is, to .fune/build/.env.example; fune secrets says which are set (never their values), and fune secrets --check fails a deploy step when one is missing.

fune secrets --check
Download for TypeScript storage.signed-url-1.0.0-typescript.fune · 34,484 bytes sha256 f2b70026d3dd5031874a328f4e49f3169e125aba5267488eb33e84a1bcbd94c6

The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./storage.signed-url-1.0.0-typescript.fune, or fetch it from a terminal with fune pull storage.signed-url@1.0.0:typescript.

It is TypeScript only, so there is no package for Python or Rust. The full package is one file too: storage.signed-url-1.0.0.fune, 34,456 bytes, sha256 1453b0cd3ea22d9478f5559ac5c8ff9027bcf241f2c6a4a1aeb340d646d55d4a.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

// fune: before storage.signed-url.signUpload
// fune: before storage.signed-url.signDownload

after — your function gets the result and the arguments, and returns the final result.

// fune: after storage.signed-url.signUpload
// fune: after storage.signed-url.signDownload

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

// fune: replace crypto.hmac-sha256 in storage.signed-url
// fune: replace crypto.sha256 in storage.signed-url
// fune: replace encoding.hex in storage.signed-url
// fune: replace encoding.utf8 in storage.signed-url

step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show storage.signed-url --steps.

// fune: step storage.signed-url.<fn> after <n|label>

Contract tests

These are contract tests on recorded exchanges, offline: each case runs the interface through one provider with fake credentials and a fixed clock, and the funeio seam serves the HTTP exchanges or socket dialogue it recorded. A request that differs from the recording, or a recorded exchange never made, fails the case. They prove the integration speaks the protocol as recorded and handles what the service answers; they do not reach the service. Every function needs at least 8, every provider at least 2, and every function that does I/O a case through each provider. fune verify runs them in a project, and the registry ran them in its sandbox, which has no network. Cases per provider: s3 13, gcs 10. The exact JSON is contracts.json.

signUpload 13 contract tests

CaseArgumentsExpected
s3 s3: a PUT URL for an avatar, the content type signed avatars/u_42.png, image/png → method PUT, url https://acme-uploads.s3.eu-west-2.amazonaws.com/avatars/u_42.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260301%2Feu-west-2%2Fs3…
gcs gcs: an hour-long PUT URL, a space in the key invoices/2026/03/inv 001.pdf, application/pdf, 3,600 → method PUT, url https://storage.googleapis.com/acme-uploads/invoices/2026/03/inv%20001.pdf?X-Goog-Algorithm=GOOG4-HMAC-SHA256&X-Goog-Credential=GOOG1EXAMPLEACCESSIDFORCONTRACTTEST…
s3 s3: Cloudflare R2 through S3_ENDPOINT, path-style, region auto docs/report.csv, text/csv; charset=utf-8 → method PUT, url https://accountid.r2.cloudflarestorage.com/acme-uploads/docs/report.csv?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=R2EXAMPLEACCESSKEY01%2F20260301%2Fauto%2F…
s3 s3: MinIO on localhost, a port in the host, non-ASCII in the key a/b c/été.txt, text/plain, 60 → method PUT, url http://localhost:9000/dev-bucket/a/b%20c/%C3%A9t%C3%A9.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20260301%2Fus-east-1%2Fs3%2Faws4_request&…
s3 s3: a bucket with a dot is path-style, a week at most x.json, application/json, 604,800 → method PUT, url https://s3.amazonaws.com/acme.uploads/x.json?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260301%2Fus-east-1%2Fs3%2Faws4_request&X-Am…
s3 a key with .. is refused avatars/../secrets.txt, text/plain → error: contains ".."
gcs a key with a leading slash /avatars/u.png, image/png → error: starts with "/"
s3 a key with a control character a b.png, image/png → error: key contains a control character
gcs a key longer than 1024 bytes ééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé… → error: key is longer than 1024 bytes
s3 a content type that is not one a.png, png → error: contentType "png" is not a media type
Show the other 3 tests
CaseArgumentsExpected
gcs an expiry over a week a.png, image/png, 604,801 → error: expiresSeconds is a whole number from 1 to 604800
s3 no secret set a.png, image/png → error: S3_SECRET_ACCESS_KEY is not set
no provider chosen a.png, image/png → error: STORAGE_PROVIDER is not set; set it to one of s3, gcs

signDownload 12 contract tests

CaseArgumentsExpected
s3 s3: AWS's documented example, reproduced exactly test.txt, 86,400 → method GET, url https://examplebucket.s3.amazonaws.com/test.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20130524%2Fus-east-1%2Fs3%2Faws4_request&X…
s3 s3: saved as a file name avatars/u_42.png, 300, avatar.png → method GET, url https://acme-uploads.s3.eu-west-2.amazonaws.com/avatars/u_42.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260301%2Feu-west-2%2Fs3…
gcs gcs: a GET URL, the default fifteen minutes invoices/2026/03/inv 001.pdf → method GET, url https://storage.googleapis.com/acme-uploads/invoices/2026/03/inv%20001.pdf?X-Goog-Algorithm=GOOG4-HMAC-SHA256&X-Goog-Credential=GOOG1EXAMPLEACCESSIDFORCONTRACTTEST…
gcs gcs: a non-ASCII file name has a UTF-8 form r.pdf, 900, résumé.pdf → method GET, url https://storage.googleapis.com/acme-uploads/r.pdf?X-Goog-Algorithm=GOOG4-HMAC-SHA256&X-Goog-Credential=GOOG1EXAMPLEACCESSIDFORCONTRACTTESTS0000000000000000000000%2…
s3 s3: reserved characters in the key are encoded, the clock read in whole seconds a+b&c=d.txt → method GET, url https://acme-uploads.s3.eu-west-2.amazonaws.com/a%2Bb%26c%3Dd.txt?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIOSFODNN7EXAMPLE%2F20260301%2Feu-west-2%2Fs…
s3 a file name with a quote is refused a.png, 900, a".png → error: filename is a plain file name
gcs an expiry of 0 a.png, 0 → error: expiresSeconds is a whole number from 1 to 604800
gcs an empty key → error: key is the object's name
gcs a traversal in the key ../etc/passwd → error: contains ".."
s3 an endpoint with a path is refused a.png → error: S3_ENDPOINT is an origin
Show the other 2 tests
CaseArgumentsExpected
gcs no HMAC secret set a.png → error: GCS_HMAC_SECRET is not set
an unknown provider a.png → error: STORAGE_PROVIDER is "azure"; set it to one of s3, gcs

Verification

Verified by the operator, not the sandbox 25 test vectors declared; none run by the registry.

Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.

Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON

More from the author

From a Next.js route handler:

// 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).

Files

PathBytes
README.md2,753
adapters/typescript/gcs.ts1,004
adapters/typescript/s3.ts5,599
contracts.json14,302
impl/typescript/sign_download.ts1,064
impl/typescript/sign_upload.ts2,211