mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
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.
172 lines
5.8 KiB
TypeScript
172 lines
5.8 KiB
TypeScript
/**
|
|
* Pure helpers extracted from `use-video-player.ts`.
|
|
*
|
|
* The hook itself is ~1400 lines of hls.js wiring, iframe messaging and
|
|
* requestAnimationFrame loops that jsdom cannot run. The arithmetic below is the
|
|
* part that is actually worth pinning down with tests, so it lives here where it
|
|
* can be called directly with fixed inputs. Nothing in this module touches
|
|
* React, the DOM or any player SDK.
|
|
*/
|
|
|
|
// A frame number is only meaningful against a stable rate: a raw measurement
|
|
// drifts (29.94, 30.07, ...) and would slide the count by whole frames late in a
|
|
// long video. Snap to the nearest broadcast standard when we are close enough.
|
|
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;
|
|
|
|
// 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;
|
|
}
|
|
|
|
/**
|
|
* How far a single frame-mode step moves the playhead. Falls back to one second
|
|
* when no frame rate has been measured yet, which is also what the label says.
|
|
*/
|
|
export function getFrameStepSeconds(estimatedFrameRate: number | null): number {
|
|
if (estimatedFrameRate && Number.isFinite(estimatedFrameRate) && estimatedFrameRate > 0) {
|
|
return 1 / estimatedFrameRate;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
export function getFrameStepLabel(estimatedFrameRate: number | null): string {
|
|
if (estimatedFrameRate && Number.isFinite(estimatedFrameRate) && estimatedFrameRate > 0) {
|
|
return '1f';
|
|
}
|
|
return '1s';
|
|
}
|
|
|
|
/**
|
|
* In frame mode every skip collapses to exactly one frame, keeping only the
|
|
* direction of the requested jump. A zero-second request counts as forward.
|
|
*/
|
|
export function resolveSkipAmount(
|
|
seconds: number,
|
|
options: { isFrameMode: boolean; frameStepSeconds: number }
|
|
): number {
|
|
if (!options.isFrameMode) return seconds;
|
|
const direction = seconds === 0 ? 1 : Math.sign(seconds);
|
|
return options.frameStepSeconds * direction;
|
|
}
|
|
|
|
export function clampSeekTime(time: number, duration: number): number {
|
|
return Math.max(0, Math.min(duration, time));
|
|
}
|
|
|
|
/** Timeline fill / playhead offset, as a percentage clamped to [0, 100]. */
|
|
export function getPlayheadPercent(time: number, duration: number): number {
|
|
return duration > 0 ? Math.max(0, Math.min(100, (time / duration) * 100)) : 0;
|
|
}
|
|
|
|
/**
|
|
* Frame N covers [N/rate, (N+1)/rate); the epsilon keeps a time that lands
|
|
* exactly on a boundary from floating-point-ing down to N-1. The result never
|
|
* exceeds the last frame the duration can hold.
|
|
*/
|
|
export function getFrameIndexAtTime(time: number, frameRate: number, duration: number): number {
|
|
const lastFrame = duration > 0 ? Math.max(0, Math.ceil(duration * frameRate) - 1) : 0;
|
|
return Math.min(Math.floor(time * frameRate + 1e-6), lastFrame);
|
|
}
|
|
|
|
/** Convert a pointer x-coordinate into a time, using a captured timeline rect. */
|
|
export function timeFromClientX(
|
|
clientX: number,
|
|
rect: { left: number; width: number } | null,
|
|
duration: number
|
|
): number {
|
|
if (!rect || rect.width === 0) return 0;
|
|
const percentage = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
|
|
return percentage * duration;
|
|
}
|
|
|
|
/**
|
|
* Next or previous entry in the speed ladder, or `null` at either end. An
|
|
* unknown current speed behaves like index -1, so stepping up lands on the
|
|
* slowest option and stepping down does nothing.
|
|
*/
|
|
export function getAdjacentPlaybackSpeed(
|
|
speedOptions: number[],
|
|
currentSpeed: number,
|
|
direction: 1 | -1
|
|
): number | null {
|
|
const currentIndex = speedOptions.indexOf(currentSpeed);
|
|
if (direction === 1) {
|
|
if (currentIndex >= speedOptions.length - 1) return null;
|
|
return speedOptions[currentIndex + 1];
|
|
}
|
|
if (currentIndex <= 0) return null;
|
|
return speedOptions[currentIndex - 1];
|
|
}
|
|
|
|
export type PlayerShortcut =
|
|
| 'toggle-play'
|
|
| 'skip-back'
|
|
| 'skip-forward'
|
|
| 'speed-up'
|
|
| 'speed-down'
|
|
| 'toggle-mute'
|
|
| 'jump-back'
|
|
| 'jump-forward'
|
|
| 'toggle-fullscreen';
|
|
|
|
/**
|
|
* Map a physical key to a player action. `null` means "not a player shortcut",
|
|
* and the caller must then leave the event alone (no `preventDefault`), so that
|
|
* an unshifted comma still types a comma.
|
|
*/
|
|
export function resolvePlayerShortcut(event: {
|
|
code: string;
|
|
shiftKey?: boolean;
|
|
}): PlayerShortcut | null {
|
|
switch (event.code) {
|
|
case 'Space':
|
|
case 'KeyK':
|
|
return 'toggle-play';
|
|
case 'ArrowLeft':
|
|
return 'skip-back';
|
|
case 'ArrowRight':
|
|
return 'skip-forward';
|
|
case 'ArrowUp':
|
|
return 'speed-up';
|
|
case 'ArrowDown':
|
|
return 'speed-down';
|
|
case 'Comma':
|
|
return event.shiftKey ? 'speed-down' : null;
|
|
case 'Period':
|
|
return event.shiftKey ? 'speed-up' : null;
|
|
case 'KeyM':
|
|
return 'toggle-mute';
|
|
case 'KeyJ':
|
|
return 'jump-back';
|
|
case 'KeyL':
|
|
return 'jump-forward';
|
|
case 'KeyF':
|
|
return 'toggle-fullscreen';
|
|
default:
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** True when the keystroke belongs to a text field and must not be hijacked. */
|
|
export function isTypingTarget(target: HTMLElement): boolean {
|
|
return (
|
|
target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable === true
|
|
);
|
|
}
|