Add Dockerfile and standalone output config

This commit is contained in:
Zebratic committed 2026-03-14 04:25:48 +00:00
1 parent d8244c9fd6
commit 0d1dd5821a
36 files changed
+2208 -5

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
# MongoDB
MONGODB_URI=mongodb://localhost:27017/apk-forge
# Auth
NEXTAUTH_SECRET=random-secret-here-min-32-chars
# LLM
LLM_API_KEY=sk-xxx
LLM_API_URL=https://llm.molberg.cloud/v1
LLM_MODEL=claude-sonnet-4-6
# Stripe (placeholder)
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_PUBLISHABLE_KEY=pk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
STRIPE_PRICE_PRO=price_xxx
STRIPE_PRICE_UNLIMITED=price_xxx
# App
NEXT_PUBLIC_APP_URL=http://localhost:3000
+3 -4
View File
@@ -1,5 +1,3 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
@@ -30,8 +28,9 @@ yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# env files
.env
.env*.local
# vercel
.vercel
+47
View File
@@ -0,0 +1,47 @@
FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ARG MONGODB_URI
ARG NEXTAUTH_SECRET
ARG LLM_API_KEY
ARG LLM_API_URL
ARG LLM_MODEL
ARG NEXT_PUBLIC_APP_URL
ARG STRIPE_SECRET_KEY
ARG STRIPE_PUBLISHABLE_KEY
ARG STRIPE_WEBHOOK_SECRET
ARG STRIPE_PRICE_PRO
ARG STRIPE_PRICE_UNLIMITED
ENV MONGODB_URI=$MONGODB_URI
ENV NEXTAUTH_SECRET=$NEXTAUTH_SECRET
ENV LLM_API_KEY=$LLM_API_KEY
ENV LLM_API_URL=$LLM_API_URL
ENV LLM_MODEL=$LLM_MODEL
ENV NEXT_PUBLIC_APP_URL=$NEXT_PUBLIC_APP_URL
RUN npm run build
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]
+1 -1
View File
@@ -1,7 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
};
export default nextConfig;
+33
View File
@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin, updateUser } from "@/lib/auth";
import { PlanTier } from "@/types";
export async function PATCH(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const { id } = await params;
const body = await req.json();
// Only allow updating plan and role
const allowedFields: Record<string, unknown> = {};
if (body.plan && ["free", "pro", "unlimited"].includes(body.plan)) {
allowedFields.plan = body.plan as PlanTier;
}
if (body.role && ["user", "admin"].includes(body.role)) {
allowedFields.role = body.role;
}
if (Object.keys(allowedFields).length === 0) {
return NextResponse.json({ error: "No valid fields to update" }, { status: 400 });
}
await updateUser(id, allowedFields);
return NextResponse.json({ success: true });
}
+40
View File
@@ -0,0 +1,40 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/auth";
import { getDb } from "@/lib/db";
export async function GET(req: NextRequest) {
try {
await requireAdmin();
} catch {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const url = new URL(req.url);
const page = parseInt(url.searchParams.get("page") || "1");
const pageSize = parseInt(url.searchParams.get("pageSize") || "50");
const search = url.searchParams.get("search") || "";
const db = await getDb();
const filter = search
? {
$or: [
{ username: { $regex: search, $options: "i" } },
{ email: { $regex: search, $options: "i" } },
],
}
: {};
const [users, total] = await Promise.all([
db
.collection("users")
.find(filter)
.project({ passwordHash: 0, emailVerificationToken: 0, passwordResetToken: 0 })
.sort({ createdAt: -1 })
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray(),
db.collection("users").countDocuments(filter),
]);
return NextResponse.json({ users, total, page, pageSize });
}
+50
View File
@@ -0,0 +1,50 @@
import { NextRequest, NextResponse } from "next/server";
import { getSession, findUserById, verifyPassword, hashPassword, updateUser } from "@/lib/auth";
export async function POST(req: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { currentPassword, newPassword } = await req.json();
if (!currentPassword || !newPassword) {
return NextResponse.json(
{ error: "Current password and new password are required" },
{ status: 400 }
);
}
if (newPassword.length < 8) {
return NextResponse.json(
{ error: "New password must be at least 8 characters" },
{ status: 400 }
);
}
const user = await findUserById(session.userId);
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
const valid = await verifyPassword(currentPassword, user.passwordHash);
if (!valid) {
return NextResponse.json(
{ error: "Current password is incorrect" },
{ status: 401 }
);
}
const newHash = await hashPassword(newPassword);
await updateUser(session.userId, { passwordHash: newHash });
return NextResponse.json({ success: true });
} catch {
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
+61
View File
@@ -0,0 +1,61 @@
import { NextRequest, NextResponse } from "next/server";
import { findUserByUsername, findUserByEmail, verifyPassword, createToken } from "@/lib/auth";
export async function POST(req: NextRequest) {
try {
const { login, password } = await req.json();
if (!login || !password) {
return NextResponse.json(
{ error: "Username/email and password are required" },
{ status: 400 }
);
}
// Allow login by username or email
const user =
(await findUserByUsername(login)) || (await findUserByEmail(login));
if (!user) {
return NextResponse.json(
{ error: "Invalid credentials" },
{ status: 401 }
);
}
const valid = await verifyPassword(password, user.passwordHash);
if (!valid) {
return NextResponse.json(
{ error: "Invalid credentials" },
{ status: 401 }
);
}
const token = createToken(user);
const response = NextResponse.json({
success: true,
user: {
username: user.username,
email: user.email,
plan: user.plan,
role: user.role,
},
});
response.cookies.set("auth-token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 7,
path: "/",
});
return response;
} catch {
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
export async function POST() {
const response = NextResponse.json({ success: true });
response.cookies.set("auth-token", "", {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 0,
path: "/",
});
return response;
}
+27
View File
@@ -0,0 +1,27 @@
import { NextResponse } from "next/server";
import { getSession, findUserById } from "@/lib/auth";
export async function GET() {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Not authenticated" }, { status: 401 });
}
const user = await findUserById(session.userId);
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
return NextResponse.json({
user: {
id: user._id!.toString(),
username: user.username,
email: user.email,
role: user.role,
plan: user.plan,
emailVerified: user.emailVerified,
usage: user.usage,
createdAt: user.createdAt,
},
});
}
+88
View File
@@ -0,0 +1,88 @@
import { NextRequest, NextResponse } from "next/server";
import { createUser, findUserByUsername, findUserByEmail, createToken } from "@/lib/auth";
export async function POST(req: NextRequest) {
try {
const { username, email, password } = await req.json();
if (!username || !email || !password) {
return NextResponse.json(
{ error: "Username, email, and password are required" },
{ status: 400 }
);
}
if (username.length < 3 || username.length > 30) {
return NextResponse.json(
{ error: "Username must be 3-30 characters" },
{ status: 400 }
);
}
if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
return NextResponse.json(
{ error: "Username can only contain letters, numbers, hyphens, and underscores" },
{ status: 400 }
);
}
if (password.length < 8) {
return NextResponse.json(
{ error: "Password must be at least 8 characters" },
{ status: 400 }
);
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
return NextResponse.json(
{ error: "Invalid email address" },
{ status: 400 }
);
}
// Check existing user
const existingUsername = await findUserByUsername(username);
if (existingUsername) {
return NextResponse.json(
{ error: "Username already taken" },
{ status: 409 }
);
}
const existingEmail = await findUserByEmail(email);
if (existingEmail) {
return NextResponse.json(
{ error: "Email already registered" },
{ status: 409 }
);
}
const user = await createUser(username, email, password);
const token = createToken(user);
const response = NextResponse.json({
success: true,
user: {
username: user.username,
email: user.email,
plan: user.plan,
},
});
response.cookies.set("auth-token", token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24 * 7,
path: "/",
});
return response;
} catch (err) {
console.error("Registration error:", err);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
+78
View File
@@ -0,0 +1,78 @@
import { NextRequest, NextResponse } from "next/server";
import { findUserByEmail, updateUser, hashPassword, generateToken } from "@/lib/auth";
// POST /api/auth/reset-password — request a password reset
export async function POST(req: NextRequest) {
try {
const { email, token, newPassword } = await req.json();
// Step 1: Request reset (only email provided)
if (email && !token && !newPassword) {
const user = await findUserByEmail(email);
if (!user) {
// Don't reveal whether email exists
return NextResponse.json({
success: true,
message: "If an account exists with that email, a reset link has been sent.",
});
}
const resetToken = generateToken();
const expires = new Date(Date.now() + 60 * 60 * 1000); // 1 hour
await updateUser(user._id!.toString(), {
passwordResetToken: resetToken,
passwordResetExpires: expires,
});
// TODO: Send email with reset link containing the token
// For now, log it (in production, wire up email service)
console.log(`[Password Reset] Token for ${email}: ${resetToken}`);
return NextResponse.json({
success: true,
message: "If an account exists with that email, a reset link has been sent.",
});
}
// Step 2: Complete reset (token + newPassword provided)
if (token && newPassword) {
if (newPassword.length < 8) {
return NextResponse.json(
{ error: "Password must be at least 8 characters" },
{ status: 400 }
);
}
const { getDb } = await import("@/lib/db");
const db = await getDb();
const user = await db.collection("users").findOne({
passwordResetToken: token,
passwordResetExpires: { $gt: new Date() },
});
if (!user) {
return NextResponse.json(
{ error: "Invalid or expired reset token" },
{ status: 400 }
);
}
const newHash = await hashPassword(newPassword);
await updateUser(user._id.toString(), {
passwordHash: newHash,
passwordResetToken: undefined,
passwordResetExpires: undefined,
});
return NextResponse.json({ success: true, message: "Password has been reset." });
}
return NextResponse.json({ error: "Invalid request" }, { status: 400 });
} catch {
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
+37
View File
@@ -0,0 +1,37 @@
import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";
import { updateUser } from "@/lib/auth";
export async function POST(req: NextRequest) {
try {
const { token } = await req.json();
if (!token) {
return NextResponse.json({ error: "Token is required" }, { status: 400 });
}
const db = await getDb();
const user = await db.collection("users").findOne({
emailVerificationToken: token,
});
if (!user) {
return NextResponse.json(
{ error: "Invalid verification token" },
{ status: 400 }
);
}
await updateUser(user._id.toString(), {
emailVerified: true,
emailVerificationToken: undefined,
});
return NextResponse.json({ success: true, message: "Email verified successfully." });
} catch {
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
+171
View File
@@ -0,0 +1,171 @@
import { NextRequest, NextResponse } from "next/server";
import { getSession, incrementUsage, checkBuildLimit } from "@/lib/auth";
import { checkRateLimit } from "@/lib/rate-limit";
import { getDb } from "@/lib/db";
import { callLLM } from "@/lib/llm";
import { ObjectId } from "mongodb";
import { ChatMessage } from "@/types";
export async function POST(req: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
// Rate limit check
const rateCheck = await checkRateLimit(session.userId, session.plan);
if (!rateCheck.allowed) {
return NextResponse.json(
{
error: "Rate limit exceeded. Please wait before sending more messages.",
resetAt: rateCheck.resetAt,
},
{
status: 429,
headers: {
"Retry-After": Math.ceil(
(rateCheck.resetAt.getTime() - Date.now()) / 1000
).toString(),
"X-RateLimit-Remaining": "0",
},
}
);
}
const { projectId, message, questionAnswers } = await req.json();
if (!projectId || !message) {
return NextResponse.json(
{ error: "Project ID and message are required" },
{ status: 400 }
);
}
const db = await getDb();
const project = await db.collection("projects").findOne({
_id: new ObjectId(projectId),
userId: session.userId,
});
if (!project) {
return NextResponse.json({ error: "Project not found" }, { status: 404 });
}
const isFirstMessage = project.messages.length === 0;
// Build conversation history for LLM context
const conversationHistory = project.messages.slice(-20).map((m: ChatMessage) => ({
role: m.role as "user" | "assistant",
content: m.role === "assistant"
? JSON.stringify({
message: m.content,
files: m.files || [],
questions: m.questions || [],
buildReady: m.buildReady || false,
})
: m.content,
}));
// If the user is answering questions, format the message
let userMessage = message;
if (questionAnswers && Object.keys(questionAnswers).length > 0) {
userMessage = `${message}\n\nAnswers to your questions:\n${Object.entries(questionAnswers)
.map(([key, val]) => `- ${key}: ${val}`)
.join("\n")}`;
}
// Call LLM
const aiResponse = await callLLM(userMessage, conversationHistory, {
currentFiles: project.currentFiles || {},
isFirstMessage,
projectName: project.name,
});
// Track usage
await incrementUsage(session.userId, "totalPrompts");
// If build is ready, check limits and increment
if (aiResponse.buildReady) {
const buildCheck = await checkBuildLimit(session.userId);
if (!buildCheck.allowed) {
aiResponse.buildReady = false;
aiResponse.message += "\n\n⚠️ You've reached your monthly build limit. Upgrade your plan to build more APKs.";
} else {
await incrementUsage(session.userId, "buildsThisMonth");
await incrementUsage(session.userId, "totalBuilds");
}
}
// Update project files
const updatedFiles = { ...(project.currentFiles || {}) };
if (aiResponse.files) {
for (const file of aiResponse.files) {
if (file.action === "deleted") {
delete updatedFiles[file.path];
} else {
updatedFiles[file.path] = file.content;
}
}
}
// Create snapshot if files changed
if (aiResponse.files && aiResponse.files.length > 0) {
await db.collection("snapshots").insertOne({
projectId: projectId,
files: updatedFiles,
prompt: userMessage,
message: aiResponse.message,
timestamp: new Date(),
});
}
// Create chat messages
const userMsg: ChatMessage = {
id: new ObjectId().toString(),
role: "user",
content: userMessage,
timestamp: new Date(),
};
const assistantMsg: ChatMessage = {
id: new ObjectId().toString(),
role: "assistant",
content: aiResponse.message,
files: aiResponse.files,
questions: aiResponse.questions,
buildReady: aiResponse.buildReady,
timestamp: new Date(),
};
// Update project name if first message
const updateSet: Record<string, unknown> = {
currentFiles: updatedFiles,
updatedAt: new Date(),
};
if (isFirstMessage) {
updateSet.name = message.slice(0, 60);
updateSet.description = message.slice(0, 200);
}
await db.collection("projects").updateOne(
{ _id: new ObjectId(projectId) },
{
$push: { messages: { $each: [userMsg, assistantMsg] } } as Record<string, unknown>,
$set: updateSet,
}
);
return NextResponse.json({
message: assistantMsg,
buildReady: aiResponse.buildReady,
remainingBuilds: (await checkBuildLimit(session.userId)).remaining,
});
} catch (err) {
console.error("Chat error:", err);
return NextResponse.json(
{ error: "Failed to process message" },
{ status: 500 }
);
}
}
+60
View File
@@ -0,0 +1,60 @@
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { ObjectId } from "mongodb";
export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
const { snapshotId } = await req.json();
const db = await getDb();
// Verify project ownership
const project = await db.collection("projects").findOne({
_id: new ObjectId(id),
userId: session.userId,
});
if (!project) {
return NextResponse.json({ error: "Project not found" }, { status: 404 });
}
// Find the snapshot
const snapshot = await db.collection("snapshots").findOne({
_id: new ObjectId(snapshotId),
projectId: id,
});
if (!snapshot) {
return NextResponse.json({ error: "Snapshot not found" }, { status: 404 });
}
// Restore files from snapshot
await db.collection("projects").updateOne(
{ _id: new ObjectId(id) },
{
$set: {
currentFiles: snapshot.files,
updatedAt: new Date(),
},
$push: {
messages: {
id: new ObjectId().toString(),
role: "assistant",
content: `⏪ Reverted to snapshot from ${new Date(snapshot.timestamp).toLocaleString()}. The project has been restored to the state after: "${snapshot.prompt}"`,
timestamp: new Date(),
},
} as Record<string, unknown>,
}
);
return NextResponse.json({ success: true, files: snapshot.files });
}
+67
View File
@@ -0,0 +1,67 @@
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { ObjectId } from "mongodb";
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
const db = await getDb();
const project = await db
.collection("projects")
.findOne({ _id: new ObjectId(id), userId: session.userId });
if (!project) {
return NextResponse.json({ error: "Project not found" }, { status: 404 });
}
return NextResponse.json({ project });
}
export async function PATCH(
req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
const { name } = await req.json();
const db = await getDb();
await db.collection("projects").updateOne(
{ _id: new ObjectId(id), userId: session.userId },
{ $set: { name, updatedAt: new Date() } }
);
return NextResponse.json({ success: true });
}
export async function DELETE(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
const db = await getDb();
await db.collection("projects").deleteOne({
_id: new ObjectId(id),
userId: session.userId,
});
await db.collection("snapshots").deleteMany({ projectId: id });
return NextResponse.json({ success: true });
}
@@ -0,0 +1,36 @@
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { ObjectId } from "mongodb";
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { id } = await params;
// Verify project ownership
const db = await getDb();
const project = await db.collection("projects").findOne({
_id: new ObjectId(id),
userId: session.userId,
});
if (!project) {
return NextResponse.json({ error: "Project not found" }, { status: 404 });
}
const snapshots = await db
.collection("snapshots")
.find({ projectId: id })
.sort({ timestamp: -1 })
.project({ _id: 1, prompt: 1, message: 1, timestamp: 1 })
.toArray();
return NextResponse.json({ snapshots });
}
+62
View File
@@ -0,0 +1,62 @@
import { NextRequest, NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
export async function GET() {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const db = await getDb();
const projects = await db
.collection("projects")
.find({ userId: session.userId })
.sort({ updatedAt: -1 })
.project({
_id: 1,
name: 1,
description: 1,
createdAt: 1,
updatedAt: 1,
"messages.0": { $slice: 1 },
})
.toArray();
// Add message count separately
const projectsWithCount = projects.map((p) => ({
_id: p._id,
name: p.name,
description: p.description,
createdAt: p.createdAt,
updatedAt: p.updatedAt,
}));
return NextResponse.json({ projects: projectsWithCount });
}
export async function POST(req: NextRequest) {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const { name, description } = await req.json();
const db = await getDb();
const project = {
userId: session.userId,
name: name || "New Project",
description: description || "",
messages: [],
currentFiles: {},
createdAt: new Date(),
updatedAt: new Date(),
};
const result = await db.collection("projects").insertOne(project);
return NextResponse.json({
project: { ...project, _id: result.insertedId },
});
}
+87
View File
@@ -0,0 +1,87 @@
import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";
import { PlanTier } from "@/types";
// Stripe webhook endpoint — stub for now, wire up when Stripe is configured
export async function POST(req: NextRequest) {
try {
const body = await req.text();
const signature = req.headers.get("stripe-signature");
const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
if (!webhookSecret) {
console.warn("[Stripe Webhook] No webhook secret configured");
return NextResponse.json({ received: true });
}
// TODO: Verify signature with Stripe SDK
// const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
// const event = stripe.webhooks.constructEvent(body, signature!, webhookSecret);
// For now, parse the body as JSON
const event = JSON.parse(body);
const db = await getDb();
switch (event.type) {
case "checkout.session.completed": {
const session = event.data.object;
const customerId = session.customer;
const priceId = session.line_items?.data?.[0]?.price?.id;
let plan: PlanTier = "free";
if (priceId === process.env.STRIPE_PRICE_PRO) plan = "pro";
if (priceId === process.env.STRIPE_PRICE_UNLIMITED) plan = "unlimited";
await db.collection("users").updateOne(
{ stripeCustomerId: customerId },
{
$set: {
plan,
stripeSubscriptionId: session.subscription,
updatedAt: new Date(),
},
}
);
break;
}
case "customer.subscription.updated": {
const subscription = event.data.object;
const customerId = subscription.customer;
const status = subscription.status;
if (status === "canceled" || status === "unpaid") {
await db.collection("users").updateOne(
{ stripeCustomerId: customerId },
{ $set: { plan: "free" as PlanTier, updatedAt: new Date() } }
);
}
break;
}
case "customer.subscription.deleted": {
const subscription = event.data.object;
await db.collection("users").updateOne(
{ stripeCustomerId: subscription.customer },
{
$set: {
plan: "free" as PlanTier,
stripeSubscriptionId: undefined,
updatedAt: new Date(),
},
}
);
break;
}
default:
console.log(`[Stripe Webhook] Unhandled event: ${event.type}`);
}
return NextResponse.json({ received: true });
} catch (err) {
console.error("[Stripe Webhook] Error:", err);
return NextResponse.json({ error: "Webhook error" }, { status: 400 });
}
}
+109
View File
@@ -0,0 +1,109 @@
"use client"
import * as React from "react"
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
import { cn } from "@/lib/utils"
function Avatar({
className,
size = "default",
...props
}: AvatarPrimitive.Root.Props & {
size?: "default" | "sm" | "lg"
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
className
)}
{...props}
/>
)
}
function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn(
"aspect-square size-full rounded-full object-cover",
className
)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: AvatarPrimitive.Fallback.Props) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
className
)}
{...props}
/>
)
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="avatar-badge"
className={cn(
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className
)}
{...props}
/>
)
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group"
className={cn(
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
className
)}
{...props}
/>
)
}
function AvatarGroupCount({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group-count"
className={cn(
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className
)}
{...props}
/>
)
}
export {
Avatar,
AvatarImage,
AvatarFallback,
AvatarGroup,
AvatarGroupCount,
AvatarBadge,
}
+52
View File
@@ -0,0 +1,52 @@
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary:
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive:
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
outline:
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost:
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
return useRender({
defaultTagName: "span",
props: mergeProps<"span">(
{
className: cn(badgeVariants({ variant }), className),
},
props
),
render,
state: {
slot: "badge",
variant,
},
})
}
export { Badge, badgeVariants }
+103
View File
@@ -0,0 +1,103 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
"group/card flex flex-col gap-4 overflow-hidden rounded-xl bg-card py-4 text-sm text-card-foreground ring-1 ring-foreground/10 has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:gap-3 data-[size=sm]:py-3 data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-4 group-data-[size=sm]/card:px-3 has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-4 group-data-[size=sm]/card:[.border-b]:pb-3",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn(
"text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-4 group-data-[size=sm]/card:px-3", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-4 group-data-[size=sm]/card:p-3",
className
)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
+21
View File
@@ -0,0 +1,21 @@
"use client"
import { Collapsible as CollapsiblePrimitive } from "@base-ui/react/collapsible"
function Collapsible({ ...props }: CollapsiblePrimitive.Root.Props) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({ ...props }: CollapsiblePrimitive.Trigger.Props) {
return (
<CollapsiblePrimitive.Trigger data-slot="collapsible-trigger" {...props} />
)
}
function CollapsibleContent({ ...props }: CollapsiblePrimitive.Panel.Props) {
return (
<CollapsiblePrimitive.Panel data-slot="collapsible-content" {...props} />
)
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
+157
View File
@@ -0,0 +1,157 @@
"use client"
import * as React from "react"
import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
function Dialog({ ...props }: DialogPrimitive.Root.Props) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({ ...props }: DialogPrimitive.Trigger.Props) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({ ...props }: DialogPrimitive.Portal.Props) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({ ...props }: DialogPrimitive.Close.Props) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: DialogPrimitive.Backdrop.Props) {
return (
<DialogPrimitive.Backdrop
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: DialogPrimitive.Popup.Props & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Popup
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-background p-4 text-sm ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
render={
<Button
variant="ghost"
className="absolute top-2 right-2"
size="icon-sm"
/>
}
>
<XIcon
/>
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Popup>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close render={<Button variant="outline" />}>
Close
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({ className, ...props }: DialogPrimitive.Title.Props) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-base leading-none font-medium", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: DialogPrimitive.Description.Props) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}
+20
View File
@@ -0,0 +1,20 @@
import * as React from "react"
import { Input as InputPrimitive } from "@base-ui/react/input"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<InputPrimitive
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }
+20
View File
@@ -0,0 +1,20 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Label({ className, ...props }: React.ComponentProps<"label">) {
return (
<label
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+55
View File
@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import { ScrollArea as ScrollAreaPrimitive } from "@base-ui/react/scroll-area"
import { cn } from "@/lib/utils"
function ScrollArea({
className,
children,
...props
}: ScrollAreaPrimitive.Root.Props) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: ScrollAreaPrimitive.Scrollbar.Props) {
return (
<ScrollAreaPrimitive.Scrollbar
data-slot="scroll-area-scrollbar"
data-orientation={orientation}
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",
className
)}
{...props}
>
<ScrollAreaPrimitive.Thumb
data-slot="scroll-area-thumb"
className="relative flex-1 rounded-full bg-border"
/>
</ScrollAreaPrimitive.Scrollbar>
)
}
export { ScrollArea, ScrollBar }
+25
View File
@@ -0,0 +1,25 @@
"use client"
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
...props
}: SeparatorPrimitive.Props) {
return (
<SeparatorPrimitive
data-slot="separator"
orientation={orientation}
className={cn(
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
className
)}
{...props}
/>
)
}
export { Separator }
+18
View File
@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"flex field-sizing-content min-h-16 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-base transition-colors outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Textarea }
+66
View File
@@ -0,0 +1,66 @@
"use client"
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
import { cn } from "@/lib/utils"
function TooltipProvider({
delay = 0,
...props
}: TooltipPrimitive.Provider.Props) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delay={delay}
{...props}
/>
)
}
function Tooltip({ ...props }: TooltipPrimitive.Root.Props) {
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
}
function TooltipTrigger({ ...props }: TooltipPrimitive.Trigger.Props) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
side = "top",
sideOffset = 4,
align = "center",
alignOffset = 0,
children,
...props
}: TooltipPrimitive.Popup.Props &
Pick<
TooltipPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Positioner
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
className="isolate z-50"
>
<TooltipPrimitive.Popup
data-slot="tooltip-content"
className={cn(
"z-50 inline-flex w-fit max-w-xs origin-(--transform-origin) items-center gap-1.5 rounded-md bg-foreground px-3 py-1.5 text-xs text-background has-data-[slot=kbd]:pr-1.5 data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 **:data-[slot=kbd]:relative **:data-[slot=kbd]:isolate **:data-[slot=kbd]:z-50 **:data-[slot=kbd]:rounded-sm data-[state=delayed-open]:animate-in data-[state=delayed-open]:fade-in-0 data-[state=delayed-open]:zoom-in-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="z-50 size-2.5 translate-y-[calc(-50%-2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground data-[side=bottom]:top-1 data-[side=inline-end]:top-1/2! data-[side=inline-end]:-left-1 data-[side=inline-end]:-translate-y-1/2 data-[side=inline-start]:top-1/2! data-[side=inline-start]:-right-1 data-[side=inline-start]:-translate-y-1/2 data-[side=left]:top-1/2! data-[side=left]:-right-1 data-[side=left]:-translate-y-1/2 data-[side=right]:top-1/2! data-[side=right]:-left-1 data-[side=right]:-translate-y-1/2 data-[side=top]:-bottom-2.5" />
</TooltipPrimitive.Popup>
</TooltipPrimitive.Positioner>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
+181
View File
@@ -0,0 +1,181 @@
import jwt from "jsonwebtoken";
import bcrypt from "bcryptjs";
import { cookies } from "next/headers";
import { getDb } from "./db";
import { User, UserSession, PlanTier } from "@/types";
import { ObjectId } from "mongodb";
const SECRET = process.env.NEXTAUTH_SECRET || "fallback-secret-change-me-32chars!!";
// ─── Password Helpers ───────────────────────────────────────────
export async function hashPassword(password: string): Promise<string> {
return bcrypt.hash(password, 12);
}
export async function verifyPassword(password: string, hash: string): Promise<boolean> {
return bcrypt.compare(password, hash);
}
// ─── Token Helpers ──────────────────────────────────────────────
export function createToken(user: User): string {
const payload: Omit<UserSession, "exp"> = {
userId: user._id!.toString(),
username: user.username,
email: user.email,
role: user.role,
plan: user.plan,
};
return jwt.sign(payload, SECRET, { expiresIn: "7d" });
}
export function verifyToken(token: string): UserSession | null {
try {
return jwt.verify(token, SECRET) as UserSession;
} catch {
return null;
}
}
// ─── Session Helpers ────────────────────────────────────────────
export async function getSession(): Promise<UserSession | null> {
const cookieStore = await cookies();
const token = cookieStore.get("auth-token")?.value;
if (!token) return null;
return verifyToken(token);
}
export async function requireAuth(): Promise<UserSession> {
const session = await getSession();
if (!session) throw new Error("Unauthorized");
return session;
}
export async function requireAdmin(): Promise<UserSession> {
const session = await requireAuth();
if (session.role !== "admin") throw new Error("Forbidden");
return session;
}
// ─── User CRUD ──────────────────────────────────────────────────
export async function createUser(
username: string,
email: string,
password: string
): Promise<User> {
const db = await getDb();
const passwordHash = await hashPassword(password);
const now = new Date();
const user: Omit<User, "_id"> = {
username: username.toLowerCase().trim(),
email: email.toLowerCase().trim(),
passwordHash,
role: "user",
plan: "free" as PlanTier,
emailVerified: false,
emailVerificationToken: generateToken(),
usage: {
buildsThisMonth: 0,
totalBuilds: 0,
totalPrompts: 0,
monthResetAt: getNextMonthReset(),
},
createdAt: now,
updatedAt: now,
};
const result = await db.collection<Omit<User, "_id">>("users").insertOne(user);
return { ...user, _id: result.insertedId };
}
export async function findUserByUsername(username: string): Promise<User | null> {
const db = await getDb();
return db.collection<User>("users").findOne({ username: username.toLowerCase().trim() });
}
export async function findUserByEmail(email: string): Promise<User | null> {
const db = await getDb();
return db.collection<User>("users").findOne({ email: email.toLowerCase().trim() });
}
export async function findUserById(id: string): Promise<User | null> {
const db = await getDb();
return db.collection<User>("users").findOne({ _id: new ObjectId(id) });
}
export async function updateUser(id: string, update: Partial<User>): Promise<void> {
const db = await getDb();
await db.collection("users").updateOne(
{ _id: new ObjectId(id) },
{ $set: { ...update, updatedAt: new Date() } }
);
}
// ─── Usage Tracking ─────────────────────────────────────────────
export async function incrementUsage(
userId: string,
field: "buildsThisMonth" | "totalBuilds" | "totalPrompts"
): Promise<void> {
const db = await getDb();
const user = await findUserById(userId);
if (!user) return;
// Reset monthly counter if needed
if (new Date() >= user.usage.monthResetAt) {
await db.collection("users").updateOne(
{ _id: new ObjectId(userId) },
{
$set: {
"usage.buildsThisMonth": field === "buildsThisMonth" ? 1 : 0,
"usage.monthResetAt": getNextMonthReset(),
updatedAt: new Date(),
},
$inc: {
[`usage.${field === "buildsThisMonth" ? "totalBuilds" : field}`]: 1,
},
}
);
} else {
await db.collection("users").updateOne(
{ _id: new ObjectId(userId) },
{
$inc: { [`usage.${field}`]: 1 },
$set: { updatedAt: new Date() },
}
);
}
}
export async function checkBuildLimit(userId: string): Promise<{ allowed: boolean; remaining: number }> {
const user = await findUserById(userId);
if (!user) return { allowed: false, remaining: 0 };
const { plan, usage } = user;
const limits = (await import("@/types")).PLAN_LIMITS[plan];
if (limits.buildsPerMonth === -1) return { allowed: true, remaining: -1 };
// Reset if month passed
let currentBuilds = usage.buildsThisMonth;
if (new Date() >= usage.monthResetAt) currentBuilds = 0;
const remaining = limits.buildsPerMonth - currentBuilds;
return { allowed: remaining > 0, remaining };
}
// ─── Helpers ────────────────────────────────────────────────────
function generateToken(): string {
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
let token = "";
for (let i = 0; i < 48; i++) {
token += chars[Math.floor(Math.random() * chars.length)];
}
return token;
}
function getNextMonthReset(): Date {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth() + 1, 1);
}
export { generateToken };
+39
View File
@@ -0,0 +1,39 @@
import { MongoClient, Db } from "mongodb";
const MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost:27017/apk-forge";
let cachedClient: MongoClient | null = null;
let cachedDb: Db | null = null;
export async function getDb(): Promise<Db> {
if (cachedDb) return cachedDb;
const client = new MongoClient(MONGODB_URI);
await client.connect();
const dbName = new URL(MONGODB_URI).pathname.slice(1) || "apk-forge";
cachedClient = client;
cachedDb = client.db(dbName);
// Ensure indexes
await ensureIndexes(cachedDb);
return cachedDb;
}
async function ensureIndexes(db: Db) {
try {
await db.collection("users").createIndex({ username: 1 }, { unique: true });
await db.collection("users").createIndex({ email: 1 }, { unique: true });
await db.collection("users").createIndex({ emailVerificationToken: 1 }, { sparse: true });
await db.collection("users").createIndex({ passwordResetToken: 1 }, { sparse: true });
await db.collection("projects").createIndex({ userId: 1, updatedAt: -1 });
await db.collection("snapshots").createIndex({ projectId: 1, timestamp: -1 });
await db.collection("rateLimits").createIndex({ key: 1 }, { unique: true });
await db.collection("rateLimits").createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 });
} catch {
// indexes may already exist
}
}
export { cachedClient };
+78
View File
@@ -0,0 +1,78 @@
import { AIResponse } from "@/types";
import { getSystemPrompt } from "./system-prompt";
const LLM_API_URL = process.env.LLM_API_URL || "https://llm.molberg.cloud/v1";
const LLM_API_KEY = process.env.LLM_API_KEY || "";
const LLM_MODEL = process.env.LLM_MODEL || "claude-sonnet-4-6";
interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
}
export async function callLLM(
userMessage: string,
conversationHistory: ChatMessage[],
projectContext?: {
currentFiles?: Record<string, string>;
isFirstMessage?: boolean;
projectName?: string;
}
): Promise<AIResponse> {
const systemPrompt = getSystemPrompt(projectContext);
const messages: ChatMessage[] = [
{ role: "system", content: systemPrompt },
...conversationHistory,
{ role: "user", content: userMessage },
];
const response = await fetch(`${LLM_API_URL}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${LLM_API_KEY}`,
},
body: JSON.stringify({
model: LLM_MODEL,
messages,
temperature: 0.7,
max_tokens: 16000,
}),
});
if (!response.ok) {
const errorText = await response.text();
console.error("LLM API error:", errorText);
throw new Error(`LLM API error: ${response.status}`);
}
const data = await response.json();
const content = data.choices?.[0]?.message?.content || "";
// Parse the JSON response from the LLM
try {
// Try to extract JSON from the response (handle markdown code blocks)
let jsonStr = content;
const jsonMatch = content.match(/```(?:json)?\s*([\s\S]*?)```/);
if (jsonMatch) {
jsonStr = jsonMatch[1].trim();
}
const parsed = JSON.parse(jsonStr) as AIResponse;
return {
message: parsed.message || "I processed your request.",
files: parsed.files || [],
questions: parsed.questions || [],
buildReady: parsed.buildReady || false,
};
} catch {
// If the LLM didn't return valid JSON, wrap the response
return {
message: content,
files: [],
questions: [],
buildReady: false,
};
}
}
+53
View File
@@ -0,0 +1,53 @@
import { getDb } from "./db";
import { PlanTier, PLAN_LIMITS } from "@/types";
interface RateLimitEntry {
key: string;
count: number;
expiresAt: Date;
}
// Rate limits per tier (requests per minute)
const RATE_LIMITS: Record<PlanTier, number> = {
free: 10,
pro: 30,
unlimited: 60,
};
export async function checkRateLimit(
userId: string,
plan: PlanTier
): Promise<{ allowed: boolean; remaining: number; resetAt: Date }> {
const db = await getDb();
const collection = db.collection<RateLimitEntry>("rateLimits");
const key = `ratelimit:${userId}`;
const limit = RATE_LIMITS[plan];
const windowMs = 60 * 1000;
const now = new Date();
const entry = await collection.findOne({ key });
if (!entry || entry.expiresAt <= now) {
// Create or reset window
await collection.updateOne(
{ key },
{
$set: {
count: 1,
expiresAt: new Date(now.getTime() + windowMs),
},
},
{ upsert: true }
);
return { allowed: true, remaining: limit - 1, resetAt: new Date(now.getTime() + windowMs) };
}
if (entry.count >= limit) {
return { allowed: false, remaining: 0, resetAt: entry.expiresAt };
}
await collection.updateOne({ key }, { $inc: { count: 1 } });
return { allowed: true, remaining: limit - entry.count - 1, resetAt: entry.expiresAt };
}
export { RATE_LIMITS, PLAN_LIMITS };
+93
View File
@@ -0,0 +1,93 @@
export function getSystemPrompt(projectContext?: {
currentFiles?: Record<string, string>;
isFirstMessage?: boolean;
projectName?: string;
}): string {
const fileContext = projectContext?.currentFiles
? Object.entries(projectContext.currentFiles)
.map(([path, content]) => `### ${path}\n\`\`\`\n${content}\n\`\`\``)
.join("\n\n")
: "";
return `You are APK Forge AI — an expert Android and React Native developer that builds mobile apps from natural language descriptions.
## Your Role
You help users create Android apps by generating complete, buildable React Native (Expo) project files. You respond with structured JSON that the frontend parses to show file changes and build status.
## Response Format
ALWAYS respond with valid JSON matching this exact schema:
\`\`\`json
{
"message": "A brief, friendly explanation of what you did or are asking",
"files": [
{
"path": "relative/path/to/file.tsx",
"content": "full file content here",
"action": "added|modified|deleted",
"explanation": "Brief explanation of this change"
}
],
"questions": [
{
"id": "unique_id",
"text": "Question text",
"type": "toggle|text|color|select",
"options": ["Option1", "Option2"],
"defaultValue": "default"
}
],
"buildReady": false
}
\`\`\`
## Rules
### First Message (New Project)
When the user describes an app for the first time:
1. Acknowledge their idea enthusiastically but briefly
2. Ask clarifying questions using the \`questions\` array:
- App name (type: "text")
- Dark mode preference (type: "toggle", default: yes)
- Primary color theme (type: "color")
- Offline support needed (type: "toggle")
- Any app-specific questions based on the prompt
3. Do NOT generate files yet — wait for answers
4. Set \`buildReady\` to false
### After Receiving Answers / Subsequent Messages
1. Generate a complete, working React Native (Expo) project
2. Include ALL necessary files: App.tsx, package.json, app.json, component files, etc.
3. Use the \`files\` array with every file and its full content
4. Set \`action\` correctly: "added" for new files, "modified" for changes, "deleted" for removals
5. Include brief \`explanation\` for each file change
6. Set \`buildReady\` to true when the project is complete and buildable
### Code Style
- Use TypeScript for all React Native code
- Follow Material Design 3 patterns
- Default to dark mode with a modern color scheme
- Use React Navigation for routing
- Use Expo SDK for native features
- Keep code clean, well-commented, and beginner-friendly
- Use functional components with hooks
- Proper error handling
### When Modifying Existing Projects
- Only include files that changed in the \`files\` array
- Reference the current project state (provided below) to make accurate modifications
- When removing features, carefully remove all related code without breaking other functionality
- When the user says "undo" or "revert", indicate that the system should restore the previous snapshot
### Important
- NEVER include API keys, secrets, or credentials in generated code
- Use environment variables or config files for sensitive data
- Keep explanations brief and beginner-friendly
- If the user's request is unclear, ask for clarification in the \`message\` field
- Always return valid JSON — no markdown wrapping, no explanation outside the JSON
${projectContext?.isFirstMessage ? "" : `
## Current Project State
${projectContext?.projectName ? `Project: ${projectContext.projectName}` : ""}
${fileContext ? `\n### Current Files:\n${fileContext}` : "No files generated yet."}
`}`;
}
+137
View File
@@ -0,0 +1,137 @@
import { ObjectId } from "mongodb";
// ─── Subscription & Plans ───────────────────────────────────────
export type PlanTier = "free" | "pro" | "unlimited";
export interface PlanLimits {
buildsPerMonth: number; // -1 = unlimited
models: string[];
priorityBuild: boolean;
customBranding: boolean;
}
export const PLAN_LIMITS: Record<PlanTier, PlanLimits> = {
free: {
buildsPerMonth: 3,
models: ["claude-sonnet-4-6"],
priorityBuild: false,
customBranding: false,
},
pro: {
buildsPerMonth: 50,
models: ["claude-sonnet-4-6", "gpt-4.1-mini", "claude-opus-4-6", "gpt-5-mini"],
priorityBuild: true,
customBranding: false,
},
unlimited: {
buildsPerMonth: -1,
models: ["claude-sonnet-4-6", "gpt-4.1-mini", "claude-opus-4-6", "gpt-5-mini", "gpt-5.4", "o3"],
priorityBuild: true,
customBranding: true,
},
};
export const PLAN_PRICES: Record<PlanTier, number> = {
free: 0,
pro: 9,
unlimited: 29,
};
// ─── Users ──────────────────────────────────────────────────────
export interface User {
_id?: ObjectId;
username: string;
email: string;
passwordHash: string;
role: "user" | "admin";
plan: PlanTier;
stripeCustomerId?: string;
stripeSubscriptionId?: string;
emailVerified: boolean;
emailVerificationToken?: string;
passwordResetToken?: string;
passwordResetExpires?: Date;
usage: {
buildsThisMonth: number;
totalBuilds: number;
totalPrompts: number;
monthResetAt: Date;
};
createdAt: Date;
updatedAt: Date;
}
// ─── Projects ───────────────────────────────────────────────────
export interface ProjectFile {
path: string;
content: string;
action: "added" | "modified" | "deleted";
explanation?: string;
}
export interface ClarifyingQuestion {
id: string;
text: string;
type: "toggle" | "text" | "color" | "select";
options?: string[];
defaultValue?: string;
}
export interface AIResponse {
message: string;
files?: ProjectFile[];
questions?: ClarifyingQuestion[];
buildReady?: boolean;
}
export interface ChatMessage {
id: string;
role: "user" | "assistant";
content: string;
files?: ProjectFile[];
questions?: ClarifyingQuestion[];
buildReady?: boolean;
timestamp: Date;
}
export interface Project {
_id?: ObjectId;
userId: string;
name: string;
description: string;
messages: ChatMessage[];
currentFiles: Record<string, string>;
createdAt: Date;
updatedAt: Date;
}
export interface Snapshot {
_id?: ObjectId;
projectId: string;
files: Record<string, string>;
prompt: string;
message: string;
timestamp: Date;
}
// ─── Auth Session ───────────────────────────────────────────────
export interface UserSession {
userId: string;
username: string;
email: string;
role: "user" | "admin";
plan: PlanTier;
exp: number;
}
// ─── API responses ──────────────────────────────────────────────
export interface ApiError {
error: string;
}
export interface PaginatedResponse<T> {
data: T[];
total: number;
page: number;
pageSize: number;
}