Files
OpenFrame/components/video-page/hooks/use-download-actions.ts
T
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

212 lines
7.6 KiB
TypeScript

'use client';
import { useCallback, useRef, useState } from 'react';
import { toast } from 'sonner';
import type {
BunnyDownloadPreference,
Comment,
DownloadTarget,
Version,
VideoData,
} from '@/components/video-page/types';
import { resolvePublicBunnyCdnHostname } from '@/lib/bunny-cdn';
import {
downloadNamedFile,
downloadProgressLabel,
downloadProgressPercent,
extensionFromUrl,
navigateDownload,
} from '@/lib/client/download-file';
import {
createDownloadProgressToast,
type DownloadProgressToastHandle,
} from '@/components/download-progress-toast';
function sanitizeDownloadFileName(value: string): string {
return value
.replace(/[<>:"/\\|?*\u0000-\u001F]/g, '-')
.replace(/\s+/g, ' ')
.trim();
}
function getAllowedHosts() {
const bunnyCdnHostname = resolvePublicBunnyCdnHostname();
return [
...(bunnyCdnHostname ? [bunnyCdnHostname] : []),
...(process.env.NEXT_PUBLIC_DIRECT_DOWNLOAD_ALLOWED_HOSTS ?? '').split(','),
]
.map((host) => host.trim().toLowerCase())
.filter(Boolean);
}
function getSafeDirectDownloadUrl(rawUrl: string): string | null {
try {
const parsed = new URL(rawUrl);
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return null;
}
const allowedHosts = getAllowedHosts();
if (allowedHosts.length === 0) {
return null;
}
const normalizedHost = parsed.hostname.toLowerCase();
if (!allowedHosts.includes(normalizedHost)) {
return null;
}
return parsed.toString();
} catch {
return null;
}
}
interface UseDownloadActionsParams {
activeVersion: (Version & { comments: Comment[] }) | undefined;
video: VideoData | null;
}
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 || isDownloadingRef.current) return;
if (!video.canDownload) {
toast.error('Download is disabled for this shared link');
return;
}
if (
activeVersion.providerId !== 'bunny' &&
activeVersion.providerId !== 'direct' &&
activeVersion.providerId !== 'r2'
) {
toast.error('This video source does not support direct download');
return;
}
const target: DownloadTarget = activeVersion.providerId === 'bunny' ? preference : 'direct';
isDownloadingRef.current = true;
setActiveDownloadTarget(target);
let progressToast: DownloadProgressToastHandle | null = null;
try {
let downloadUrl: string | null = null;
if (activeVersion.providerId === 'bunny') {
const prepareRes = await fetch(
`/api/versions/${activeVersion.id}/download?source=${preference}&prepare=1`,
{
cache: 'no-store',
}
);
if (!prepareRes.ok) {
const prepareBody = await prepareRes.json().catch(() => null);
const fallbackError =
preference === 'original'
? 'Original file is not available for this video'
: 'Compressed file is not available for this video';
const errorMessage =
typeof prepareBody?.error === 'string' ? prepareBody.error : fallbackError;
throw new Error(errorMessage);
}
downloadUrl = `/api/versions/${activeVersion.id}/download?source=${preference}`;
} else if (activeVersion.providerId === 'r2') {
if (!activeVersion.originalUrl.startsWith('/api/upload/video/')) {
throw new Error('Direct download URL is not allowed');
}
downloadUrl = activeVersion.originalUrl;
} else {
downloadUrl = getSafeDirectDownloadUrl(activeVersion.originalUrl);
if (!downloadUrl) {
throw new Error('Direct download URL is not allowed');
}
}
if (!downloadUrl) {
throw new Error('Missing download URL');
}
// File name: "<video title> <version label>" if the editor set a label
// for this version, otherwise "<video title> v<number>".
const versionLabel = activeVersion.versionLabel?.trim();
const baseName =
sanitizeDownloadFileName(
versionLabel
? `${video.title} ${versionLabel}`
: `${video.title} v${activeVersion.versionNumber}`
) || 'video';
if (activeVersion.providerId === 'r2') {
// Same-origin proxy: the download attribute applies and streams
// without buffering the whole file in memory (any size).
const ext = extensionFromUrl(activeVersion.originalUrl) || 'mp4';
navigateDownload(downloadUrl, `${baseName}.${ext}`);
} else {
// Bunny (CDN redirect) and direct hosts are cross-origin, so the
// download attribute is ignored on a plain navigation. Fetch the bytes
// (CORS is open) and save them with our filename — unless the file is
// over 10 GB, in which case downloadNamedFile returns false and we fall
// back to a plain navigation (streams to disk with the CDN's name).
const fallbackExt =
(activeVersion.providerId === 'direct'
? extensionFromUrl(activeVersion.originalUrl)
: '') || 'mp4';
// The file is pulled into the browser before it can be saved, which on
// a big file / slow connection takes a while with no native download UI
// — show live progress so it doesn't look stuck. The panel can be
// minimized because it sits over the comment composer.
progressToast = createDownloadProgressToast(`download-${activeVersion.id}`, {
title: `Downloading “${baseName}”`,
description: 'Starting…',
});
const saved = await downloadNamedFile(downloadUrl, `${baseName}.${fallbackExt}`, (p) => {
progressToast?.update({
description: downloadProgressLabel(p),
percent: downloadProgressPercent(p),
});
});
if (saved) {
progressToast.success(`“${baseName}” downloaded`);
} else {
// Too large to buffer (or fetch blocked): let the browser download it
// directly (its own progress UI, CDN filename).
progressToast.dismiss();
navigateDownload(downloadUrl);
}
}
} catch (error) {
console.error('Failed to start video download:', error);
// The progress panel never expires on its own, so clear it before the
// error toast replaces it.
progressToast?.dismiss();
if (error instanceof Error && error.message === 'Direct download URL is not allowed') {
toast.error('This direct download host is not allowed');
} else if (error instanceof Error && error.message) {
toast.error(error.message);
} else {
toast.error('Failed to start download');
}
} finally {
isDownloadingRef.current = false;
setActiveDownloadTarget(null);
}
},
[activeVersion, video]
);
return {
activeDownloadTarget,
isDownloadingVideo,
startDownload,
};
}