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
+24 -20
View File
@@ -165,16 +165,16 @@ describe('checkRateLimit', () => {
expect(result.remaining).toBe(RATE_LIMIT_CONFIGS.api.maxRequests - 1);
});
// Defence in depth against oversized values reaching the query. The call is
// allowed but nothing is recorded, so an attacker cannot use a huge key to
// bloat the table either.
it('allows and records nothing for an over-long key or action', async () => {
// An oversized value is hashed to fit its column rather than skipped, so it is written
// and counted like any other. A huge key cannot bloat the table either: what lands in
// the column is a fixed-width digest.
it('records an over-long key and an over-long action', async () => {
const longKey = await checkRateLimit('x'.repeat(257), 'login', CONFIG);
const longAction = await checkRateLimit('1.2.3.4', 'y'.repeat(65), CONFIG);
expect(longKey.allowed).toBe(true);
expect(longAction.allowed).toBe(true);
expect(await countRows('rate_limits')).toBe(0);
expect(await countRows('rate_limits')).toBe(2);
});
it('records a key of exactly 255 characters, the column width', async () => {
@@ -184,27 +184,31 @@ describe('checkRateLimit', () => {
expect(await countRows('rate_limits')).toBe(1);
});
// Documents an off-by-one, reported rather than fixed. The guard in
// lib/rate-limit.ts rejects `key.length > 256`, but rate_limits.key is
// VARCHAR(255), so a 256-character key clears the guard and then fails the
// INSERT with P2010. The catch treats any database error as "allow", so such a
// key is never counted and the limit silently stops applying to it.
//
// Not reachable from the product today: every call site builds a key from an
// IP, a user id or a 24-character hash. The failure mode is fail-open, so a
// future longer key would disable a limit rather than break a page.
it('fails open for a 256-character key instead of counting it', async () => {
// Kept to four attempts, one past the limit, because each one logs the
// swallowed Postgres error and the point is made without ten copies of it.
// This is the case that used to fail open twice over: the guard allowed a 256-character
// key through, the INSERT then failed with SQLSTATE 22001 against a VARCHAR(255) column,
// and the catch answered "allowed" for every attempt. The key is now hashed before it
// reaches the query, so the limit applies to it like any other.
it('counts a 256-character key and blocks it past the cap', async () => {
const key = 'x'.repeat(256);
for (let attempt = 0; attempt < 4; attempt += 1) {
for (let attempt = 0; attempt < CONFIG.maxRequests; attempt += 1) {
const result = await checkRateLimit(key, 'login', CONFIG);
expect(result.allowed).toBe(true);
expect(result.remaining).toBe(CONFIG.maxRequests);
}
expect(await countRows('rate_limits')).toBe(0);
const blocked = await checkRateLimit(key, 'login', CONFIG);
expect(blocked.allowed).toBe(false);
expect(blocked.remaining).toBe(0);
expect(await countRows('rate_limits')).toBe(1);
expect((await db.rateLimit.findFirstOrThrow()).count).toBe(CONFIG.maxRequests + 1);
});
it('keeps two different over-long keys in separate buckets', async () => {
await checkRateLimit(`a${'x'.repeat(300)}`, 'login', CONFIG);
await checkRateLimit(`b${'x'.repeat(300)}`, 'login', CONFIG);
expect(await countRows('rate_limits')).toBe(2);
});
it('counts concurrent calls exactly once each', async () => {