Files
OpenFrame/lib/client/upload-chunking.ts
yusufipk b51e690062 fix: close the findings the test suite surfaced
The suite that landed in #43/#44 was written against existing behaviour, so a
number of tests pinned bugs rather than asserting correct behaviour. This fixes
the production code and moves each of those tests onto the fixed behaviour in
the same change.

Security:

- project-download: derive the archive entry extension from the last path
  segment and restrict it to a short alphanumeric run, so an extensionless
  allowlisted url can no longer contribute a path separator; validate the r2
  branch against the strict proxy-path pattern instead of a `startsWith`, which
  let `/api/upload/video/clip.mp4/../../etc/passwd` through verbatim.
- rate-limit: hash a key or action wider than its column instead of skipping the
  query. Both the guard and the failing INSERT used to answer "allowed", so the
  limit stopped applying entirely. Warn at startup when TRUSTED_PROXY_MODE is
  unset in production.
- video uploads: the file name decides the content type; a client-declared video
  mime no longer makes `payload.exe` acceptable.
- email templates: escape in the helpers rather than relying on every caller,
  with an explicit `rawEmailHtml()` opt-out for the one call site that builds
  markup. `escapeHtml` now covers the single quote.
- CSP: allow loopback object storage outside production only.
- route-access: reach the billing redirect only for the workspace owner. Keying
  it off the owner's billing status alone made the redirect target an oracle for
  whose subscription had lapsed, and sent members to a page they cannot act on.
- search: carry the same billing condition every other read path carries.
- logger: check `err.name` as well as `err.constructor.name`, so a re-thrown,
  deserialised or minified Prisma error is still redacted.
- upload tokens: resolve the signing secret outside the try, so a server booted
  without one fails loudly instead of reporting every grant as a forgery.
- invitations: never downgrade an existing membership, and report a scoped
  invitation that points at nothing as not_found rather than accepted.
- auth: resolve the workspace role for every signed-in caller, so
  checkProjectAccess and computeProjectAccess stop disagreeing about the owner
  who also owns the workspace. The `intent` option is gone with it.
- r2-media-proxy: validate the object key inside the proxy so the guard travels
  with the function; delete the unused, unanchored `mediaUrlToR2Key`.
- r2: sign the content type into presigned PUT grants.

Correctness:

- frame rate snapping picks the nearest standard, not the first within
  tolerance, so 24, 30 and 60 fps are reachable at all.
- a version upload registers its Bunny cleanup as soon as bunny-init answers, so
  a failed tus upload no longer leaves a billed video behind.
- deleting videos clears storage before the rows, so a refused DELETE leaves a
  retryable row rather than an orphaned object.
- an expired upload session can be cancelled, which is what releases its quota.
- `voice/` joins the delete allowlist, so a voice note can be removed by the
  module that wrote it.
- a failed CORS write propagates instead of being mistaken for an empty config
  and replacing the bucket's rules.
- filtering projects by workspace no longer hides projects the unfiltered call
  returns.
- upload retries skip aborts and permanent 4xx; progress no longer divides by
  zero.
- reply edits no longer clear the comment's tag; optimistic resolve rolls back
  to the state it replaced; the delete snapshot is captured once.
- assorted UI fixes: duplicate React keys, double-click guards reading stale
  closures, the tag list fetched twice per load, a failed member list rendering
  as an empty one, a stale "Initializing upload..." beside a failure, and a
  registration banner pointing at an email that never arrives.

Consistency and access:

- the two download routes answer 404 for an id belonging to another tenant, as
  the comment export route already did. A caller who does belong still gets 403.
- accessible names for the share-link password field, the guest name gates, the
  version dialog inputs and the comment-tag controls.

Repository health:

- the runner image installs production dependencies only.
- a setup file for the unit project restores stubbed env centrally.
- native tsconfig path resolution replaces vite-tsconfig-paths.
- `uploadBytesWithProgress` exists once.
- admin stats bill Bunny storage to the workspace owner like every other
  quota, gate on the configured flag, wire up the single-flight guard and count
  the statuses that belonged to no bucket.
