mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
feat(share): add video-level secure share links with password unlock and session-based watch/comment access
This commit is contained in:
@@ -17,6 +17,8 @@ export const RATE_LIMIT_CONFIGS: Record<string, RateLimitConfig> = {
|
||||
// Auth — strict to prevent brute force / credential stuffing
|
||||
register: { windowMs: 60 * 60 * 1000, maxRequests: 5 }, // 5 per hour
|
||||
login: { windowMs: 15 * 60 * 1000, maxRequests: 10 }, // 10 per 15 min
|
||||
'share-unlock': { windowMs: 15 * 60 * 1000, maxRequests: 20 }, // 20 per 15 min per IP
|
||||
'share-unlock-token': { windowMs: 15 * 60 * 1000, maxRequests: 8 }, // 8 per 15 min per IP+token
|
||||
|
||||
// Content creation — moderate limits
|
||||
comment: { windowMs: 60 * 1000, maxRequests: 15 }, // 15 per minute
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
import type { ShareLink, SharePermission } from '@prisma/client';
|
||||
import { db } from '@/lib/db';
|
||||
|
||||
export const MAX_SHARE_PASSWORD_LENGTH = 128;
|
||||
|
||||
interface ValidateShareLinkParams {
|
||||
token: string;
|
||||
projectId: string;
|
||||
videoId?: string;
|
||||
requiredPermission?: SharePermission;
|
||||
presentedPassword?: string;
|
||||
passwordVerified?: boolean;
|
||||
}
|
||||
|
||||
export interface ShareLinkAccessResult {
|
||||
hasAccess: boolean;
|
||||
canComment: boolean;
|
||||
allowGuests: boolean;
|
||||
requiresPassword: boolean;
|
||||
link: ShareLink | null;
|
||||
}
|
||||
|
||||
function hasRequiredPermission(
|
||||
actual: SharePermission,
|
||||
required: SharePermission
|
||||
): boolean {
|
||||
if (required === 'VIEW') return actual === 'VIEW' || actual === 'COMMENT';
|
||||
return actual === 'COMMENT';
|
||||
}
|
||||
|
||||
function isLinkExpired(link: ShareLink): boolean {
|
||||
if (!link.expiresAt) return false;
|
||||
return link.expiresAt.getTime() <= Date.now();
|
||||
}
|
||||
|
||||
export async function validateShareLinkAccess({
|
||||
token,
|
||||
projectId,
|
||||
videoId,
|
||||
requiredPermission = 'VIEW',
|
||||
presentedPassword,
|
||||
passwordVerified = false,
|
||||
}: ValidateShareLinkParams): Promise<ShareLinkAccessResult> {
|
||||
const link = await db.shareLink.findUnique({
|
||||
where: { token },
|
||||
});
|
||||
|
||||
if (!link) {
|
||||
return { hasAccess: false, canComment: false, allowGuests: false, requiresPassword: false, link: null };
|
||||
}
|
||||
|
||||
const projectMatches = link.projectId === projectId;
|
||||
// When a specific video is requested, require the link to be scoped to that exact video.
|
||||
const videoMatches = videoId === undefined ? link.videoId === null : link.videoId === videoId;
|
||||
const permissionMatches = hasRequiredPermission(link.permission, requiredPermission);
|
||||
|
||||
if (!projectMatches || !videoMatches || !permissionMatches || isLinkExpired(link)) {
|
||||
return { hasAccess: false, canComment: false, allowGuests: false, requiresPassword: false, link };
|
||||
}
|
||||
|
||||
if (link.passwordHash && !passwordVerified) {
|
||||
if (!presentedPassword) {
|
||||
return { hasAccess: false, canComment: false, allowGuests: false, requiresPassword: true, link };
|
||||
}
|
||||
|
||||
if (presentedPassword.length > MAX_SHARE_PASSWORD_LENGTH) {
|
||||
return { hasAccess: false, canComment: false, allowGuests: false, requiresPassword: true, link };
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(presentedPassword, link.passwordHash);
|
||||
if (!isPasswordValid) {
|
||||
return { hasAccess: false, canComment: false, allowGuests: false, requiresPassword: true, link };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hasAccess: true,
|
||||
canComment: link.permission === 'COMMENT',
|
||||
allowGuests: link.allowGuests,
|
||||
requiresPassword: false,
|
||||
link,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { createHmac, timingSafeEqual } from 'crypto';
|
||||
import type { NextRequest } from 'next/server';
|
||||
|
||||
const DEFAULT_SESSION_TTL_SECONDS = 60 * 60 * 24 * 14; // 14 days
|
||||
const PENDING_TTL_SECONDS = 60 * 10; // 10 minutes
|
||||
|
||||
interface ShareSessionPayload {
|
||||
token: string;
|
||||
videoId: string;
|
||||
exp: number;
|
||||
passwordVerified: boolean;
|
||||
}
|
||||
|
||||
interface PendingSharePayload {
|
||||
token: string;
|
||||
videoId: string;
|
||||
exp: number;
|
||||
}
|
||||
|
||||
function getSessionSecret(): string {
|
||||
const secret = process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET;
|
||||
if (!secret) {
|
||||
throw new Error('Missing AUTH_SECRET/NEXTAUTH_SECRET for share session signing');
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
function sign(data: string): string {
|
||||
return createHmac('sha256', getSessionSecret()).update(data).digest('base64url');
|
||||
}
|
||||
|
||||
function createSignedValue(payload: object): string {
|
||||
const encodedPayload = Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
|
||||
const signature = sign(encodedPayload);
|
||||
return `${encodedPayload}.${signature}`;
|
||||
}
|
||||
|
||||
function parseSignedValue<T>(value: string): T | null {
|
||||
const [encodedPayload, signature] = value.split('.');
|
||||
if (!encodedPayload || !signature) return null;
|
||||
|
||||
const expectedSignature = sign(encodedPayload);
|
||||
const actualBytes = Buffer.from(signature);
|
||||
const expectedBytes = Buffer.from(expectedSignature);
|
||||
if (actualBytes.length !== expectedBytes.length) return null;
|
||||
if (!timingSafeEqual(actualBytes, expectedBytes)) return null;
|
||||
|
||||
try {
|
||||
return JSON.parse(Buffer.from(encodedPayload, 'base64url').toString('utf8')) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getShareSessionCookieName(videoId: string): string {
|
||||
return `openframe_share_session_${videoId}`;
|
||||
}
|
||||
|
||||
export function getPendingShareCookieName(videoId: string): string {
|
||||
return `openframe_share_pending_${videoId}`;
|
||||
}
|
||||
|
||||
export function createShareSessionValue(
|
||||
token: string,
|
||||
videoId: string,
|
||||
passwordVerified: boolean,
|
||||
ttlSeconds = DEFAULT_SESSION_TTL_SECONDS
|
||||
): string {
|
||||
return createSignedValue({
|
||||
token,
|
||||
videoId,
|
||||
passwordVerified,
|
||||
exp: Math.floor(Date.now() / 1000) + ttlSeconds,
|
||||
} satisfies ShareSessionPayload);
|
||||
}
|
||||
|
||||
export function createPendingShareValue(token: string, videoId: string, ttlSeconds = PENDING_TTL_SECONDS): string {
|
||||
return createSignedValue({
|
||||
token,
|
||||
videoId,
|
||||
exp: Math.floor(Date.now() / 1000) + ttlSeconds,
|
||||
} satisfies PendingSharePayload);
|
||||
}
|
||||
|
||||
export function getShareSessionFromRequest(
|
||||
request: NextRequest,
|
||||
videoId: string
|
||||
): { token: string; passwordVerified: boolean } | null {
|
||||
const cookieName = getShareSessionCookieName(videoId);
|
||||
const cookieValue = request.cookies.get(cookieName)?.value;
|
||||
if (!cookieValue) return null;
|
||||
|
||||
const payload = parseSignedValue<ShareSessionPayload>(cookieValue);
|
||||
if (!payload || payload.videoId !== videoId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (payload.exp <= Math.floor(Date.now() / 1000)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { token: payload.token, passwordVerified: payload.passwordVerified };
|
||||
}
|
||||
|
||||
export function getPendingShareTokenFromRequest(request: NextRequest, videoId: string): string | null {
|
||||
const cookieName = getPendingShareCookieName(videoId);
|
||||
const cookieValue = request.cookies.get(cookieName)?.value;
|
||||
if (!cookieValue) return null;
|
||||
|
||||
const payload = parseSignedValue<PendingSharePayload>(cookieValue);
|
||||
if (!payload || payload.videoId !== videoId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (payload.exp <= Math.floor(Date.now() / 1000)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return payload.token;
|
||||
}
|
||||
|
||||
export const shareSessionCookieConfig = {
|
||||
maxAge: DEFAULT_SESSION_TTL_SECONDS,
|
||||
} as const;
|
||||
|
||||
export const pendingShareCookieConfig = {
|
||||
maxAge: PENDING_TTL_SECONDS,
|
||||
} as const;
|
||||
Reference in New Issue
Block a user