summaryrefslogtreecommitdiff
path: root/apps/web/src/app
diff options
context:
space:
mode:
authorKhắc Tuấn <khtuankendy@gmail.com>2025-07-16 20:04:27 +0700
committerGitHub <noreply@github.com>2025-07-16 20:04:27 +0700
commit2974fd89a942f4e3173642b165f228e2af604ae7 (patch)
tree179811835f69429d6fc4b7917c8ece2615a74a3b /apps/web/src/app
parentfaf317cd20756b72974b67aaacab1ccf49ec8a86 (diff)
parent0554a031c2d8cc8d736172aeaf503d33b0764c04 (diff)
downloadopencut-2974fd89a942f4e3173642b165f228e2af604ae7.tar.gz
Merge branch 'main' into feature/optimize-timeline-ruler
Diffstat (limited to 'apps/web/src/app')
-rw-r--r--apps/web/src/app/api/waitlist/route.ts68
-rw-r--r--apps/web/src/app/api/waitlist/token/route.ts46
-rw-r--r--apps/web/src/app/contributors/page.tsx2
-rw-r--r--apps/web/src/app/editor/[project_id]/page.tsx39
-rw-r--r--apps/web/src/app/layout.tsx11
-rw-r--r--apps/web/src/app/page.tsx8
-rw-r--r--apps/web/src/app/projects/page.tsx34
7 files changed, 144 insertions, 64 deletions
diff --git a/apps/web/src/app/api/waitlist/route.ts b/apps/web/src/app/api/waitlist/route.ts
index f6f81103..f62e24e9 100644
--- a/apps/web/src/app/api/waitlist/route.ts
+++ b/apps/web/src/app/api/waitlist/route.ts
@@ -1,54 +1,77 @@
import { NextRequest, NextResponse } from "next/server";
import { db, eq } from "@opencut/db";
import { waitlist } from "@opencut/db/schema";
+import { checkBotId } from "botid/server";
import { nanoid } from "nanoid";
import { waitlistRateLimit } from "@/lib/rate-limit";
import { z } from "zod";
+import { env } from "@/env";
+import { cookies } from "next/headers";
+import crypto from "crypto";
const waitlistSchema = z.object({
email: z.string().email("Invalid email format").min(1, "Email is required"),
});
+const CSRF_TOKEN_NAME = "waitlist-csrf";
+const TOKEN_EXPIRY = 60 * 60 * 1000;
+
+async function validateCSRFToken(request: NextRequest): Promise<boolean> {
+ const clientToken = request.headers.get("x-csrf-token");
+ if (!clientToken) return false;
+
+ const cookieStore = await cookies();
+ const cookieValue = cookieStore.get(CSRF_TOKEN_NAME)?.value;
+ if (!cookieValue) return false;
+
+ const [token, timestamp, signature] = cookieValue.split(":");
+ if (!token || !timestamp || !signature) return false;
+
+ if (clientToken !== token) return false;
+
+ const now = Date.now();
+ const tokenTime = parseInt(timestamp);
+ if (now - tokenTime > TOKEN_EXPIRY) return false;
+
+ const expectedSignature = crypto.createHmac("sha256", env.BETTER_AUTH_SECRET).update(`${token}:${timestamp}`).digest("hex");
+
+ return signature === expectedSignature;
+}
+
export async function POST(request: NextRequest) {
- // Rate limit check
+ const verification = await checkBotId();
+
+ if (verification.isBot) {
+ return NextResponse.json({ error: "Access denied" }, { status: 403 });
+ }
+
const identifier = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
const { success } = await waitlistRateLimit.limit(identifier);
if (!success) {
- return NextResponse.json(
- { error: "Too many requests. Please try again later." },
- { status: 429 }
- );
+ return NextResponse.json({ error: "Too many requests. Please try again later." }, { status: 429 });
+ }
+ const isValidToken = await validateCSRFToken(request);
+ if (!isValidToken) {
+ return NextResponse.json({ error: "Invalid security token" }, { status: 403 });
}
try {
const body = await request.json();
const { email } = waitlistSchema.parse(body);
- // Check if email already exists
- const existingEmail = await db
- .select()
- .from(waitlist)
- .where(eq(waitlist.email, email.toLowerCase()))
- .limit(1);
+ const existingEmail = await db.select().from(waitlist).where(eq(waitlist.email, email.toLowerCase())).limit(1);
if (existingEmail.length > 0) {
- return NextResponse.json(
- { error: "Email already registered" },
- { status: 409 }
- );
+ return NextResponse.json({ error: "Email already registered" }, { status: 409 });
}
- // Add to waitlist
await db.insert(waitlist).values({
id: nanoid(),
email: email.toLowerCase(),
});
- return NextResponse.json(
- { message: "Successfully joined waitlist!" },
- { status: 201 }
- );
+ return NextResponse.json({ message: "Successfully joined waitlist!" }, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
const firstError = error.errors[0];
@@ -56,9 +79,6 @@ export async function POST(request: NextRequest) {
}
console.error("Waitlist signup error:", error);
- return NextResponse.json(
- { error: "Internal server error" },
- { status: 500 }
- );
+ return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
diff --git a/apps/web/src/app/api/waitlist/token/route.ts b/apps/web/src/app/api/waitlist/token/route.ts
new file mode 100644
index 00000000..4c7695fa
--- /dev/null
+++ b/apps/web/src/app/api/waitlist/token/route.ts
@@ -0,0 +1,46 @@
+import { NextRequest, NextResponse } from "next/server";
+import { cookies } from "next/headers";
+import crypto from "crypto";
+import { env } from "@/env";
+
+const CSRF_TOKEN_NAME = "waitlist-csrf";
+const TOKEN_EXPIRY = 60 * 60 * 1000;
+const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"];
+
+export async function GET(request: NextRequest) {
+ const referer = request.headers.get("referer");
+ const host = request.headers.get("host");
+
+ if (referer) {
+ const refererUrl = new URL(referer);
+
+ if (!allowedHosts.some((allowed) => refererUrl.host === allowed || refererUrl.host.endsWith(allowed))) {
+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ }
+ } else if (host) {
+ if (!allowedHosts.some((allowed) => host === allowed || host.endsWith(allowed))) {
+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ }
+ } else {
+ return NextResponse.json({ error: "Forbidden" }, { status: 403 });
+ }
+
+ if (!env.BETTER_AUTH_SECRET) {
+ throw new Error("BETTER_AUTH_SECRET must be configured");
+ }
+
+ const token = crypto.randomBytes(32).toString("hex");
+ const timestamp = Date.now();
+ const signature = crypto.createHmac("sha256", env.BETTER_AUTH_SECRET).update(`${token}:${timestamp}`).digest("hex");
+
+ const cookieStore = await cookies();
+ cookieStore.set(CSRF_TOKEN_NAME, `${token}:${timestamp}:${signature}`, {
+ httpOnly: true,
+ secure: env.NODE_ENV === "production",
+ sameSite: "strict",
+ maxAge: TOKEN_EXPIRY / 1000,
+ path: "/",
+ });
+
+ return NextResponse.json({ token });
+}
diff --git a/apps/web/src/app/contributors/page.tsx b/apps/web/src/app/contributors/page.tsx
index fcf96e11..5613f1f9 100644
--- a/apps/web/src/app/contributors/page.tsx
+++ b/apps/web/src/app/contributors/page.tsx
@@ -32,7 +32,7 @@ interface Contributor {
async function getContributors(): Promise<Contributor[]> {
try {
const response = await fetch(
- "https://api.github.com/repos/OpenCut-app/OpenCut/contributors",
+ "https://api.github.com/repos/OpenCut-app/OpenCut/contributors?per_page=100",
{
headers: {
Accept: "application/vnd.github.v3+json",
diff --git a/apps/web/src/app/editor/[project_id]/page.tsx b/apps/web/src/app/editor/[project_id]/page.tsx
index f48d032a..d9d8a08c 100644
--- a/apps/web/src/app/editor/[project_id]/page.tsx
+++ b/apps/web/src/app/editor/[project_id]/page.tsx
@@ -1,7 +1,7 @@
"use client";
-import { useEffect } from "react";
-import { useParams } from "next/navigation";
+import { useEffect, useRef } from "react";
+import { useParams, useRouter } from "next/navigation";
import {
ResizablePanelGroup,
ResizablePanel,
@@ -34,26 +34,39 @@ export default function Editor() {
const { activeProject, loadProject, createNewProject } = useProjectStore();
const params = useParams();
+ const router = useRouter();
const projectId = params.project_id as string;
+ const handledProjectIds = useRef<Set<string>>(new Set());
useDisableBrowserZoom();
usePlaybackControls();
useEffect(() => {
- const initializeProject = async () => {
- if (projectId && (!activeProject || activeProject.id !== projectId)) {
- try {
- await loadProject(projectId);
- } catch (error) {
- console.error("Failed to load project:", error);
- // If project doesn't exist, create a new one
- await createNewProject("Untitled Project");
- }
+ const initProject = async () => {
+
+ if (!projectId) return;
+
+ if (activeProject?.id === projectId) {
+ return;
+ }
+
+ if (handledProjectIds.current.has(projectId)) {
+ return;
+ }
+
+ try {
+ await loadProject(projectId);
+ } catch (error) {
+ handledProjectIds.current.add(projectId);
+
+ const newProjectId = await createNewProject("Untitled Project");
+ router.replace(`/editor/${newProjectId}`);
+ return;
}
};
- initializeProject();
- }, [projectId, activeProject, loadProject, createNewProject]);
+ initProject();
+ }, [projectId, activeProject?.id, loadProject, createNewProject, router]);
return (
<EditorProvider>
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
index 9ac54262..1cbc3f2e 100644
--- a/apps/web/src/app/layout.tsx
+++ b/apps/web/src/app/layout.tsx
@@ -7,9 +7,17 @@ import { TooltipProvider } from "../components/ui/tooltip";
import { StorageProvider } from "../components/storage-provider";
import { baseMetaData } from "./metadata";
import { defaultFont } from "../lib/font-config";
+import { BotIdClient } from "botid/client";
export const metadata = baseMetaData;
+const protectedRoutes = [
+ {
+ path: "/api/waitlist",
+ method: "POST",
+ },
+];
+
export default function RootLayout({
children,
}: Readonly<{
@@ -17,6 +25,9 @@ export default function RootLayout({
}>) {
return (
<html lang="en" suppressHydrationWarning>
+ <head>
+ <BotIdClient protect={protectedRoutes} />
+ </head>
<body className={`${defaultFont.className} font-sans antialiased`}>
<ThemeProvider attribute="class" forcedTheme="dark">
<TooltipProvider>
diff --git a/apps/web/src/app/page.tsx b/apps/web/src/app/page.tsx
index 74308470..74961549 100644
--- a/apps/web/src/app/page.tsx
+++ b/apps/web/src/app/page.tsx
@@ -1,18 +1,12 @@
import { Hero } from "@/components/landing/hero";
import { Header } from "@/components/header";
import { Footer } from "@/components/footer";
-import { getWaitlistCount } from "@/lib/waitlist";
-
-// Force dynamic rendering so waitlist count updates in real-time
-export const dynamic = "force-dynamic";
export default async function Home() {
- const signupCount = await getWaitlistCount();
-
return (
<div>
<Header />
- <Hero signupCount={signupCount} />
+ <Hero />
<Footer />
</div>
);
diff --git a/apps/web/src/app/projects/page.tsx b/apps/web/src/app/projects/page.tsx
index 94defe1e..499b999a 100644
--- a/apps/web/src/app/projects/page.tsx
+++ b/apps/web/src/app/projects/page.tsx
@@ -173,28 +173,24 @@ export default function ProjectsPage() {
</div>
{isSelectionMode && savedProjects.length > 0 && (
- <div className="mb-6 p-4 bg-muted/30 rounded-lg border">
+ <div
+ className="mb-6 p-4 bg-muted/30 rounded-lg border cursor-pointer hover:bg-muted/40 transition-colors"
+ onClick={() => handleSelectAll(!allSelected)}
+ >
<div className="flex items-center gap-3">
<Checkbox
checked={allSelected}
- ref={(el) => {
- if (el) {
- const checkboxElement = el.querySelector(
- "input"
- ) as HTMLInputElement;
- if (checkboxElement) {
- checkboxElement.indeterminate = someSelected;
- }
- }
- }}
onCheckedChange={handleSelectAll}
+ onClick={(e) => e.stopPropagation()}
/>
- <span className="text-sm font-medium">
- {allSelected ? "Deselect All" : "Select All"}
- </span>
- <span className="text-sm text-muted-foreground">
- ({selectedProjects.size} of {savedProjects.length} selected)
- </span>
+ <div className="flex-1 flex items-center justify-start gap-2">
+ <span className="text-sm font-medium">
+ {allSelected ? "Deselect All" : "Select All"}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ ({selectedProjects.size} of {savedProjects.length} selected)
+ </span>
+ </div>
</div>
</div>
)}
@@ -296,7 +292,7 @@ function ProjectCard({
{/* Selection checkbox */}
{isSelectionMode && (
<div className="absolute top-3 left-3 z-10">
- <div className="w-5 h-5 rounded bg-background/80 backdrop-blur-sm border flex items-center justify-center">
+ <div className="w-5 h-5 rounded-full bg-background/80 backdrop-blur-sm border flex items-center justify-center">
<Checkbox
checked={isSelected}
onCheckedChange={(checked) =>
@@ -326,7 +322,7 @@ function ProjectCard({
</div>
</div>
- <CardContent className="px-0 pt-5 flex flex-col gap-1">
+ <CardContent className="px-0 pt-5 flex flex-col gap-1 p-2">
<div className="flex items-start justify-between">
<h3 className="font-medium text-sm leading-snug group-hover:text-foreground/90 transition-colors line-clamp-2">
{project.name}