feat: phase 0 skeleton — next.js 16 + better-auth + prisma

This commit is contained in:
Semih
2026-05-13 09:17:50 +00:00
commit 67a7c5b887
26 changed files with 1254 additions and 0 deletions

43
apps/web/Dockerfile Normal file
View File

@@ -0,0 +1,43 @@
FROM node:22-alpine AS base
RUN apk add --no-cache libc6-compat openssl
WORKDIR /app
RUN corepack enable && corepack prepare pnpm@9.12.0 --activate
# ---- deps ----
FROM base AS deps
COPY package.json pnpm-lock.yaml* pnpm-workspace.yaml ./
COPY apps/web/package.json apps/web/package.json
RUN pnpm install --frozen-lockfile || pnpm install
# ---- builder ----
FROM base AS builder
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
COPY --from=deps /app/apps/web/node_modules ./apps/web/node_modules
COPY . .
WORKDIR /app/apps/web
RUN pnpm prisma generate
RUN pnpm build
# ---- runner ----
FROM base AS runner
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
WORKDIR /app
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 nextjs
COPY --from=builder /app/apps/web/public ./apps/web/public
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/prisma ./apps/web/prisma
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/node_modules/.prisma ./apps/web/node_modules/.prisma
COPY --from=builder --chown=nextjs:nodejs /app/apps/web/node_modules/@prisma ./apps/web/node_modules/@prisma
COPY --from=builder --chown=nextjs:nodejs /app/node_modules/prisma ./node_modules/prisma
COPY apps/web/docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
USER nextjs
EXPOSE 3000
ENV PORT=3000 HOSTNAME=0.0.0.0
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["node", "apps/web/server.js"]

View File

@@ -0,0 +1,6 @@
#!/bin/sh
set -e
cd /app/apps/web
npx prisma db push --accept-data-loss --skip-generate || echo "prisma db push skipped/failed (continuing)"
cd /app
exec "$@"

21
apps/web/middleware.ts Normal file
View File

@@ -0,0 +1,21 @@
import { NextResponse, type NextRequest } from "next/server";
const PUBLIC = new Set(["/login", "/setup-2fa"]);
export function middleware(req: NextRequest) {
const { pathname } = req.nextUrl;
if (pathname.startsWith("/api/auth") || PUBLIC.has(pathname) || pathname === "/_next" || pathname.startsWith("/_next")) {
return NextResponse.next();
}
const hasSession = req.cookies.get("sp.session_token") || req.cookies.get("sp.session_token.sig");
if (!hasSession && pathname === "/") {
const url = req.nextUrl.clone();
url.pathname = "/login";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|api/health).*)"],
};

11
apps/web/next.config.ts Normal file
View File

@@ -0,0 +1,11 @@
import type { NextConfig } from "next";
const config: NextConfig = {
output: "standalone",
reactStrictMode: true,
experimental: {
serverActions: { allowedOrigins: ["sp.semih.ai", "localhost:3000"] },
},
};
export default config;

32
apps/web/package.json Normal file
View File

@@ -0,0 +1,32 @@
{
"name": "@panel/web",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3000",
"build": "prisma generate && next build",
"start": "next start -p 3000 -H 0.0.0.0",
"lint": "next lint",
"typecheck": "tsc --noEmit",
"prisma:generate": "prisma generate",
"prisma:migrate:deploy": "prisma migrate deploy"
},
"dependencies": {
"@prisma/client": "^5.22.0",
"better-auth": "^1.2.0",
"next": "^16.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"zod": "^3.23.8"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.0.0",
"@types/node": "^22.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"postcss": "^8.4.49",
"prisma": "^5.22.0",
"tailwindcss": "^4.0.0",
"typescript": "^5.6.0"
}
}

View File

@@ -0,0 +1,3 @@
export default {
plugins: { "@tailwindcss/postcss": {} },
};

View File

