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.
This commit is contained in:
yusufipk
2026-07-26 18:53:54 +07:00
parent 0ceba72d5b
commit b51e690062
111 changed files with 1665 additions and 804 deletions
@@ -116,7 +116,12 @@ export function useCommentActions({
const [editingCommentId, setEditingCommentId] = useState<string | null>(null);
const [editText, setEditText] = useState('');
const [editTagId, setEditTagId] = useState<string | null>(null);
// `undefined` means "this editor does not manage a tag", which is the reply editor:
// replies have no tag picker. `null` means "no tag", which the comment editor seeds
// from the comment itself. Initialising to `null` made `editTagId !== undefined` always
// true, so editing a reply's text sent `tagId: null` and cleared its tag, or sent a
// stale value left over from a previous edit.
const [editTagId, setEditTagId] = useState<string | null | undefined>(undefined);
const [editAnnotationData, setEditAnnotationData] = useState<string | null | undefined>(
undefined
);
@@ -569,6 +574,11 @@ export function useCommentActions({
if (!activeVersionId) return;
isMutatingRef.current = true;
// The optimistic flip, the request body and the rollback all derive from the same
// value. Flipping relative to the row (`!c.isResolved`) while the body and the
// rollback came from `currentlyResolved` meant a failed request could leave the
// comment in a state it was never in whenever the two disagreed.
const nextResolved = !currentlyResolved;
setVideo((prev) => {
if (!prev) return prev;
return {
@@ -578,7 +588,7 @@ export function useCommentActions({
? {
...v,
comments: v.comments.map((c) =>
c.id === commentId ? { ...c, isResolved: !c.isResolved } : c
c.id === commentId ? { ...c, isResolved: nextResolved } : c
),
}
: v
@@ -590,7 +600,7 @@ export function useCommentActions({
const res = await fetch(`/api/comments/${commentId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ isResolved: !currentlyResolved }),
body: JSON.stringify({ isResolved: nextResolved }),
});
if (!res.ok) {
@@ -1027,7 +1037,7 @@ export function useCommentActions({
});
setEditingCommentId(null);
setEditText('');
setEditTagId(null);
setEditTagId(undefined);
setEditAnnotationData(undefined);
setIsEditingAnnotation(false);
if (finalAnnotationData !== undefined && finalAnnotationData) {
@@ -1070,9 +1080,17 @@ export function useCommentActions({
isMutatingRef.current = true;
// The snapshot is taken once, however many times React runs the updater. React is
// free to invoke an updater more than once (StrictMode, and React 19 retries a
// render that threw), and a second run would otherwise capture the post-delete
// state, turning a failed delete into a silent confirmation of it.
const previousVideoRef: { current: VideoData | null } = { current: null };
let capturedSnapshot = false;
setVideo((prev) => {
previousVideoRef.current = prev;
if (!capturedSnapshot) {
previousVideoRef.current = prev;
capturedSnapshot = true;
}
if (!prev) return prev;
return {
...prev,
@@ -1,6 +1,6 @@
'use client';
import { useCallback, useState } from 'react';
import { useCallback, useRef, useState } from 'react';
import { toast } from 'sonner';
import type {
BunnyDownloadPreference,
@@ -70,10 +70,14 @@ interface UseDownloadActionsParams {
export function useDownloadActions({ activeVersion, video }: UseDownloadActionsParams) {
const [activeDownloadTarget, setActiveDownloadTarget] = useState<DownloadTarget | null>(null);
const isDownloadingVideo = activeDownloadTarget !== null;
// The guard reads a ref, not the state. Two calls originating in the same render both
// saw the old state value and both proceeded, so a fast double-click downloaded the
// file twice.
const isDownloadingRef = useRef(false);
const startDownload = useCallback(
async (preference: BunnyDownloadPreference = 'compressed') => {
if (!activeVersion || !video || isDownloadingVideo) return;
if (!activeVersion || !video || isDownloadingRef.current) return;
if (!video.canDownload) {
toast.error('Download is disabled for this shared link');
return;
@@ -88,6 +92,7 @@ export function useDownloadActions({ activeVersion, video }: UseDownloadActionsP
}
const target: DownloadTarget = activeVersion.providerId === 'bunny' ? preference : 'direct';
isDownloadingRef.current = true;
setActiveDownloadTarget(target);
let progressToast: DownloadProgressToastHandle | null = null;
try {
@@ -191,10 +196,11 @@ export function useDownloadActions({ activeVersion, video }: UseDownloadActionsP
toast.error('Failed to start download');
}
} finally {
isDownloadingRef.current = false;
setActiveDownloadTarget(null);
}
},
[activeVersion, video, isDownloadingVideo]
[activeVersion, video]
);
return {
@@ -13,6 +13,11 @@ import type { VersionActionsConfig, VideoData } from '@/components/video-page/ty
import { resolvePublicBunnyCdnHostname } from '@/lib/bunny-cdn';
import { cleanupPendingR2VideoUpload, uploadVideoToR2 } from '@/lib/client/r2-video-upload';
/** What a failed version upload has to undo, depending on which provider it started on. */
type PendingVersionCleanup =
| { objectKey: string; uploadToken: string; reservationId: string | null }
| { bunnyVideoId: string; uploadToken: string };
interface UseVersionActionsParams extends VersionActionsConfig {
setVideo: Dispatch<SetStateAction<VideoData | null>>;
activeVersionId: string | null;
@@ -60,7 +65,18 @@ export function useVersionActions({
}
};
const uploadNewVersionFile = async (file: File, title: string) => {
/**
* `onPendingCleanup` is called the moment there is something to clean up, which for a
* Bunny upload is when bunny-init answers and the remote video already exists. Waiting
* for this function to return instead meant a tus `onError` threw past the assignment,
* so every failed Bunny upload left a video behind on the Bunny side: billed, and
* invisible in the app.
*/
const uploadNewVersionFile = async (
file: File,
title: string,
onPendingCleanup: (cleanup: PendingVersionCleanup) => void
) => {
if (!projectId) throw new Error('Missing project');
if (directUploadProvider === 'r2') {
@@ -102,6 +118,9 @@ export function useVersionActions({
data: { videoId: bunnyVideoId, libraryId, signature, expirationTime, uploadToken },
} = await initRes.json();
// The remote video exists from here on, so it is cleanable from here on.
onPendingCleanup({ bunnyVideoId, uploadToken });
await new Promise((resolve, reject) => {
setNewVersionUploadStatus('Uploading video...');
const upload = new tus.Upload(file, {
@@ -154,17 +173,7 @@ export function useVersionActions({
setIsCreatingVersion(true);
setNewVersionUploadStatus('');
setNewVersionUploadProgress(0);
let pendingCleanup:
| {
objectKey: string;
uploadToken: string;
reservationId: string | null;
}
| {
bunnyVideoId: string;
uploadToken: string;
}
| null = null;
let pendingCleanup: PendingVersionCleanup | null = null;
try {
let finalVideoUrl = '';
@@ -194,7 +203,9 @@ export function useVersionActions({
title = title.replace(/\.[^/.]+$/, '');
}
const uploaded = await uploadNewVersionFile(newVersionFile, title);
const uploaded = await uploadNewVersionFile(newVersionFile, title, (cleanup) => {
pendingCleanup = cleanup;
});
finalVideoUrl = uploaded.finalVideoUrl;
finalProviderId = uploaded.finalProviderId;
finalProviderVideoId = uploaded.finalProviderVideoId;
@@ -57,13 +57,18 @@ export function useVideoAssets({
const [assets, setAssets] = useState<VideoAsset[]>([]);
const [isLoadingAssets, setIsLoadingAssets] = useState(true);
const [isCreatingAsset, setIsCreatingAsset] = useState(false);
const [activeDeleteAssetId, setActiveDeleteAssetId] = useState<string | null>(null);
// A set, not a single slot. Two overlapping deletes used to clear each other's
// spinner, so the first one stopped indicating progress while it was still running.
const [deletingAssetIds, setDeletingAssetIds] = useState<string[]>([]);
const [activeDownloadAssetId, setActiveDownloadAssetId] = useState<string | null>(null);
const [hasMoreAssets, setHasMoreAssets] = useState(false);
const [nextAssetsOffset, setNextAssetsOffset] = useState(0);
const [isLoadingMoreAssets, setIsLoadingMoreAssets] = useState(false);
const assetsEtagRef = useRef<string | null>(null);
const isMutatingRef = useRef(false);
// The double-call guard reads a ref, not the state: two calls originating in the same
// render both saw the old state value and both fetched the next page.
const isLoadingMoreRef = useRef(false);
const fetchAssets = useCallback(
async (options?: { useEtag?: boolean; silent?: boolean }) => {
@@ -106,7 +111,8 @@ export function useVideoAssets({
);
const loadMoreAssets = useCallback(async () => {
if (isLoadingMoreAssets || !hasMoreAssets) return;
if (isLoadingMoreRef.current || !hasMoreAssets) return;
isLoadingMoreRef.current = true;
setIsLoadingMoreAssets(true);
try {
const res = await fetch(
@@ -129,9 +135,10 @@ export function useVideoAssets({
} catch {
toast.error('Failed to load more assets');
} finally {
isLoadingMoreRef.current = false;
setIsLoadingMoreAssets(false);
}
}, [hasMoreAssets, isLoadingMoreAssets, nextAssetsOffset, videoId]);
}, [hasMoreAssets, nextAssetsOffset, videoId]);
useEffect(() => {
void fetchAssets({ useEtag: true });
@@ -198,7 +205,7 @@ export function useVideoAssets({
const deleteAsset = useCallback(
async (assetId: string) => {
setActiveDeleteAssetId(assetId);
setDeletingAssetIds((prev) => (prev.includes(assetId) ? prev : [...prev, assetId]));
isMutatingRef.current = true;
try {
const res = await fetch(`/api/videos/${videoId}/assets/${assetId}`, {
@@ -217,7 +224,7 @@ export function useVideoAssets({
toast.error('Failed to delete asset');
return false;
} finally {
setActiveDeleteAssetId(null);
setDeletingAssetIds((prev) => prev.filter((id) => id !== assetId));
isMutatingRef.current = false;
}
},
@@ -292,7 +299,7 @@ export function useVideoAssets({
assets,
isLoadingAssets,
isCreatingAsset,
activeDeleteAssetId,
deletingAssetIds,
activeDownloadAssetId,
hasMoreAssets,
isLoadingMoreAssets,
@@ -129,6 +129,14 @@ export function useVideoPageData({ mode, videoId, propProjectId }: UseVideoPageD
void fetchVersionComments(activeVersionId, true);
}, [activeVersionId, fetchVersionComments]);
// The auto-select reads the current selection from a ref rather than the dependency
// array. Depending on `selectedTagId` meant setting it re-ran the effect, so
// /api/projects/<id>/tags was requested a second time on every page load.
const selectedTagIdRef = useRef(selectedTagId);
useEffect(() => {
selectedTagIdRef.current = selectedTagId;
}, [selectedTagId]);
useEffect(() => {
if (!projectId) return;
async function fetchTags() {
@@ -139,7 +147,7 @@ export function useVideoPageData({ mode, videoId, propProjectId }: UseVideoPageD
const data = await res.json();
const tags = data.data || [];
setAvailableTags(tags);
if (tags.length > 0 && !selectedTagId) {
if (tags.length > 0 && !selectedTagIdRef.current) {
setSelectedTagId(tags[0].id);
}
}
@@ -148,7 +156,7 @@ export function useVideoPageData({ mode, videoId, propProjectId }: UseVideoPageD
}
}
void fetchTags();
}, [projectId, selectedTagId, videoId]);
}, [projectId, videoId]);
return {
video,
@@ -242,8 +242,15 @@ export function useVideoPlayer({
const tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
// A document with no <script> is unusual but not impossible, and dereferencing the
// first one threw on mount when there was none. Next always emits one in the app;
// appending to <head> covers everything else.
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode?.insertBefore(tag, firstScriptTag);
if (firstScriptTag?.parentNode) {
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
} else {
document.head.appendChild(tag);
}
window.onYouTubeIframeAPIReady = () => {
setIsApiLoaded(true);
@@ -15,8 +15,23 @@ const STANDARD_FRAME_RATES = [23.976, 24, 25, 29.97, 30, 48, 50, 59.94, 60, 120]
export function normalizeFrameRate(rate: number | undefined): number | null {
if (typeof rate !== 'number' || !Number.isFinite(rate) || rate < 12 || rate > 120) return null;
const standard = STANDARD_FRAME_RATES.find((value) => Math.abs(rate - value) / value < 0.015);
return standard ?? rate;
// Nearest, not first-within-tolerance. The NTSC pairs (23.976/24, 29.97/30, 59.94/60)
// are 0.1 percent apart and the tolerance is 1.5 percent, so taking the first match made
// an exactly 30 fps source snap to 29.97 and left 24, 30 and 60 unreachable entirely.
// That produced the very drift the snapping exists to prevent, roughly 18 frames after
// ten minutes.
let nearest: number | null = null;
let nearestDistance = Infinity;
for (const value of STANDARD_FRAME_RATES) {
const distance = Math.abs(rate - value);
if (distance / value < 0.015 && distance < nearestDistance) {
nearest = value;
nearestDistance = distance;
}
}
return nearest ?? rate;
}
/**