fix(uploads): stop a storage hold from being dropped by whoever can name it

A reservation id was never a secret and could not have been one. An upload
token is base64url(payload) followed by its signature, so a client can read
every claim out of its own token, and the two R2 init routes hand their
reservation ids to the client outright. The asset route takes a reservation
id from the request body and deleted it on the strength of that id and the
billed user alone, and every hold an account owns is billed to the same user.

So a caller could start a Bunny upload, read the id out of the token they
were just given, quote it while attaching a one byte image or even a bare
YouTube link, and have the quota handed back while the upload carried on.
Repeat and a trial worth three gigabytes uploads as much as it likes for as
long as Bunny takes to report a figure of its own. Signing the id rather than
handing it over bought nothing, because signing is not hiding.

A hold now records what it was opened for and is only ever consumed by that
flow, so naming one is no longer enough to drop it.

Guests hold against the workspace owner's quota rather than their own and had
no way to give it back: the release was gated on being signed in. Declaring a
size and walking away cost the guest nothing and cost the owner their whole
remaining allowance for two hours. The guest grant now carries the reservation
and the declared size, bound to the Bunny video as well as to ours, so
cancelling gives the quota back and costs them the upload it stood for. What a
guest can hold without cancelling lapses in half an hour rather than two hours.

The in-transaction fallback check counted the account's Bunny storage as zero
on a Bunny upload, because the figure was only prefetched for R2 providers and
that branch was unreachable for Bunny until this PR made it reachable. On an
account whose storage is all Bunny that was a check that could not fail. It is
prefetched for every provider that can reach the fallback now.
This commit is contained in:
2026-08-18 11:07:18 +03:00
parent 4ff801738c
commit 00f1d430b8
22 changed files with 721 additions and 130 deletions
+36 -2
View File
@@ -29,6 +29,33 @@ export async function getStorageLimitForUser(userId: string): Promise<bigint> {
// TTL for upload reservations: 30 minutes is enough for R2 image/audio uploads
const RESERVATION_TTL_MS = 30 * 60 * 1000;
/**
* What a hold was opened for.
*
* A reservation is only ever consumed by the flow that opened it, and the
* finalize routes match on this as well as on the id. Without it, naming a
* reservation would be enough to drop it: the asset route takes a reservation id
* from the request body, and every hold an account owns is billed to the same
* user, so an image being attached could quietly release a video upload that was
* still in flight. The ids are not secret. Two of them are handed to the client
* outright, and the rest ride inside signed-but-readable token payloads.
*/
export const UPLOAD_RESERVATION_PURPOSES = {
/** A comment attachment or standalone image going to R2. */
IMAGE: 'IMAGE',
/** A voice note going to R2. */
AUDIO: 'AUDIO',
/** Image and voice attachments weighed together when a comment is posted. */
ATTACHMENT: 'ATTACHMENT',
/** A presigned direct upload to our own S3-compatible storage. */
R2_VIDEO: 'R2_VIDEO',
/** A direct upload to Bunny, where the bytes never pass through us. */
BUNNY: 'BUNNY',
} as const;
export type UploadReservationPurpose =
(typeof UPLOAD_RESERVATION_PURPOSES)[keyof typeof UPLOAD_RESERVATION_PURPOSES];
// Sentinel error thrown inside a Prisma transaction to signal quota exceeded
class QuotaExceededError extends Error {}
@@ -137,6 +164,7 @@ export async function enforceStorageQuota(
export async function reserveStorageQuota(
userId: string,
incomingSizeBytes: bigint,
purpose: UploadReservationPurpose,
reservationTtlMs: number = RESERVATION_TTL_MS
): Promise<{ reservationId: string | null } | { error: NextResponse }> {
if (!isStripeFeatureEnabled()) {
@@ -199,7 +227,7 @@ export async function reserveStorageQuota(
}
const reservation = await tx.uploadReservation.create({
data: { billedUserId: userId, sizeBytes: incomingSizeBytes, expiresAt },
data: { billedUserId: userId, sizeBytes: incomingSizeBytes, expiresAt, purpose },
select: { id: true },
});
@@ -218,16 +246,22 @@ export async function reserveStorageQuota(
/**
* Deletes an upload reservation created by `reserveStorageQuota`.
* Safe to call with `null` (no-op) for flows where billing is disabled.
*
* Pass the purpose wherever the caller knows it. A release that names only an id
* will delete a hold opened for something else, which is the same hole the
* purpose column exists to close.
*/
export async function releaseStorageReservation(
reservationId: string | null,
billedUserId?: string | null
billedUserId?: string | null,
purpose?: UploadReservationPurpose
): Promise<void> {
if (!reservationId) return;
await db.uploadReservation.deleteMany({
where: {
id: reservationId,
...(billedUserId ? { billedUserId } : {}),
...(purpose ? { purpose } : {}),
},
});
}