@@ -0,0 +1,96 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL_PANEL")
}
model User {
id String @id
name String
email String @unique
emailVerified Boolean @default(false)
image String?
twoFactorEnabled Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
sessions Session[]
accounts Account[]
twoFactors TwoFactor[]
}
model Session {
id String @id
userId String
token String @unique
expiresAt DateTime
ipAddress String?
userAgent String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model Account {
id String @id
userId String
accountId String
providerId String
accessToken String?
refreshToken String?
accessTokenExpiresAt DateTime?
refreshTokenExpiresAt DateTime?
scope String?
idToken String?
password String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model Verification {
id String @id
identifier String
value String
expiresAt DateTime
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model TwoFactor {
id String @id
userId String
secret String
backupCodes String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
}
model Project {
id String @id @default(cuid())
key String @unique
name String
description String?
active Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model AuditLog {
id String @id @default(cuid())
actorUserId String?
projectKey String?
endpoint String
method String
requestHash String?
responseStatus Int?
durationMs Int?
sourceIp String?
userAgent String?
createdAt DateTime @default(now())
@@index([createdAt])
@@index([actorUserId])
@@index([projectKey])
}

View File

@@ -0,0 +1,4 @@
import { auth } from "@/lib/auth";
import { toNextJsHandler } from "better-auth/next-js";
export const { GET, POST } = toNextJsHandler(auth);

View File

@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
export async function GET() {
try {
await prisma.$queryRaw`SELECT 1`;
return NextResponse.json({ ok: true });
} catch {
return NextResponse.json({ ok: false }, { status: 503 });
}
}

View File

@@ -0,0 +1,16 @@
@import "tailwindcss";
@theme {
--color-bg: #0a0a0a;
--color-surface: #111111;
--color-border: #1f1f1f;
--color-fg: #ededed;
--color-muted: #8b8b8b;
--color-accent: #f97316;
}
html, body {
background: var(--color-bg);
color: var(--color-fg);
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
}

View File

@@ -0,0 +1,16 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Süper Panel",
description: "Internal admin panel",
robots: { index: false, follow: false },
};
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="tr" className="dark">
<body>{children}</body>
</html>
);
}

View File

@@ -0,0 +1,101 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { signIn, twoFactor } from "@/lib/auth-client";
export default function LoginPage() {
const router = useRouter();
const [stage, setStage] = useState<"creds" | "totp">("creds");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [code, setCode] = useState("");
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
async function submitCreds(e: React.FormEvent) {
e.preventDefault();
setError(null);
setLoading(true);
const { data, error } = await signIn.email({ email, password });
setLoading(false);
if (error) return setError(error.message ?? "Login failed");
if ((data as { twoFactorRedirect?: boolean })?.twoFactorRedirect) {
setStage("totp");
return;
}
router.replace("/");
}
async function submitTotp(e: React.FormEvent) {
e.preventDefault();
setError(null);
setLoading(true);
const { error } = await twoFactor.verifyTotp({ code });
setLoading(false);
if (error) return setError(error.message ?? "Invalid code");
router.replace("/");
}
return (
<main className="flex min-h-screen items-center justify-center px-4">
<div className="w-full max-w-sm rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-8">
<h1 className="text-xl font-semibold">Süper Panel</h1>
<p className="mt-1 text-sm text-[var(--color-muted)]">
{stage === "creds" ? "Sign in" : "Two-factor code"}
</p>
{stage === "creds" ? (
<form onSubmit={submitCreds} className="mt-6 space-y-3">
<input
type="email"
required
placeholder="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full rounded-md border border-[var(--color-border)] bg-black px-3 py-2 text-sm outline-none focus:border-[var(--color-accent)]"
/>
<input
type="password"
required
minLength={12}
placeholder="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-md border border-[var(--color-border)] bg-black px-3 py-2 text-sm outline-none focus:border-[var(--color-accent)]"
/>
<button
type="submit"
disabled={loading}
className="w-full rounded-md bg-[var(--color-accent)] py-2 text-sm font-medium text-black disabled:opacity-60"
>
{loading ? "…" : "Sign in"}
</button>
</form>
) : (
<form onSubmit={submitTotp} className="mt-6 space-y-3">
<input
inputMode="numeric"
pattern="[0-9]*"
required
maxLength={6}
placeholder="123456"
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
className="w-full rounded-md border border-[var(--color-border)] bg-black px-3 py-2 text-center text-lg tracking-[0.4em] outline-none focus:border-[var(--color-accent)]"
/>
<button
type="submit"
disabled={loading || code.length !== 6}
className="w-full rounded-md bg-[var(--color-accent)] py-2 text-sm font-medium text-black disabled:opacity-60"
>
{loading ? "…" : "Verify"}
</button>
</form>
)}
{error && <p className="mt-4 text-sm text-red-400">{error}</p>}
</div>
</main>
);
}

47
apps/web/src/app/page.tsx Normal file
View File

@@ -0,0 +1,47 @@
import { auth } from "@/lib/auth";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
export default async function Home() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/login");
return (
<main className="min-h-screen p-8">
<header className="mb-10 flex items-center justify-between">
<div>
<h1 className="text-2xl font-semibold tracking-tight">Süper Panel</h1>
<p className="text-sm text-[var(--color-muted)]">{session.user.email}</p>
</div>
<form action="/api/auth/sign-out" method="POST">
<button
type="submit"
className="rounded-md border border-[var(--color-border)] px-3 py-1.5 text-sm hover:bg-[var(--color-surface)]"
>
Sign out
</button>
</form>
</header>
<section className="grid grid-cols-1 gap-4 md:grid-cols-3">
<Card title="Projects" value="0" hint="No spokes wired yet" />
<Card title="Events (24h)" value="0" hint="Redis Streams idle" />
<Card title="Audit (24h)" value="0" hint="No actions" />
</section>
<p className="mt-10 text-xs text-[var(--color-muted)]">
Phase 0 skeleton · Tailscale-only · sp.semih.ai
</p>
</main>
);
}
function Card({ title, value, hint }: { title: string; value: string; hint: string }) {
return (
<div className="rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-5">
<div className="text-xs uppercase tracking-wide text-[var(--color-muted)]">{title}</div>
<div className="mt-2 text-3xl font-semibold">{value}</div>
<div className="mt-1 text-xs text-[var(--color-muted)]">{hint}</div>
</div>
);
}

