# Files and uploads

Send files directly to R2, confirm durable upload intent and recover interrupted multipart uploads.

<Diagram name="uploads" alt="An authenticated upload persists intent, creates an immutable R2 object, then confirms metadata; cron recovers unfinished confirmation." />

## Gateway and isolation [#gateway-and-isolation]

The web client uses authorized upload procedures for direct byte transport and the files-sdk gateway at `/api/files` for browsing, downloads and deletion. Every operation checks the request’s Session (the signed snapshot, at most 60 s old, or the database) and reads the membership from the database. Minting a download or upload URL, including a download redirect, also checks the database session. Purging the trash (`purge`, which deletes files for good) also checks the database session and is limited to Organization owners and admins; a Member gets HTTP 403. The SDK identifies presign, completion and proxy PUT as the same upload operation, so completion and proxy PUT each also read the database session once. URLs minted before revocation work until expiry, at most 15 minutes. The gateway's upload and proxy tokens are signed with a key derived from `BETTER_AUTH_SECRET` for that purpose alone (`files.token-secret.ts`: HMAC-SHA256 of a fixed label), never with the secret itself, so a signature from one protocol is not a credential in the other; rotating the secret rotates this key with it. The server applies `orgs/<organizationId>/`; a filename cannot select or escape an Organization. One private R2 bucket serves all Organizations.

Keys preserve the User's filename, including spaces and Unicode, under [ADR-0001](/docs/adr/0001-stored-file-keys-keep-the-user-s-filename). Treat keys as opaque and encode them for URLs. Do not reintroduce filename sanitization that silently changes the display name.

## Files workspace [#files-workspace]

On the web, `useFilesWorkspace` (`features/files/files.hooks.ts`) owns the page: one tenant-scoped listing through the gateway, the Document Text status of each item and the selection the details dialog shows. Every Files query key starts with the Session identity (`user:organization`), so another Organization's same key never reuses a listing, a trash page or a signed URL. Components receive items and callbacks; the operations behind the card menu, the share dialog, the preview and the search live in `files.actions.hooks.ts`, `files.preview.hooks.ts` and `files.trash.hooks.ts`, and no component holds the files-sdk handle (W5).

The dashboard's file count and bytes come from the read-only `files.stats` procedure (`packages/api/src/features/files`), which sums the live objects under the Organization's prefix on the server and is prefetched by the dashboard loader. `uploaded_file` records confirmed uploads but not later deletes, moves or restores, so the listing, not the table, is the source.

## Durable upload lifecycle [#durable-upload-lifecycle]

`uploads.prepare` persists an intent after validating membership, MIME type and size. A signed PUT binds the exact key, size, content type and conditional create. Files above 16 MiB use multipart uploads with 8 MiB parts, at most three concurrent parts and at most three attempts per part. The browser sends `File.slice()` objects and resumes from server-listed parts.

Completion validates part lengths and ETags, then checks HEAD metadata before confirming the file. Signed URLs expire after 15 minutes; intents last 24 hours. Cron recovers missing acknowledgements and aborts abandoned multipart sessions.

A reservation is not free: cron checks each one every round, and above 16 MiB it holds a multipart session in the bucket. So an uploader may hold at most 100 unfinished uploads and an Organization 500 (`uploads.rules.ts`), counted in every state that is not final; the next `uploads.prepare` answers 429 until one finishes or expires (a cancelled one counts until its 16 minutes are over, a `publishing` one until it settles). `uploads.complete` marks nothing stored before it has seen the bytes. The sweep for abandoned multipart sessions reads at most two listing pages of 25 uploads per tick and keeps its position in `job_cursor` (`uploads.multipart-sweep`), so its cost per tick is the same however many young reservations the bucket holds; a long listing only takes more ticks to pass through. The position carries a revision, so a run that another one overtook stores nothing.

The upload job has 10 seconds of the 25-second tick. Recovery gets 4 seconds and each cleanup step (staged purge, multipart sweep, expired holds) gets 2. A claim moves an upload behind the others. The sweep checkpoints each abort attempt so the next run can reach untried sessions from the same listing. Staged removal is rescheduled before contacting storage. Each cleanup abort or removal has a 500 ms timeout. An expired intent releases its live key without checking storage. Expired in-place cleanup stops sending deletes and releases the key 16 minutes after expiry to let earlier deletes settle.

### Staging: signed URLs never write a live key [#staging-signed-urls-never-write-a-live-key]

A direct upload has two keys. The intent's `key` is the live one the file will have, `orgs/<organizationId>/<requestKey>/<name>`. Its `staging_key` is where the bytes actually go: `staging/orgs/<organizationId>/<intentId>`, derived from the row and enforced by a database CHECK. Every signed URL, single PUT and multipart part alike, addresses the staging key. Nothing under `staging/` is listed, counted, downloadable or visible to agent tools, because every one of those reads is scoped to `orgs/<organizationId>/`.

Confirmation moves the bytes in three steps under the intent's lease:

1. **Authorize.** The staged object has the declared size and type, a HEAD finds the live key empty, and the uploader is still a Member. The intent becomes `publishing`. An upload that fails here is `rejected` and never leaves staging.
2. **Publish.** A server-side copy inside the bucket to the live key, with R2's `cf-copy-destination-if-none-match: *`, so it creates the object or does nothing. The copy stamps the object with the intent's id (`x-amz-meta-upload-intent`). No bytes pass through the Worker.
3. **Commit.** Only for a live object that carries that stamp: one transaction completes the intent and inserts `uploaded_file`, the document, the audit entry and the webhook notice.

