Files
OpenFrame/tests/component/share-link-unlock.test.tsx
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

193 lines
7.1 KiB
TypeScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ShareLinkUnlock } from '@/components/share-link-unlock';
const replace = vi.fn();
const refresh = vi.fn();
vi.mock('next/navigation', () => ({
useRouter: () => ({ replace, refresh, push: vi.fn(), back: vi.fn(), prefetch: vi.fn() }),
}));
// next/link needs the App Router context to mount. The link is incidental to
// the validation branches under test, so stub it down to an anchor.
vi.mock('next/link', () => ({
default: ({ href, children }: { href: string; children: React.ReactNode }) => (
<a href={href}>{children}</a>
),
}));
let fetchMock: ReturnType<typeof vi.fn>;
/**
* A password input has no ARIA role, so `getByRole` cannot reach it whatever the
* markup does. `getByLabelText` can, and it only works because the field now has a
* visually hidden <label> associated by id: it used to have no label, no aria-label and
* no aria-labelledby, which left the placeholder as the only handle anything had.
*/
function passwordField() {
return screen.getByLabelText('Password');
}
beforeEach(() => {
fetchMock = vi.fn().mockResolvedValue({ ok: true, json: () => Promise.resolve({}) });
vi.stubGlobal('fetch', fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
replace.mockReset();
refresh.mockReset();
});
describe('ShareLinkUnlock', () => {
it('asks for the password and offers a sign-in escape hatch', () => {
render(<ShareLinkUnlock videoId="vid1" />);
expect(screen.getByRole('heading', { name: 'Password Required' })).toBeInTheDocument();
expect(passwordField()).toHaveAttribute('type', 'password');
expect(passwordField()).toHaveAttribute('maxLength', '128');
expect(screen.getByRole('link', { name: 'sign in' })).toHaveAttribute('href', '/login');
});
it('ignores a submit with an empty field', async () => {
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(fetchMock).not.toHaveBeenCalled();
expect(replace).not.toHaveBeenCalled();
});
it('ignores a submit with only whitespace', async () => {
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), ' ');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(fetchMock).not.toHaveBeenCalled();
});
it('posts the password to the session endpoint for this video', async () => {
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/watch/vid1/session');
expect(init.method).toBe('POST');
expect(JSON.parse(init.body as string)).toEqual({ password: 'hunter2' });
});
it('sends the password verbatim, without trimming', async () => {
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), ' hunter2 ');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
expect(JSON.parse(fetchMock.mock.calls[0][1].body as string)).toEqual({
password: ' hunter2 ',
});
});
it('navigates into the video on success', async () => {
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
await waitFor(() => expect(replace).toHaveBeenCalledWith('/watch/vid1'));
expect(refresh).toHaveBeenCalledTimes(1);
expect(screen.queryByText('Invalid password')).not.toBeInTheDocument();
});
it('submits on Enter as well as on the button', async () => {
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'hunter2{Enter}');
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
expect(replace).toHaveBeenCalledWith('/watch/vid1');
});
it('shows the server message for a rejected password', async () => {
fetchMock.mockResolvedValue({
ok: false,
json: () => Promise.resolve({ error: 'This link has expired' }),
});
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'wrong');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(await screen.findByText('This link has expired')).toBeInTheDocument();
expect(replace).not.toHaveBeenCalled();
});
it('falls back to "Invalid password" when the error body is not JSON', async () => {
fetchMock.mockResolvedValue({ ok: false, json: () => Promise.reject(new SyntaxError('nope')) });
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'wrong');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(await screen.findByText('Invalid password')).toBeInTheDocument();
});
it('reports a network failure separately from a wrong password', async () => {
fetchMock.mockRejectedValue(new Error('offline'));
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'hunter2');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(await screen.findByText('Failed to verify password')).toBeInTheDocument();
});
it('clears a stale error when the password is retried', async () => {
fetchMock.mockResolvedValue({
ok: false,
json: () => Promise.resolve({ error: 'This link has expired' }),
});
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'wrong');
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
expect(await screen.findByText('This link has expired')).toBeInTheDocument();
fetchMock.mockResolvedValue({ ok: true, json: () => Promise.resolve({}) });
await userEvent.click(screen.getByRole('button', { name: 'Continue' }));
await waitFor(() => expect(replace).toHaveBeenCalledWith('/watch/vid1'));
expect(screen.queryByText('This link has expired')).not.toBeInTheDocument();
});
it('blocks a second submit while the first is still in flight', async () => {
let release: (value: unknown) => void = () => {};
fetchMock.mockReturnValue(
new Promise((resolve) => {
release = resolve;
})
);
render(<ShareLinkUnlock videoId="vid1" />);
await userEvent.type(passwordField(), 'hunter2');
const submit = screen.getByRole('button', { name: 'Continue' });
await userEvent.click(submit);
expect(submit).toBeDisabled();
// The spinner that replaces the label carries a visually hidden name, so the button
// stays findable and announceable while it submits.
expect(submit).toHaveAccessibleName('Unlocking');
release({ ok: true, json: () => Promise.resolve({}) });
await waitFor(() => expect(replace).toHaveBeenCalledTimes(1));
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});