View File

@@ -0,0 +1,91 @@
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { twoFactor, useSession } from "@/lib/auth-client";
export default function Setup2FA() {
const router = useRouter();
const { data: session, isPending } = useSession();
const [password, setPassword] = useState("");
const [otpAuthUri, setOtpAuthUri] = useState<string | null>(null);
const [backupCodes, setBackupCodes] = useState<string[] | null>(null);
const [code, setCode] = useState("");
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!isPending && !session) router.replace("/login");
}, [isPending, session, router]);
async function enable(e: React.FormEvent) {
e.preventDefault();
setError(null);
const { data, error } = await twoFactor.enable({ password });
if (error) return setError(error.message ?? "Failed");
setOtpAuthUri(data?.totpURI ?? null);
setBackupCodes(data?.backupCodes ?? null);
}
async function verify(e: React.FormEvent) {
e.preventDefault();
setError(null);
const { error } = await twoFactor.verifyTotp({ code });
if (error) return setError(error.message ?? "Invalid code");
router.replace("/");
}
return (
<main className="flex min-h-screen items-center justify-center px-4">
<div className="w-full max-w-md rounded-lg border border-[var(--color-border)] bg-[var(--color-surface)] p-8">
<h1 className="text-xl font-semibold">Enable two-factor</h1>
<p className="mt-1 text-sm text-[var(--color-muted)]">Scan the URI in your authenticator</p>
{!otpAuthUri ? (
<form onSubmit={enable} className="mt-6 space-y-3">
<input
type="password"
required
placeholder="current password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded-md border border-[var(--color-border)] bg-black px-3 py-2 text-sm outline-none"
/>
<button type="submit" className="w-full rounded-md bg-[var(--color-accent)] py-2 text-sm font-medium text-black">
Generate TOTP
</button>
</form>
) : (
<div className="mt-6 space-y-4">
<code className="block break-all rounded-md border border-[var(--color-border)] bg-black p-3 text-xs">
{otpAuthUri}
</code>
{backupCodes && (
<div>
<p className="text-xs uppercase tracking-wide text-[var(--color-muted)]">Backup codes</p>
<ul className="mt-1 grid grid-cols-2 gap-1 text-xs">
{backupCodes.map((c) => <li key={c} className="font-mono">{c}</li>)}
</ul>
</div>
)}
<form onSubmit={verify} className="space-y-3">
<input
inputMode="numeric"
required
maxLength={6}
placeholder="123456"
value={code}
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
className="w-full rounded-md border border-[var(--color-border)] bg-black px-3 py-2 text-center text-lg tracking-[0.4em] outline-none"
/>
<button type="submit" className="w-full rounded-md bg-[var(--color-accent)] py-2 text-sm font-medium text-black">
Verify &amp; finish
</button>
</form>
</div>
)}
{error && <p className="mt-4 text-sm text-red-400">{error}</p>}
</div>
</main>
);
}

View File

@@ -0,0 +1,10 @@
"use client";
import { createAuthClient } from "better-auth/react";
import { twoFactorClient } from "better-auth/client/plugins";
export const authClient = createAuthClient({
plugins: [twoFactorClient()],
});
export const { signIn, signUp, signOut, useSession, twoFactor } = authClient;

29
apps/web/src/lib/auth.ts Normal file
View File

@@ -0,0 +1,29 @@
import { betterAuth } from "better-auth";
import { prismaAdapter } from "better-auth/adapters/prisma";
import { twoFactor } from "better-auth/plugins";
import { prisma } from "./db";
export const auth = betterAuth({
database: prismaAdapter(prisma, { provider: "postgresql" }),
secret: process.env.BETTER_AUTH_SECRET,
baseURL: process.env.BETTER_AUTH_URL,
emailAndPassword: {
enabled: true,
autoSignIn: true,
minPasswordLength: 12,
},
session: {
expiresIn: 60 * 60 * 8,
updateAge: 60 * 60,
cookieCache: { enabled: true, maxAge: 5 * 60 },
},
advanced: {
cookiePrefix: "sp",
useSecureCookies: process.env.NODE_ENV === "production",
},
plugins: [
twoFactor({
issuer: "Süper Panel",
}),
],
});

9
apps/web/src/lib/db.ts Normal file
View File

@@ -0,0 +1,9 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({ log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"] });
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;

21
apps/web/tsconfig.json Normal file
View File

@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}