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.
206 lines
6.6 KiB
TypeScript
206 lines
6.6 KiB
TypeScript
import type { NextRequest } from 'next/server';
|
|
import type { VideoAsset } from '@prisma/client';
|
|
import { auth, checkProjectAccess } from '@/lib/auth';
|
|
import { db } from '@/lib/db';
|
|
import { getGuestIdentityFromRequest } from '@/lib/guest-identity';
|
|
import { getShareSessionFromRequest } from '@/lib/share-session';
|
|
import { validateShareLinkAccess } from '@/lib/share-links';
|
|
import { canDownloadProjectMedia } from '@/lib/project-download';
|
|
|
|
const IMAGE_PROXY_PREFIX = '/api/upload/image/';
|
|
const AUDIO_PROXY_PREFIX = '/api/upload/audio/';
|
|
const VIDEO_PROXY_PREFIX = '/api/upload/video/';
|
|
|
|
export const SAFE_IMAGE_PROXY_PATH =
|
|
/^\/api\/upload\/image\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/i;
|
|
export const SAFE_AUDIO_PROXY_PATH =
|
|
/^\/api\/upload\/audio\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/i;
|
|
export const SAFE_VIDEO_PROXY_PATH =
|
|
/^\/api\/upload\/video\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.[a-z0-9]+$/i;
|
|
export const SAFE_BUNNY_VIDEO_ID = /^[A-Za-z0-9_-]{8,128}$/;
|
|
|
|
export type VideoAssetAccessContext = {
|
|
video: {
|
|
id: string;
|
|
title: string;
|
|
projectId: string;
|
|
project: {
|
|
id: string;
|
|
name: string;
|
|
ownerId: string;
|
|
workspaceId: string;
|
|
visibility: string;
|
|
allowDownloads: boolean;
|
|
workspace: {
|
|
id: string;
|
|
ownerId: string;
|
|
};
|
|
};
|
|
};
|
|
hasViewAccess: boolean;
|
|
/**
|
|
* Whether the viewer has any relationship to the project: owner, project member,
|
|
* workspace member, or a valid share link. Distinguishes "you may not" from "there is
|
|
* no such thing", so a route can answer 404 for another tenant's id without answering
|
|
* 404 to somebody whose access merely lapsed.
|
|
*/
|
|
viewerBelongsToProject: boolean;
|
|
canUploadAssets: boolean;
|
|
canDownloadAssets: boolean;
|
|
canManageAssets: boolean;
|
|
viewerUserId: string | null;
|
|
viewerGuestIdentityId: string | null;
|
|
};
|
|
|
|
export function sanitizeAssetDisplayName(
|
|
value: string | null | undefined,
|
|
fallback: string
|
|
): string {
|
|
const raw = typeof value === 'string' ? value : '';
|
|
const normalized = raw
|
|
.replace(/[\u0000-\u001F\u007F]/g, '')
|
|
.replace(/[\[\]\(\)]/g, '')
|
|
.replace(/\s+/g, ' ')
|
|
.trim();
|
|
if (normalized.length === 0) return fallback;
|
|
return normalized.slice(0, 200);
|
|
}
|
|
|
|
export function extractImageKeyFromProxyUrl(url: string): string | null {
|
|
if (!SAFE_IMAGE_PROXY_PATH.test(url)) return null;
|
|
const filename = url.slice(IMAGE_PROXY_PREFIX.length);
|
|
if (!filename) return null;
|
|
return `images/${filename}`;
|
|
}
|
|
|
|
export function extractImageFileNameFromProxyUrl(url: string): string | null {
|
|
if (!SAFE_IMAGE_PROXY_PATH.test(url)) return null;
|
|
const filename = url.slice(IMAGE_PROXY_PREFIX.length);
|
|
return filename || null;
|
|
}
|
|
|
|
export function extractAudioKeyFromProxyUrl(url: string): string | null {
|
|
if (!SAFE_AUDIO_PROXY_PATH.test(url)) return null;
|
|
const filename = url.slice(AUDIO_PROXY_PREFIX.length);
|
|
if (!filename) return null;
|
|
return `voice/${filename}`;
|
|
}
|
|
|
|
export function extractAudioFileNameFromProxyUrl(url: string): string | null {
|
|
if (!SAFE_AUDIO_PROXY_PATH.test(url)) return null;
|
|
const filename = url.slice(AUDIO_PROXY_PREFIX.length);
|
|
return filename || null;
|
|
}
|
|
|
|
export function extractVideoKeyFromProxyUrl(url: string): string | null {
|
|
if (!SAFE_VIDEO_PROXY_PATH.test(url)) return null;
|
|
const filename = url.slice(VIDEO_PROXY_PREFIX.length);
|
|
if (!filename) return null;
|
|
return `videos/${filename}`;
|
|
}
|
|
|
|
export function extractVideoFileNameFromProxyUrl(url: string): string | null {
|
|
if (!SAFE_VIDEO_PROXY_PATH.test(url)) return null;
|
|
const filename = url.slice(VIDEO_PROXY_PREFIX.length);
|
|
return filename || null;
|
|
}
|
|
|
|
export function canDeleteAssetForViewer(
|
|
asset: Pick<VideoAsset, 'uploadedByUserId' | 'uploadedByGuestIdentityId'>,
|
|
viewer: Pick<
|
|
VideoAssetAccessContext,
|
|
'canManageAssets' | 'viewerUserId' | 'viewerGuestIdentityId'
|
|
>
|
|
): boolean {
|
|
if (viewer.canManageAssets) return true;
|
|
if (viewer.viewerUserId && asset.uploadedByUserId === viewer.viewerUserId) return true;
|
|
if (
|
|
!viewer.viewerUserId &&
|
|
viewer.viewerGuestIdentityId &&
|
|
asset.uploadedByGuestIdentityId &&
|
|
asset.uploadedByGuestIdentityId === viewer.viewerGuestIdentityId
|
|
) {
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
export async function getVideoAssetAccessContext(
|
|
request: NextRequest,
|
|
videoId: string,
|
|
requiredPermission: 'VIEW' | 'COMMENT' = 'VIEW'
|
|
): Promise<VideoAssetAccessContext | null> {
|
|
const session = await auth();
|
|
const video = await db.video.findUnique({
|
|
where: { id: videoId },
|
|
select: {
|
|
id: true,
|
|
title: true,
|
|
projectId: true,
|
|
project: {
|
|
select: {
|
|
id: true,
|
|
name: true,
|
|
ownerId: true,
|
|
workspaceId: true,
|
|
visibility: true,
|
|
allowDownloads: true,
|
|
workspace: {
|
|
select: {
|
|
id: true,
|
|
ownerId: true,
|
|
},
|
|
},
|
|
},
|
|
},
|
|
},
|
|
});
|
|
|
|
if (!video) return null;
|
|
|
|
const access = await checkProjectAccess(video.project, session?.user?.id);
|
|
const shareSession = getShareSessionFromRequest(request, video.id);
|
|
const shareAccess = shareSession
|
|
? await validateShareLinkAccess({
|
|
token: shareSession.token,
|
|
projectId: video.projectId,
|
|
videoId: video.id,
|
|
requiredPermission,
|
|
passwordVerified: shareSession.passwordVerified,
|
|
})
|
|
: {
|
|
hasAccess: false,
|
|
canComment: false,
|
|
canDownload: false,
|
|
allowGuests: false,
|
|
requiresPassword: false,
|
|
link: null,
|
|
};
|
|
|
|
const hasViewAccess = access.hasAccess || shareAccess.hasAccess;
|
|
const canCommentWithMembership = !!session?.user?.id && access.hasAccess;
|
|
const canCommentWithShare =
|
|
shareAccess.canComment && (session?.user?.id ? true : shareAccess.allowGuests);
|
|
const canUploadAssets = canCommentWithMembership || canCommentWithShare;
|
|
const canDownloadWithMembership = canDownloadProjectMedia(video.project, access);
|
|
const canDownloadWithShare = shareAccess.hasAccess && shareAccess.canDownload;
|
|
const canDownloadAssets = hasViewAccess && (canDownloadWithMembership || canDownloadWithShare);
|
|
|
|
const viewerUserId = session?.user?.id ?? null;
|
|
const viewerGuestIdentityId = viewerUserId ? null : getGuestIdentityFromRequest(request);
|
|
|
|
const viewerBelongsToProject =
|
|
access.isOwner || access.isProjectMember || access.isWorkspaceMember || shareAccess.hasAccess;
|
|
|
|
return {
|
|
video,
|
|
hasViewAccess,
|
|
viewerBelongsToProject,
|
|
canUploadAssets,
|
|
canDownloadAssets,
|
|
canManageAssets: access.canEdit,
|
|
viewerUserId,
|
|
viewerGuestIdentityId,
|
|
};
|
|
}
|