- `r2Client.destroy()` releases the presign client too.
- `prepare` tolerates a production install, where husky is absent.
2026-07-26 18:53:54 +07:00

104 lines
4.2 KiB
TypeScript

/**
* Pure arithmetic extracted from `r2-video-upload.ts`.
*
* The uploader itself is XMLHttpRequest wiring, `fetch` calls and timers, so the
* only test that can reach it is the end-to-end upload spec, and that spec only
* ever walks the happy path. The numbers below are the part of the uploader that
* is actually worth pinning down: which bytes each multipart part carries, how
* long a failed part waits before it is retried, and what percentage the UI is
* told. They live here so they can be called directly with fixed inputs.
*
* Nothing in this module touches the network, the DOM or a timer.
*/
/**
* Wait, in milliseconds, before each attempt at uploading a single multipart
* part, indexed by attempt number. Index 0 is the first try and is never waited
* on, so the schedule is really "try, then retry after 2s, 5s and 10s": four
* attempts and at most 17 seconds of backoff per part.
*/
export const PART_RETRY_DELAYS_MS = [0, 2000, 5000, 10000];
/**
* How long attempt `attempt` waits before it runs. The first attempt never
* waits, and an attempt past the end of the schedule is not one the caller
* should be making, so it waits not at all rather than for `undefined` ms.
*/
export function getRetryDelayMs(attempt: number, delays: number[] = PART_RETRY_DELAYS_MS): number {
if (attempt <= 0) return 0;
return delays[attempt] ?? 0;
}
export type PartByteRange = { start: number; end: number };
/**
* The slice of the file that a given part carries. Part numbers are 1-based
* because that is what S3 uses, and the final part is short: it stops at the end
* of the file rather than at a full part boundary.
*
* The part list comes from the server, which sized it from the same file length,
* so `partNumber` is always within range in practice. A part beyond the end of
* the file would produce `end` below `start`, which `Blob.slice` reads as an
* empty range.
*/
export function getPartByteRange(
partNumber: number,
partSizeBytes: number,
totalBytes: number
): PartByteRange {
const start = (partNumber - 1) * partSizeBytes;
const end = Math.min(start + partSizeBytes, totalBytes);
return { start, end };
}
/** Whole-percent progress for a single-request upload. */
export function getUploadProgressPercent(loadedBytes: number, totalBytes: number): number {
if (totalBytes <= 0) return 0;
return Math.round((loadedBytes / totalBytes) * 100);
}
/**
* Whole-percent progress across a multipart upload, given the bytes reported so
* far for each part. Clamped at 100: parts report their own progress
* independently and a re-tried part can briefly double-count.
*
* A total of zero reports 0 rather than dividing. The division produced NaN, which
* reached the UI as "Uploading... NaN%".
*/
export function getMultipartProgressPercent(
loadedBytesPerPart: number[],
totalBytes: number
): number {
if (totalBytes <= 0) return 0;
const loaded = loadedBytesPerPart.reduce((sum, value) => sum + value, 0);
return Math.min(100, Math.round((loaded / totalBytes) * 100));
}
/**
* Whether a failed attempt is worth repeating.
*
* The retry loop used to repeat every rejection, including the user's own cancellation
* and permanently-failing statuses. Cancelling an upload therefore did not cancel it: the
* part sat through the full 2s, 5s and 10s backoff and fired three more PUTs before the
* error surfaced. An expired presigned URL behaved the same way, turning one dead part
* into four requests and 17 seconds of apparent hanging.
*/
export function isRetryableUploadError(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
if (/aborted/i.test(message)) return false;
const status = statusFromUploadErrorMessage(message);
if (status === null) return true; // A network error has no status and is worth a retry.
if (status === 408 || status === 429) return true;
return status < 400 || status >= 500;
}
/** The status code an upload error message carries, if it carries one. */
export function statusFromUploadErrorMessage(message: string): number | null {
const match = /failed with status (\d{3})\b/i.exec(message);
if (!match) return null;
const status = Number(match[1]);
return Number.isFinite(status) ? status : null;
}