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
@@ -40,11 +40,7 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
});
if (!approvalRequest) return apiErrors.notFound('Approval request');
const access = await checkProjectAccess(
approvalRequest.version.video.project,
session.user.id,
{ intent: 'manage' }
);
const access = await checkProjectAccess(approvalRequest.version.video.project, session.user.id);
const canCancel = approvalRequest.requestedById === session.user.id || access.canEdit;
if (!canCancel) return apiErrors.forbidden('Access denied');
+2 -2
View File
@@ -133,7 +133,7 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
const project = comment.version.video.project;
const userId = session?.user?.id ?? null;
const access = await checkProjectAccess(project, userId ?? undefined, { intent: 'manage' });
const access = await checkProjectAccess(project, userId ?? undefined);
const isOwner = userId === project.ownerId;
const isAuthor = !!userId && comment.authorId === userId;
const guestIdentityId = !userId ? getGuestIdentityFromRequest(request) : null;
@@ -295,7 +295,7 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
const isAuthor = !!userId && comment.authorId === userId;
// Project owners/admins and workspace admins can delete any comment
const access = userId ? await checkProjectAccess(project, userId, { intent: 'manage' }) : null;
const access = userId ? await checkProjectAccess(project, userId) : null;
const isPrivilegedUser = !!access?.canEdit;
let canDelete = isAuthor || isPrivilegedUser;
@@ -20,7 +20,7 @@ export async function GET(_request: NextRequest, { params }: RouteParams) {
});
if (!project) return apiErrors.notFound('Project');
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
if (!access.canEdit) return apiErrors.forbidden('Access denied');
const candidates = await getApprovalCandidatesForProject(projectId);
@@ -30,7 +30,7 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
@@ -93,7 +93,7 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
@@ -30,7 +30,7 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
@@ -112,7 +112,7 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
const isOwner = project.ownerId === session.user.id;
const isAdmin = project.members[0]?.role === ProjectMemberRole.ADMIN;
+2 -2
View File
@@ -103,7 +103,7 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
select: { id: true, ownerId: true, workspaceId: true, visibility: true },
});
const access = projectAccessTarget
? await checkProjectAccess(projectAccessTarget, session.user.id, { intent: 'manage' })
? await checkProjectAccess(projectAccessTarget, session.user.id)
: null;
if (!access?.canEdit) {
return apiErrors.forbidden('Access denied');
@@ -181,7 +181,7 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'delete' });
const access = await checkProjectAccess(project, session.user.id);
if (!access.canDelete) {
return apiErrors.forbidden('Only the project owner can delete it');
}
@@ -28,7 +28,7 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Access denied');
}
@@ -98,7 +98,7 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Access denied');
}
+1 -1
View File
@@ -97,7 +97,7 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Access denied');
}
@@ -170,7 +170,7 @@ export async function PATCH(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Video');
}
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(video.project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Access denied');
}
@@ -251,7 +251,7 @@ export async function DELETE(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Video');
}
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(video.project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Only project owner or admin can delete videos');
}
@@ -32,7 +32,7 @@ async function getVersionWithAccess(
}
const project = version.video.project;
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
const access = await checkProjectAccess(project, userId);
return { version, canEdit: access.canEdit, isOwner: access.isOwner };
}
@@ -74,7 +74,7 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Video');
}
const access = await checkProjectAccess(video.project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(video.project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Access denied');
}
@@ -5,7 +5,7 @@ import { db } from '@/lib/db';
import { logCleanupWarnings } from '@/lib/cleanup-warnings';
import { logError } from '@/lib/logger';
import { rateLimit } from '@/lib/rate-limit';
import { deleteProjectVideosWithCleanup } from '@/lib/video-delete';
import { deleteProjectVideosWithCleanup, VideoStorageCleanupError } from '@/lib/video-delete';
type RouteParams = { params: Promise<{ projectId: string }> };
@@ -32,7 +32,7 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Only project owner or admin can delete videos');
}
@@ -59,6 +59,17 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
if (error instanceof Error && error.message === 'VIDEO_NOT_FOUND') {
return apiErrors.badRequest('One or more selected videos do not belong to this project');
}
// Storage refused a delete, so nothing was removed and the videos are still there.
// Saying so lets the caller retry, which is the whole point of leaving the rows.
if (error instanceof VideoStorageCleanupError) {
logCleanupWarnings(
{ entityType: 'video', entityId: `bulk:${normalizedIds.join(',')}` },
error.cleanupInput
);
return apiErrors.internalError(
'Could not delete the stored media for these videos. Nothing was deleted; please try again.'
);
}
throw error;
}
@@ -27,7 +27,7 @@ async function getProjectWithEditAccess(projectId: string, userId: string) {
if (!project) return null;
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
const access = await checkProjectAccess(project, userId);
const canEdit = access.canEdit;
if (!canEdit) return null;
@@ -38,7 +38,7 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
const access = await checkProjectAccess(project, userId);
if (!access.canEdit) {
return apiErrors.forbidden('Access denied');
}
@@ -141,8 +141,8 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
}
const [sourceAccess, targetAccess] = await Promise.all([
checkProjectAccess(sourceProject, userId, { intent: 'manage' }),
checkProjectAccess(targetProject, userId, { intent: 'manage' }),
checkProjectAccess(sourceProject, userId),
checkProjectAccess(targetProject, userId),
]);
if (!sourceAccess.canEdit) {
return apiErrors.forbidden('You cannot move videos out of this project');
@@ -26,7 +26,7 @@ async function getProjectWithEditAccess(projectId: string, userId: string) {
if (!project) return null;
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
const access = await checkProjectAccess(project, userId);
if (!access.canEdit) return null;
return project;
@@ -58,7 +58,7 @@ async function getProjectWithEditAccess(projectId: string, userId: string) {
if (!project) return null;
const access = await checkProjectAccess(project, userId, { intent: 'manage' });
const access = await checkProjectAccess(project, userId);
if (!access.canEdit) return null;
return project;
+1 -1
View File
@@ -83,7 +83,7 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
return apiErrors.notFound('Project');
}
const access = await checkProjectAccess(project, session.user.id, { intent: 'manage' });
const access = await checkProjectAccess(project, session.user.id);
if (!access.canEdit) {
return apiErrors.forbidden('Access denied');
}
+5 -12
View File
@@ -42,22 +42,15 @@ export async function GET(request: NextRequest) {
return apiErrors.badRequest('Invalid page range. Offset must be 10000 or less.');
}
// Build base filter: user is owner OR a member
// Build base filter: user is the project owner, a project member, or a member of the
// workspace the project lives in. The third branch used to be dropped whenever a
// workspaceId was supplied, so filtering by their own workspace showed a workspace
// member an empty list while the unfiltered call returned the same project.
const baseFilter: Record<string, unknown> = {
OR: [
{ ownerId: session.user.id },
{ members: { some: { userId: session.user.id } } },
// Also include projects in workspaces where the user is a workspace member
...(workspaceId
? []
: [
{
workspace: {
owner: buildBillingAccessWhereInput(),
members: { some: { userId: session.user.id } },
},
},
]),
{ workspace: { members: { some: { userId: session.user.id } } } },
],
workspace: {
owner: buildBillingAccessWhereInput(),
+10 -1
View File
@@ -2,6 +2,7 @@ import { NextRequest } from 'next/server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
import { apiErrors, successResponse } from '@/lib/api-response';
import { buildBillingAccessWhereInput } from '@/lib/billing';
import { checkRateLimit, rateLimitHeaders, RATE_LIMIT_CONFIGS } from '@/lib/rate-limit';
import { logError } from '@/lib/logger';
@@ -38,8 +39,15 @@ export async function GET(request: NextRequest) {
return apiErrors.badRequest('Query too long.');
}
// Access filter reused across queries
// Access filter reused across queries. The billing condition is the same one every
// other read path carries (GET /api/projects, checkProjectAccess): without it search
// kept returning project names, descriptions and video titles for a tenant whose
// access had otherwise been cut off, which is a lapsed-tenant surface no other read
// path leaves open.
const ownerWithBillingAccess = buildBillingAccessWhereInput();
const projectAccessFilter = {
workspace: { owner: ownerWithBillingAccess },
OR: [
{ ownerId: userId },
{ members: { some: { userId } } },
@@ -48,6 +56,7 @@ export async function GET(request: NextRequest) {
};
const workspaceAccessFilter = {
owner: ownerWithBillingAccess,
OR: [{ ownerId: userId }, { members: { some: { userId } } }],
};
@@ -84,9 +84,7 @@ export async function POST(request: NextRequest, { params }: RouteParams) {
});
if (!version) return apiErrors.notFound('Version');
const access = await checkProjectAccess(version.video.project, session.user.id, {
intent: 'manage',
});
const access = await checkProjectAccess(version.video.project, session.user.id);
if (!access.canEdit) return apiErrors.forbidden('Access denied');
const body = (await request.json().catch(() => ({}))) as {
@@ -308,6 +308,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
const canDownloadViaShareLink = shareAccess.hasAccess && shareAccess.canDownload;
const canDownloadViaMembership = canDownloadProjectMedia(version.video.project, access);
if (!canDownloadViaMembership && !canDownloadViaShareLink) {
// A caller with no relationship to the project at all is told the version does not
// exist, matching the comment export route: answering 403 for an id belonging to
// another tenant confirms that the id exists. Anyone who does have a relationship,
// including an owner whose billing has lapsed, already knows it exists and gets the
// more informative 403.
const belongsToProject = access.isOwner || access.isProjectMember || access.isWorkspaceMember;
if (!belongsToProject && !shareAccess.hasAccess) {
return apiErrors.notFound('Version');
}
return apiErrors.forbidden('Access denied');
}
@@ -84,7 +84,15 @@ export async function GET(request: NextRequest, { params }: RouteParams) {
const { videoId, assetId } = await params;
const context = await getVideoAssetAccessContext(request, videoId, 'VIEW');
if (!context) return apiErrors.notFound('Video');
if (!context.hasViewAccess) return apiErrors.forbidden('Access denied');
// A caller with no relationship to the project is told the video does not exist.
// Answering 403 for an id belonging to another tenant confirms that the id exists,
// and the comment export route already answers 404 for the identical shape. Somebody
// who does belong, including an owner whose billing lapsed, gets the 403.
if (!context.hasViewAccess) {
return context.viewerBelongsToProject
? apiErrors.forbidden('Access denied')
: apiErrors.notFound('Video');
}
if (!context.canDownloadAssets) {
return apiErrors.forbidden('Downloads are disabled for this project');
}