A copy request that fails or times out may still land. The Worker can send copies during a 10-minute window. For 15 more minutes recovery looks for the stamped object and commits it when found. At the deadline the database releases the key without waiting for HEAD. A copy already present can remain visible without an upload record if recovery never saw it. For a resumed publish, `publish_settles_at` protects the live key for 15 minutes after the latest copy dispatch. An interrupted attempt keeps a conservative fence through the copy window plus 15 minutes. During the fence, the file stays readable and deleting or moving it returns 409. A file confirmed by its first copy can be deleted immediately.

Three rules follow, and a change to this code must keep all of them:

- **Upload cleanup deletes staging keys only.** Cancellation, rejection and expiry remove the intent's own staged object. No upload path deletes from `orgs/`, so a file can never be lost to another upload's cleanup. A cancelled intent keeps removing late writes for 16 minutes; a settled one (`complete`, `rejected`, `expired`) keeps its staged object for 16 minutes and cron then removes it once (`staging_purge_at`). While the object exists its create-only URL cannot write again, and after that the URL has expired.
- **One writer per live key.** While an intent is `prepared`, `stored`, `publishing`, `cleanup` or `aborting`, a move, a restore from the trash or a copy _into_ its live key fails with a conflict (HTTP 409). The other way round, a delete, move, restore or copy takes a hold (`upload_key_hold`) on every key it writes or removes, in the transaction that makes this check, and releases it when its storage call returned; `uploads.prepare` refuses a held key, and a hold whose call did not report success lasts 15 minutes. Deleting or moving a key fails the same way while its publish is in flight or the proxy is writing it, and succeeds a moment later.
- **A URL is worth one staged object.** A used, cancelled or rejected URL can still write to staging until it expires, and to nothing else. It cannot recreate a file that was moved or deleted.

The gateway proxy (files up to 10 MiB sent through the Worker) writes the live key itself. Its reservation starts pinned (`UNVERIFIED_ETAG`) until prepare sees an empty key. Recovery rejects a reservation only if its pin still matches, without reading or changing the live object. Intents created before staging can confirm bytes at their live key before their reservation expires. They receive no new signed URLs and cancellation leaves their live object alone.

Images can be up to 100 MiB, documents 1 GiB and ZIP archives 5 GiB. The legacy gateway proxy remains capped at 10 MiB and reauthorizes PUTs through the files-sdk patch. Soft delete is enabled; versioning is not. Text previews stop at 64 KiB, and downloads can use range requests without loading the whole original into the Worker.

Confirmed supported files enter the separate [Document Text workflow](/docs/features/documents). Storage limits and conversion limits are independent; a stored original can remain downloadable when text preparation fails. [ADR-0008](/docs/adr/0008-documents-and-large-uploads) explains both paths.

## Configure and extend [#configure-and-extend]

Supply `STORAGE_BUCKET`, `STORAGE_ENDPOINT`, `STORAGE_ACCESS_KEY_ID` and `STORAGE_SECRET_ACCESS_KEY` in the intended environment. Setup does not create an R2 bucket. Configure bucket CORS for the actual web origins, upload/read methods and signed headers; expose `ETag` so multipart completion can read it. `apps/web/r2-cors.json` is the starting template, not a list of every worktree or deployed origin.

Extend size/MIME rules in storage config and retain admission, confirmation and source-version checks. Keep `files-sdk` on one compatible copy across web, API and storage and rebase its pinned patch on upgrades. Verify upload, download byte equality, anonymous denial, prefix isolation, multipart resume/cancel and interrupted confirmation.

## Key files [#key-files]

- [`apps/web/src/routes/api/files/$.ts`](https://github.com/CarlosZiegler/fofo/blob/main/apps/web/src/routes/api/files/$.ts)
- [`packages/api/src/features/files/files.http.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/api/src/features/files/files.http.ts)
- [`packages/api/src/features/files/files.token-secret.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/api/src/features/files/files.token-secret.ts)
- [`packages/storage/src/create-r2-files.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/storage/src/create-r2-files.ts)
- [`packages/storage/src/upload-plugin.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/storage/src/upload-plugin.ts)
- [`apps/web/src/features/files/files.hooks.ts`](https://github.com/CarlosZiegler/fofo/blob/main/apps/web/src/features/files/files.hooks.ts)
- [`packages/api/src/features/files/files.service.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/api/src/features/files/files.service.ts)
- [`packages/api/src/features/uploads/uploads.service.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/api/src/features/uploads/uploads.service.ts)
- [`packages/api/src/features/uploads/uploads.publish.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/api/src/features/uploads/uploads.publish.ts)
- [`packages/storage/src/direct-s3.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/storage/src/direct-s3.ts)
- [`packages/storage/src/config.ts`](https://github.com/CarlosZiegler/fofo/blob/main/packages/storage/src/config.ts)
- [`patches/files-sdk@3.2.1.patch`](https://github.com/CarlosZiegler/fofo/blob/main/patches/files-sdk@3.2.1.patch)
