Files
OpenFrame/tests/unit/video-player-utils.test.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

271 lines
11 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import {
clampSeekTime,
getAdjacentPlaybackSpeed,
getFrameIndexAtTime,
getFrameStepLabel,
getFrameStepSeconds,
getPlayheadPercent,
isTypingTarget,
normalizeFrameRate,
resolvePlayerShortcut,
resolveSkipAmount,
timeFromClientX,
} from '@/components/video-page/hooks/video-player-utils';
const SPEEDS = [0.25, 0.5, 1, 1.5, 2];
describe('normalizeFrameRate', () => {
it('snaps a drifting measurement to a broadcast standard', () => {
expect(normalizeFrameRate(29.94)).toBe(29.97);
expect(normalizeFrameRate(23.9)).toBe(23.976);
expect(normalizeFrameRate(59.8)).toBe(59.94);
expect(normalizeFrameRate(24.9)).toBe(25);
});
it('returns an exact standard rate unchanged', () => {
for (const rate of [23.976, 24, 25, 29.97, 30, 48, 50, 59.94, 60, 120]) {
expect(normalizeFrameRate(rate)).toBe(rate);
}
});
// The tolerance is 1.5 percent but the NTSC pairs are only 0.1 percent apart, so taking
// the first entry within tolerance made 24, 30 and 60 unreachable and reported an
// exactly 30 fps source as 29.97: the very drift the snapping exists to prevent.
it('picks the nearest standard rather than the first within tolerance', () => {
expect(normalizeFrameRate(30.07)).toBe(30);
expect(normalizeFrameRate(29.99)).toBe(30);
expect(normalizeFrameRate(29.96)).toBe(29.97);
expect(normalizeFrameRate(23.99)).toBe(24);
expect(normalizeFrameRate(59.98)).toBe(60);
expect(normalizeFrameRate(59.95)).toBe(59.94);
});
it('keeps a plausible non-standard rate rather than forcing a snap', () => {
// 45fps is more than 1.5% away from every standard, so it must survive.
expect(normalizeFrameRate(45)).toBe(45);
expect(normalizeFrameRate(12)).toBe(12);
});
it('rejects rates outside the 12-120 window', () => {
expect(normalizeFrameRate(11.9)).toBeNull();
expect(normalizeFrameRate(120.1)).toBeNull();
expect(normalizeFrameRate(0)).toBeNull();
expect(normalizeFrameRate(-30)).toBeNull();
});
it('rejects non-finite and missing input', () => {
expect(normalizeFrameRate(undefined)).toBeNull();
expect(normalizeFrameRate(Number.NaN)).toBeNull();
expect(normalizeFrameRate(Number.POSITIVE_INFINITY)).toBeNull();
});
});
describe('getFrameStepSeconds', () => {
it('is the reciprocal of a measured frame rate', () => {
expect(getFrameStepSeconds(25)).toBe(0.04);
expect(getFrameStepSeconds(50)).toBe(0.02);
});
it('falls back to one second when no rate has been measured', () => {
expect(getFrameStepSeconds(null)).toBe(1);
expect(getFrameStepSeconds(0)).toBe(1);
expect(getFrameStepSeconds(-25)).toBe(1);
expect(getFrameStepSeconds(Number.NaN)).toBe(1);
expect(getFrameStepSeconds(Number.POSITIVE_INFINITY)).toBe(1);
});
});
describe('getFrameStepLabel', () => {
it('reads "1f" only when a usable frame rate is known', () => {
expect(getFrameStepLabel(29.97)).toBe('1f');
expect(getFrameStepLabel(null)).toBe('1s');
expect(getFrameStepLabel(0)).toBe('1s');
expect(getFrameStepLabel(Number.NaN)).toBe('1s');
});
it('agrees with getFrameStepSeconds about which unit is in play', () => {
for (const rate of [null, 0, Number.NaN, 24, 25, 60]) {
const usesFrames = getFrameStepLabel(rate) === '1f';
expect(getFrameStepSeconds(rate) !== 1).toBe(usesFrames);
}
});
});
describe('resolveSkipAmount', () => {
it('passes the requested seconds straight through outside frame mode', () => {
expect(resolveSkipAmount(-5, { isFrameMode: false, frameStepSeconds: 0.04 })).toBe(-5);
expect(resolveSkipAmount(5, { isFrameMode: false, frameStepSeconds: 0.04 })).toBe(5);
expect(resolveSkipAmount(0, { isFrameMode: false, frameStepSeconds: 0.04 })).toBe(0);
});
it('collapses any jump to a single frame in frame mode, keeping direction', () => {
expect(resolveSkipAmount(5, { isFrameMode: true, frameStepSeconds: 0.04 })).toBe(0.04);
expect(resolveSkipAmount(30, { isFrameMode: true, frameStepSeconds: 0.04 })).toBe(0.04);
expect(resolveSkipAmount(-5, { isFrameMode: true, frameStepSeconds: 0.04 })).toBe(-0.04);
expect(resolveSkipAmount(-30, { isFrameMode: true, frameStepSeconds: 0.04 })).toBe(-0.04);
});
it('treats a zero-second request as one frame forward', () => {
expect(resolveSkipAmount(0, { isFrameMode: true, frameStepSeconds: 0.04 })).toBe(0.04);
});
});
describe('clampSeekTime', () => {
it('keeps a time inside [0, duration]', () => {
expect(clampSeekTime(5, 10)).toBe(5);
expect(clampSeekTime(-3, 10)).toBe(0);
expect(clampSeekTime(25, 10)).toBe(10);
expect(clampSeekTime(10, 10)).toBe(10);
});
it('pins to zero while the duration is still unknown', () => {
expect(clampSeekTime(42, 0)).toBe(0);
});
});
describe('getPlayheadPercent', () => {
it('maps a time onto a 0-100 timeline position', () => {
expect(getPlayheadPercent(0, 10)).toBe(0);
expect(getPlayheadPercent(2.5, 10)).toBe(25);
expect(getPlayheadPercent(10, 10)).toBe(100);
});
it('clamps positions that fall outside the media', () => {
expect(getPlayheadPercent(-4, 10)).toBe(0);
expect(getPlayheadPercent(14, 10)).toBe(100);
});
it('returns 0 rather than NaN when the duration is unknown', () => {
expect(getPlayheadPercent(4, 0)).toBe(0);
expect(getPlayheadPercent(4, -1)).toBe(0);
});
});
describe('getFrameIndexAtTime', () => {
it('numbers frames from zero within their half-open interval', () => {
expect(getFrameIndexAtTime(0, 25, 60)).toBe(0);
expect(getFrameIndexAtTime(0.039, 25, 60)).toBe(0);
expect(getFrameIndexAtTime(0.04, 25, 60)).toBe(1);
expect(getFrameIndexAtTime(1, 25, 60)).toBe(25);
});
it('does not slip a frame backwards on an inexact boundary', () => {
// 1.16 * 25 evaluates to 28.999999999999996 in IEEE-754, so a bare
// Math.floor would report frame 28 for the exact start of frame 29.
expect(1.16 * 25).toBeLessThan(29);
expect(getFrameIndexAtTime(1.16, 25, 60)).toBe(29);
// Same trap at 4.1s on a 30fps timeline.
expect(4.1 * 30).toBeLessThan(123);
expect(getFrameIndexAtTime(4.1, 30, 60)).toBe(123);
});
it('never reports a frame past the end of the media', () => {
// 2s at 25fps holds frames 0..49.
expect(getFrameIndexAtTime(1.99, 25, 2)).toBe(49);
expect(getFrameIndexAtTime(2, 25, 2)).toBe(49);
expect(getFrameIndexAtTime(600, 25, 2)).toBe(49);
});
it('reports frame 0 while the duration is unknown', () => {
expect(getFrameIndexAtTime(12, 25, 0)).toBe(0);
});
});
describe('timeFromClientX', () => {
const rect = { left: 100, width: 200 };
it('maps a pointer position across the timeline onto a time', () => {
expect(timeFromClientX(100, rect, 60)).toBe(0);
expect(timeFromClientX(200, rect, 60)).toBe(30);
expect(timeFromClientX(300, rect, 60)).toBe(60);
});
it('clamps a pointer that has been dragged off either end', () => {
expect(timeFromClientX(-500, rect, 60)).toBe(0);
expect(timeFromClientX(5000, rect, 60)).toBe(60);
});
it('returns 0 when the timeline rect is missing or has no width', () => {
expect(timeFromClientX(200, null, 60)).toBe(0);
expect(timeFromClientX(200, { left: 100, width: 0 }, 60)).toBe(0);
});
});
describe('getAdjacentPlaybackSpeed', () => {
it('steps up and down the ladder', () => {
expect(getAdjacentPlaybackSpeed(SPEEDS, 1, 1)).toBe(1.5);
expect(getAdjacentPlaybackSpeed(SPEEDS, 1, -1)).toBe(0.5);
expect(getAdjacentPlaybackSpeed(SPEEDS, 0.5, -1)).toBe(0.25);
});
it('returns null at either end instead of wrapping around', () => {
expect(getAdjacentPlaybackSpeed(SPEEDS, 2, 1)).toBeNull();
expect(getAdjacentPlaybackSpeed(SPEEDS, 0.25, -1)).toBeNull();
});
it('recovers from an unknown current speed by starting at the slowest', () => {
expect(getAdjacentPlaybackSpeed(SPEEDS, 3, 1)).toBe(0.25);
expect(getAdjacentPlaybackSpeed(SPEEDS, 3, -1)).toBeNull();
});
it('returns null for an empty ladder', () => {
expect(getAdjacentPlaybackSpeed([], 1, 1)).toBeNull();
expect(getAdjacentPlaybackSpeed([], 1, -1)).toBeNull();
});
});
describe('resolvePlayerShortcut', () => {
it('maps the play/pause, seek, mute and fullscreen keys', () => {
expect(resolvePlayerShortcut({ code: 'Space' })).toBe('toggle-play');
expect(resolvePlayerShortcut({ code: 'KeyK' })).toBe('toggle-play');
expect(resolvePlayerShortcut({ code: 'ArrowLeft' })).toBe('skip-back');
expect(resolvePlayerShortcut({ code: 'ArrowRight' })).toBe('skip-forward');
expect(resolvePlayerShortcut({ code: 'KeyJ' })).toBe('jump-back');
expect(resolvePlayerShortcut({ code: 'KeyL' })).toBe('jump-forward');
expect(resolvePlayerShortcut({ code: 'KeyM' })).toBe('toggle-mute');
expect(resolvePlayerShortcut({ code: 'KeyF' })).toBe('toggle-fullscreen');
});
it('maps the arrow keys to speed changes regardless of shift', () => {
expect(resolvePlayerShortcut({ code: 'ArrowUp' })).toBe('speed-up');
expect(resolvePlayerShortcut({ code: 'ArrowDown' })).toBe('speed-down');
expect(resolvePlayerShortcut({ code: 'ArrowUp', shiftKey: true })).toBe('speed-up');
expect(resolvePlayerShortcut({ code: 'ArrowDown', shiftKey: true })).toBe('speed-down');
});
it('requires shift for the comma and period speed shortcuts', () => {
expect(resolvePlayerShortcut({ code: 'Comma', shiftKey: true })).toBe('speed-down');
expect(resolvePlayerShortcut({ code: 'Period', shiftKey: true })).toBe('speed-up');
// Unshifted, these must stay available for typing.
expect(resolvePlayerShortcut({ code: 'Comma', shiftKey: false })).toBeNull();
expect(resolvePlayerShortcut({ code: 'Period' })).toBeNull();
});
it('claims no other key', () => {
for (const code of ['KeyA', 'Enter', 'Escape', 'Tab', 'Digit1', 'Slash', 'ShiftLeft']) {
expect(resolvePlayerShortcut({ code, shiftKey: true })).toBeNull();
}
});
});
describe('isTypingTarget', () => {
const asTarget = (target: { tagName?: string; isContentEditable?: boolean }) =>
isTypingTarget(target as HTMLElement);
it('recognises the elements a keystroke should be left alone in', () => {
expect(asTarget({ tagName: 'INPUT' })).toBe(true);
expect(asTarget({ tagName: 'TEXTAREA' })).toBe(true);
expect(asTarget({ tagName: 'DIV', isContentEditable: true })).toBe(true);
});
it('lets the player claim keystrokes anywhere else', () => {
expect(asTarget({ tagName: 'BODY', isContentEditable: false })).toBe(false);
expect(asTarget({ tagName: 'DIV', isContentEditable: false })).toBe(false);
expect(asTarget({ tagName: 'BUTTON' })).toBe(false);
// Lowercase never happens for HTML elements, but the check is case
// sensitive and that is worth pinning.
expect(asTarget({ tagName: 'input' })).toBe(false);
});
});