chore(template): publish Base.Next
Some checks are pending
CI / quality (push) Waiting to run

This commit is contained in:
w4c-templates 2026-10-11 23:23:30 +03:00
parent 1402848a5f
commit 219be916cb
74 changed files with 11064 additions and 2 deletions

12
.dockerignore Normal file
View file

@ -0,0 +1,12 @@
node_modules
.next
.git
.env
.env.local
*.db
docker
.github
.w4c
tests
README.md
coverage

15
.env.example Normal file
View file

@ -0,0 +1,15 @@
# --- Core -------------------------------------------------------------------
# SQLite in development; point at Postgres in production (see README).
DATABASE_URL="file:./dev.db"
# Public origin used for absolute URLs (sitemap, OG, checkout redirects).
NEXT_PUBLIC_SITE_URL="http://localhost:3000"
# --- Payments (optional) ----------------------------------------------------
# Leave empty to use the built-in mock provider (no keys needed).
STRIPE_SECRET_KEY=""
STRIPE_WEBHOOK_SECRET=""
# --- Email (optional) -------------------------------------------------------
# Leave empty to use the built-in log provider (no keys needed).
RESEND_API_KEY=""
EMAIL_FROM="Acme <noreply@example.com>"

7
.eslintrc.json Normal file
View file

@ -0,0 +1,7 @@
{
"extends": "next/core-web-vitals",
"rules": {
"@next/next/no-img-element": "off",
"react/no-unescaped-entities": "off"
}
}

33
.github/workflows/ci.yml vendored Normal file
View file

@ -0,0 +1,33 @@
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
quality:
runs-on: ubuntu-latest
env:
DATABASE_URL: "file:./ci.db"
NEXT_PUBLIC_SITE_URL: "http://localhost:3000"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run typecheck
- run: npm run db:setup
- run: npm test
- run: npm run build
- name: e2e smoke
run: |
npm start &
for i in $(seq 1 60); do
if curl -sf http://127.0.0.1:3000/api/health >/dev/null; then break; fi
sleep 1
done
npm run test:e2e

11
.gitignore vendored Normal file
View file

@ -0,0 +1,11 @@
node_modules
.next
out
dist
coverage
.env
.env.local
*.db
*.db-journal
.vercel
next-env.d.ts

BIN
.w4c/preview.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

31
.w4c/qa.json Normal file
View file

@ -0,0 +1,31 @@
{
"install": "npm ci",
"setup": "npm run db:setup",
"lint": "npm run lint",
"typecheck": "npm run typecheck",
"unit": "npm run test",
"build": "npm run build",
"start": "npm run start",
"e2e": "node tests/e2e/smoke.mjs",
"port": 3000,
"health": "/api/health",
"env": {
"DATABASE_URL": "file:./dev.db",
"NEXT_PUBLIC_SITE_URL": "http://localhost:3000"
},
"routes": [
{ "path": "/", "expect": [200] },
{ "path": "/pricing", "expect": [200] },
{ "path": "/login", "expect": [200] },
{ "path": "/register", "expect": [200] },
{ "path": "/legal/privacy", "expect": [200] },
{ "path": "/dashboard", "expect": [307, 302] },
{ "path": "/admin", "expect": [307, 302] },
{ "path": "/api/health", "expect": [200] },
{ "path": "/api/auth/me", "expect": [401] },
{ "path": "/api/admin/users", "expect": [401] },
{ "path": "/sitemap.xml", "expect": [200] },
{ "path": "/robots.txt", "expect": [200] }
],
"timeout": { "install": 900, "build": 900, "boot": 120 }
}

30
.w4c/template.json Normal file
View file

@ -0,0 +1,30 @@
{
"schema": 2,
"system": "v2",
"catalog": false,
"id": "base-next",
"case": "base",
"stack": "next",
"title": "Base — Next.js",
"description": "The shared core: auth, roles, Prisma, mock payments/email, admin shell, SEO, CI and Docker.",
"tags": ["base", "next", "starter"],
"preview": ".w4c/preview.png",
"agentId": "w4c-start2",
"defaultName": "my-app",
"featured": false,
"env": [
{ "key": "DATABASE_URL", "required": false, "note": "SQLite by default; Postgres in production" },
{ "key": "NEXT_PUBLIC_SITE_URL", "required": false, "note": "Public origin for sitemap/OG/checkout" },
{ "key": "STRIPE_SECRET_KEY", "required": false, "note": "mock provider is used when absent" },
{ "key": "RESEND_API_KEY", "required": false, "note": "log provider is used when absent" }
],
"modules": [
{ "id": "resend-email", "skill": "integration-resend-email" },
{ "id": "s3-storage", "skill": "integration-s3-storage" },
{ "id": "analytics", "skill": "integration-analytics" }
],
"seededAccounts": [
{ "role": "admin", "email": "admin@example.com", "password": "password" },
{ "role": "user", "email": "user@example.com", "password": "password" }
]
}

View file

@ -1,3 +1,68 @@
# templates2.Base.Next
# Base — Next.js (templates2)
The shared core: auth, roles, Prisma, mock payments/email, admin shell, SEO, CI and Docker.
A **ready-to-run** Next.js (App Router) base application. It is the shared core every Next.js
v2 case forks: authentication, roles, Prisma, mock payments and email, an admin shell, SEO,
i18n, observability, CI and a Docker image — all working on the first run.
> Not listed in the user catalog (`"catalog": false` in `.w4c/template.json`); it exists to be
> forked by cases such as `Store.Next` or `Saas.Next`.
## Quickstart
```bash
npm ci
cp .env.example .env # SQLite + mock providers by default — no keys needed
npm run db:setup # prisma db push + seed
npm run dev # http://localhost:3000
```
Demo accounts (seeded): `admin@example.com` (admin) and `user@example.com` (user) — password
`password`.
## Scripts
| Script | What it does |
|---|---|
| `npm run dev` | Dev server with HMR |
| `npm run build` / `npm start` | Production build / serve |
| `npm run lint` / `npm run typecheck` | ESLint / `tsc --noEmit` |
| `npm test` | Unit tests (Vitest) |
| `npm run test:e2e` | HTTP end-to-end smoke (server must be running) |
| `npm run db:setup` | `prisma db push` + seed |
| `npm run db:seed` | Seed only |
## What works out of the box
- **Auth & roles** — email + password, bcrypt, httpOnly cookie sessions (`Session` table), `user`
and `admin` roles, server-side guards (`requireUser`, `requireAdmin`) and API authorization.
- **Payments** — a provider interface with a **mock provider that needs no keys** and activates the
subscription immediately, plus a Stripe provider that turns on when `STRIPE_SECRET_KEY` is set.
Webhooks are signature-checked and idempotent.
- **Email** — a log provider by default, Resend when `RESEND_API_KEY` is set.
- **Admin** — role-gated shell, overview dashboard, users table (role change / delete with
confirmation) and an audit log.
- **SEO** — per-route metadata, OpenGraph, JSON-LD, `sitemap.xml`, `robots.txt`.
- **i18n** — English dictionary in `messages/en.json`, looked up via `t()`.
- **Observability** — `/api/health`, error boundary and loading/empty states.
- **Delivery** — multi-stage Dockerfile with a healthcheck, and CI running lint + typecheck + unit
+ build + e2e.
## Data model
`prisma/schema.prisma`: `User`, `Session`, `Subscription`, `AuditLog`. SQLite in development;
point `DATABASE_URL` at Postgres for production.
## Deployment
```bash
docker compose -f docker/docker-compose.yml up --build
```
## Quality
```bash
node ../templates2/qa.mjs Base.Next # from the repo root: node templates2/qa.mjs Base.Next
```
The harness isolates a clean copy, then runs install → verify → test → build → boot → routes →
e2e → screenshot. See [`../CONTRACT.md`](../CONTRACT.md) for the Definition of Done.

View file

@ -0,0 +1,59 @@
import Link from 'next/link';
import { Badge, Card } from '@/components/ui';
import { requireUser } from '@/lib/server/auth';
import { db } from '@/lib/server/db';
import { getPlan } from '@/lib/plans';
import { t } from '@/lib/i18n';
export const dynamic = 'force-dynamic';
export default async function DashboardPage() {
const user = await requireUser();
const sub = await db.subscription.findUnique({ where: { userId: user.id } });
const plan = getPlan(sub?.plan);
const usedCalls = await db.auditLog.count({ where: { actorId: user.id } });
const usage = [
{ label: 'Seats', used: 1, limit: plan.limits.seats },
{ label: 'API calls', used: usedCalls, limit: plan.limits.apiCalls },
];
return (
<div className="space-y-6">
<header className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold">{t('dashboard.title')}</h1>
<p className="muted mt-1">{t('dashboard.welcome', { name: user.name || user.email })}</p>
</div>
<Badge tone={plan.id === 'pro' ? 'brand' : 'neutral'}>{plan.name}</Badge>
</header>
<Card title={t('dashboard.plan')} actions={<Link href="/pricing" className="btn-secondary">{t('pricing.choose')}</Link>}>
<p className="muted text-sm">
{plan.name} — ${plan.price} / month
</p>
</Card>
<Card title={t('dashboard.usage')}>
<ul className="space-y-4">
{usage.map((u) => {
const pct = Math.min(100, Math.round((u.used / u.limit) * 100));
return (
<li key={u.label}>
<div className="mb-1 flex justify-between text-sm">
<span>{u.label}</span>
<span className="muted">
{u.used} / {u.limit}
</span>
</div>
<div className="h-2 w-full overflow-hidden rounded-full" style={{ background: 'var(--border)' }}>
<div className="h-full rounded-full" style={{ width: `${pct}%`, background: 'var(--color-brand-600)' }} />
</div>
</li>
);
})}
</ul>
</Card>
</div>
);
}

12
app/(app)/layout.tsx Normal file
View file

@ -0,0 +1,12 @@
import { SiteHeader } from '@/components/SiteHeader';
import { SiteFooter } from '@/components/SiteFooter';
export default function AppLayout({ children }: { children: React.ReactNode }) {
return (
<div className="flex min-h-screen flex-col">
<SiteHeader />
<main className="page flex-1 py-10">{children}</main>
<SiteFooter />
</div>
);
}

13
app/(auth)/layout.tsx Normal file
View file

@ -0,0 +1,13 @@
import Link from 'next/link';
import { t } from '@/lib/i18n';
export default function AuthLayout({ children }: { children: React.ReactNode }) {
return (
<div className="flex min-h-screen flex-col items-center justify-center px-5 py-12">
<Link href="/" className="mb-8 text-xl font-bold">
{t('brand.name')}
</Link>
<div className="w-full max-w-sm">{children}</div>
</div>
);
}

15
app/(auth)/login/page.tsx Normal file
View file

@ -0,0 +1,15 @@
import { Suspense } from 'react';
import { redirect } from 'next/navigation';
import { AuthForm } from '@/components/AuthForm';
import { getCurrentUser } from '@/lib/server/auth';
export const dynamic = 'force-dynamic';
export default async function LoginPage() {
if (await getCurrentUser()) redirect('/dashboard');
return (
<Suspense fallback={<p className="muted text-center">Loading…</p>}>
<AuthForm mode="login" />
</Suspense>
);
}

View file

@ -0,0 +1,15 @@
import { Suspense } from 'react';
import { redirect } from 'next/navigation';
import { AuthForm } from '@/components/AuthForm';
import { getCurrentUser } from '@/lib/server/auth';
export const dynamic = 'force-dynamic';
export default async function RegisterPage() {
if (await getCurrentUser()) redirect('/dashboard');
return (
<Suspense fallback={<p className="muted text-center">Loading…</p>}>
<AuthForm mode="register" />
</Suspense>
);
}

View file

@ -0,0 +1,12 @@
import { SiteHeader } from '@/components/SiteHeader';
import { SiteFooter } from '@/components/SiteFooter';
export default function MarketingLayout({ children }: { children: React.ReactNode }) {
return (
<div className="flex min-h-screen flex-col">
<SiteHeader />
<main className="flex-1">{children}</main>
<SiteFooter />
</div>
);
}

View file

@ -0,0 +1,10 @@
export default function PrivacyPage() {
return (
<article className="page prose max-w-3xl py-16">
<h1 className="text-3xl font-bold">Privacy Policy</h1>
<p className="muted mt-4">
This is a placeholder legal page. Replace it with your own policy before going live.
</p>
</article>
);
}

View file

@ -0,0 +1,10 @@
export default function TermsPage() {
return (
<article className="page prose max-w-3xl py-16">
<h1 className="text-3xl font-bold">Terms of Service</h1>
<p className="muted mt-4">
This is a placeholder legal page. Replace it with your own terms before going live.
</p>
</article>
);
}

44
app/(marketing)/page.tsx Normal file
View file

@ -0,0 +1,44 @@
import Link from 'next/link';
import { t } from '@/lib/i18n';
const features = ['auth', 'billing', 'admin', 'seo'] as const;
export default function HomePage() {
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'WebSite',
name: t('brand.name'),
url: process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000',
};
return (
<>
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
<section className="page py-20 text-center">
<h1 className="mx-auto max-w-3xl text-4xl font-extrabold tracking-tight sm:text-5xl">
{t('home.title')}
</h1>
<p className="muted mx-auto mt-5 max-w-2xl text-lg">{t('home.subtitle')}</p>
<div className="mt-8 flex justify-center gap-3">
<Link href="/register" className="btn-primary">
{t('home.cta')}
</Link>
<Link href="/pricing" className="btn-secondary">
{t('home.secondaryCta')}
</Link>
</div>
</section>
<section className="page pb-24">
<h2 className="mb-8 text-center text-2xl font-bold">{t('home.featuresTitle')}</h2>
<div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-4">
{features.map((key) => (
<div key={key} className="card">
<h3 className="text-base font-semibold">{t(`home.features.${key}.title`)}</h3>
<p className="muted mt-2 text-sm">{t(`home.features.${key}.body`)}</p>
</div>
))}
</div>
</section>
</>
);
}

View file

@ -0,0 +1,74 @@
import Link from 'next/link';
import { Badge } from '@/components/ui';
import { UpgradeButton } from '@/components/UpgradeButton';
import { getCurrentUser } from '@/lib/server/auth';
import { db } from '@/lib/server/db';
import { PLANS, PLAN_IDS, getPlan } from '@/lib/plans';
import { formatCurrency } from '@/lib/utils';
import { t } from '@/lib/i18n';
export const dynamic = 'force-dynamic';
export default async function PricingPage({
searchParams,
}: {
searchParams: Promise<{ billing?: string }>;
}) {
const { billing } = await searchParams;
const user = await getCurrentUser();
const sub = user ? await db.subscription.findUnique({ where: { userId: user.id } }) : null;
const currentPlan = getPlan(sub?.plan).id;
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'SoftwareApplication',
name: t('brand.name'),
applicationCategory: 'BusinessApplication',
offers: PLAN_IDS.map((id) => ({ '@type': 'Offer', name: PLANS[id].name, price: PLANS[id].price, priceCurrency: 'USD' })),
};
return (
<div className="page py-16">
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
<h1 className="text-center text-3xl font-bold">{t('pricing.title')}</h1>
<p className="muted mt-3 text-center">{t('pricing.subtitle')}</p>
{billing === 'success' && (
<p className="mx-auto mt-6 max-w-md rounded-lg border border-emerald-500 bg-emerald-50 px-4 py-3 text-center text-sm text-emerald-800">
{t('pricing.upgraded')}
</p>
)}
<div className="mx-auto mt-10 grid max-w-4xl gap-6 sm:grid-cols-2">
{PLAN_IDS.map((id) => {
const plan = PLANS[id];
const isCurrent = user && currentPlan === id;
return (
<div key={id} className="card flex flex-col">
<div className="flex items-center justify-between">
<h2 className="text-xl font-semibold">{plan.name}</h2>
{isCurrent && <Badge tone="brand">Current</Badge>}
</div>
<p className="mt-4 text-3xl font-bold">
{formatCurrency(plan.price)}
<span className="muted text-base font-normal"> {t('pricing.perMonth')}</span>
</p>
<ul className="muted mt-5 flex-1 space-y-2 text-sm">
{plan.features.map((f) => (
<li key={f}>• {f}</li>
))}
</ul>
{isCurrent ? (
<p className="mt-6 text-center text-sm font-medium text-emerald-600">{t('pricing.current')}</p>
) : user ? (
<UpgradeButton plan={id} label={t('pricing.choose')} />
) : (
<Link href={`/login?next=/pricing`} className="btn-primary mt-6 w-full">
{t('pricing.choose')}
</Link>
)}
</div>
);
})}
</div>
</div>
);
}

39
app/admin/audit/page.tsx Normal file
View file

@ -0,0 +1,39 @@
import { EmptyState } from '@/components/ui';
import { requireAdmin } from '@/lib/server/auth';
import { db } from '@/lib/server/db';
import { formatDate } from '@/lib/utils';
import { t } from '@/lib/i18n';
export const dynamic = 'force-dynamic';
export default async function AdminAuditPage() {
await requireAdmin();
const entries = await db.auditLog.findMany({
orderBy: { createdAt: 'desc' },
take: 100,
include: { actor: true },
});
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">{t('admin.audit')}</h1>
{entries.length === 0 ? (
<EmptyState />
) : (
<ul className="divide-y rounded-xl border" style={{ borderColor: 'var(--border)' }}>
{entries.map((e) => (
<li key={e.id} className="flex items-center justify-between gap-4 px-4 py-3 text-sm">
<span>
<span className="font-medium">{e.action}</span>
{e.target ? <span className="muted"> → {e.target}</span> : null}
</span>
<span className="muted shrink-0 text-xs">
{e.actor?.email ?? 'system'} · {formatDate(e.createdAt)}
</span>
</li>
))}
</ul>
)}
</div>
);
}

28
app/admin/layout.tsx Normal file
View file

@ -0,0 +1,28 @@
import Link from 'next/link';
import { AdminNav } from '@/components/AdminNav';
import { requireAdmin } from '@/lib/server/auth';
import { t } from '@/lib/i18n';
export const dynamic = 'force-dynamic';
export default async function AdminLayout({ children }: { children: React.ReactNode }) {
const admin = await requireAdmin();
return (
<div className="flex min-h-screen flex-col">
<header className="border-b" style={{ borderColor: 'var(--border)' }}>
<div className="page flex h-16 items-center justify-between">
<Link href="/" className="text-lg font-bold">
{t('brand.name')} <span className="muted font-normal">/ {t('admin.title')}</span>
</Link>
<span className="muted text-sm">{admin.email}</span>
</div>
</header>
<div className="page flex flex-1 flex-col gap-6 py-8 md:flex-row">
<aside className="md:w-52 md:shrink-0">
<AdminNav />
</aside>
<main className="min-w-0 flex-1">{children}</main>
</div>
</div>
);
}

45
app/admin/page.tsx Normal file
View file

@ -0,0 +1,45 @@
import { Card } from '@/components/ui';
import { db } from '@/lib/server/db';
import { t } from '@/lib/i18n';
export const dynamic = 'force-dynamic';
export default async function AdminOverviewPage() {
const [totalUsers, activeSubs, recent] = await Promise.all([
db.user.count(),
db.subscription.count({ where: { status: 'active' } }),
db.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 5, include: { actor: true } }),
]);
const stats = [
{ label: t('admin.totalUsers'), value: totalUsers },
{ label: t('admin.activeSubs'), value: activeSubs },
];
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">{t('admin.overview')}</h1>
<div className="grid gap-5 sm:grid-cols-2">
{stats.map((s) => (
<div key={s.label} className="card">
<p className="muted text-sm">{s.label}</p>
<p className="mt-2 text-3xl font-bold">{s.value}</p>
</div>
))}
</div>
<Card title={t('admin.audit')}>
<ul className="divide-y" style={{ borderColor: 'var(--border)' }}>
{recent.map((entry) => (
<li key={entry.id} className="flex items-center justify-between py-2 text-sm">
<span>
<span className="font-medium">{entry.action}</span>
{entry.target ? <span className="muted"> → {entry.target}</span> : null}
</span>
<span className="muted text-xs">{entry.actor?.email ?? 'system'}</span>
</li>
))}
</ul>
</Card>
</div>
);
}

51
app/admin/users/page.tsx Normal file
View file

@ -0,0 +1,51 @@
import { Badge, EmptyState } from '@/components/ui';
import { UserActions } from '@/components/admin/UserActions';
import { requireAdmin } from '@/lib/server/auth';
import { db } from '@/lib/server/db';
import { formatDate } from '@/lib/utils';
import { t } from '@/lib/i18n';
export const dynamic = 'force-dynamic';
export default async function AdminUsersPage() {
await requireAdmin();
const users = await db.user.findMany({ orderBy: { createdAt: 'asc' }, include: { subscription: true } });
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold">{t('admin.users')}</h1>
{users.length === 0 ? (
<EmptyState />
) : (
<div className="overflow-x-auto rounded-xl border" style={{ borderColor: 'var(--border)' }}>
<table className="w-full text-sm">
<thead className="muted text-left text-xs uppercase">
<tr>
<th className="px-4 py-3">Email</th>
<th className="px-4 py-3">Role</th>
<th className="px-4 py-3">Plan</th>
<th className="px-4 py-3">Created</th>
<th className="px-4 py-3 text-right">Actions</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id} className="border-t" style={{ borderColor: 'var(--border)' }}>
<td className="px-4 py-3 font-medium">{u.email}</td>
<td className="px-4 py-3">
<Badge tone={u.role === 'admin' ? 'brand' : 'neutral'}>{u.role}</Badge>
</td>
<td className="px-4 py-3">{u.subscription?.plan ?? 'free'}</td>
<td className="px-4 py-3">{formatDate(u.createdAt)}</td>
<td className="px-4 py-3">
<UserActions id={u.id} role={u.role} />
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,43 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { getCurrentUser } from '@/lib/server/auth';
import { db } from '@/lib/server/db';
import { recordAudit } from '@/lib/server/audit';
export const dynamic = 'force-dynamic';
const patchSchema = z.object({ role: z.enum(['user', 'admin']) });
async function requireAdminApi() {
const user = await getCurrentUser();
if (!user) return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
if (user.role !== 'admin') return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
return { user };
}
export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await requireAdminApi();
if (auth.error) return auth.error;
const { id } = await params;
const parsed = patchSchema.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return NextResponse.json({ error: 'Invalid role' }, { status: 400 });
if (id === auth.user!.id && parsed.data.role !== 'admin') {
return NextResponse.json({ error: 'You cannot remove your own admin role.' }, { status: 400 });
}
const updated = await db.user.update({ where: { id }, data: { role: parsed.data.role } });
await recordAudit({ actorId: auth.user!.id, action: 'user.role', target: updated.email, meta: { role: parsed.data.role } });
return NextResponse.json({ user: { id: updated.id, email: updated.email, role: updated.role } });
}
export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const auth = await requireAdminApi();
if (auth.error) return auth.error;
const { id } = await params;
if (id === auth.user!.id) return NextResponse.json({ error: 'You cannot delete your own account.' }, { status: 400 });
const deleted = await db.user.delete({ where: { id } });
await recordAudit({ actorId: auth.user!.id, action: 'user.delete', target: deleted.email });
return NextResponse.json({ ok: true });
}

View file

@ -0,0 +1,17 @@
import { NextResponse } from 'next/server';
import { getCurrentUser } from '@/lib/server/auth';
import { db } from '@/lib/server/db';
export const dynamic = 'force-dynamic';
export async function GET() {
const user = await getCurrentUser();
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
if (user.role !== 'admin') return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
const users = await db.user.findMany({
orderBy: { createdAt: 'asc' },
select: { id: true, email: true, name: true, role: true, createdAt: true, subscription: { select: { plan: true, status: true } } },
});
return NextResponse.json({ users });
}

View file

@ -0,0 +1,31 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/server/db';
import { createSession, verifyPassword } from '@/lib/server/auth';
import { recordAudit } from '@/lib/server/audit';
export const dynamic = 'force-dynamic';
const schema = z.object({ email: z.string().email(), password: z.string().min(1) });
export async function POST(request: Request) {
const parsed = schema.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return NextResponse.json({ error: 'Email and password are required.' }, { status: 400 });
const email = parsed.data.email.toLowerCase();
const user = await db.user.findUnique({ where: { email } });
// Constant-ish response: never reveal whether the email exists.
if (!user || !(await verifyPassword(parsed.data.password, user.passwordHash))) {
return NextResponse.json({ error: 'Invalid email or password.' }, { status: 401 });
}
await db.subscription.upsert({
where: { userId: user.id },
update: {},
create: { userId: user.id, plan: 'free', status: 'active', provider: 'mock' },
});
await createSession(user.id);
await recordAudit({ actorId: user.id, action: 'user.login', target: user.email });
return NextResponse.json({ user: { id: user.id, email: user.email, name: user.name, role: user.role } });
}

View file

@ -0,0 +1,10 @@
import { NextResponse } from 'next/server';
import { destroySession } from '@/lib/server/auth';
export const dynamic = 'force-dynamic';
export async function POST() {
await destroySession();
// 303 so a plain HTML form POST turns into a GET of the home page.
return NextResponse.redirect(new URL('/', process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'), 303);
}

10
app/api/auth/me/route.ts Normal file
View file

@ -0,0 +1,10 @@
import { NextResponse } from 'next/server';
import { getCurrentUser } from '@/lib/server/auth';
export const dynamic = 'force-dynamic';
export async function GET() {
const user = await getCurrentUser();
if (!user) return NextResponse.json({ user: null }, { status: 401 });
return NextResponse.json({ user });
}

View file

@ -0,0 +1,44 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { db } from '@/lib/server/db';
import { createSession, hashPassword } from '@/lib/server/auth';
import { recordAudit } from '@/lib/server/audit';
import { sendEmail } from '@/lib/server/email';
export const dynamic = 'force-dynamic';
const schema = z.object({
email: z.string().email().max(200),
password: z.string().min(8).max(200),
name: z.string().max(120).optional(),
});
export async function POST(request: Request) {
const parsed = schema.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) {
return NextResponse.json({ error: 'Invalid email or password (min 8 characters).' }, { status: 400 });
}
const email = parsed.data.email.toLowerCase();
const existing = await db.user.findUnique({ where: { email } });
if (existing) return NextResponse.json({ error: 'An account with this email already exists.' }, { status: 409 });
const user = await db.user.create({
data: {
email,
name: parsed.data.name || null,
role: 'user',
passwordHash: await hashPassword(parsed.data.password),
subscription: { create: { plan: 'free', status: 'active', provider: 'mock' } },
},
});
await recordAudit({ actorId: user.id, action: 'user.register', target: user.email });
await sendEmail({
to: user.email,
subject: 'Welcome',
html: '<p>Your account is ready. Sign in to get started.</p>',
}).catch((e) => console.error('[email] register', e));
await createSession(user.id);
return NextResponse.json({ user: { id: user.id, email: user.email, name: user.name, role: user.role } }, { status: 201 });
}

View file

@ -0,0 +1,43 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { getCurrentUser } from '@/lib/server/auth';
import { db } from '@/lib/server/db';
import { getPayments } from '@/lib/server/payments';
import { recordAudit } from '@/lib/server/audit';
import { env } from '@/lib/env';
export const dynamic = 'force-dynamic';
const schema = z.object({ plan: z.enum(['free', 'pro']) });
export async function POST(request: Request) {
const user = await getCurrentUser();
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const parsed = schema.safeParse(await request.json().catch(() => ({})));
if (!parsed.success) return NextResponse.json({ error: 'Invalid plan' }, { status: 400 });
const provider = getPayments();
const siteUrl = env.NEXT_PUBLIC_SITE_URL.replace(/\/$/, '');
const result = await provider.createCheckout({
userId: user.id,
email: user.email,
plan: parsed.data.plan,
successUrl: `${siteUrl}/dashboard`,
cancelUrl: `${siteUrl}/pricing`,
});
// The mock provider has no external redirect: activate the subscription right away so the
// full "plan → checkout → return → active" flow works with zero configuration.
if (provider.name === 'mock') {
const currentPeriodEnd = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
await db.subscription.upsert({
where: { userId: user.id },
update: { plan: parsed.data.plan, status: 'active', provider: 'mock', currentPeriodEnd },
create: { userId: user.id, plan: parsed.data.plan, status: 'active', provider: 'mock', currentPeriodEnd },
});
}
await recordAudit({ actorId: user.id, action: 'billing.checkout', target: parsed.data.plan, meta: { provider: provider.name } });
return NextResponse.json({ id: result.id, url: result.url, provider: provider.name });
}

View file

@ -0,0 +1,35 @@
import { NextResponse } from 'next/server';
import { db } from '@/lib/server/db';
import { getPayments } from '@/lib/server/payments';
import { recordAudit } from '@/lib/server/audit';
export const dynamic = 'force-dynamic';
export async function POST(request: Request) {
const raw = await request.text();
const signature = request.headers.get('stripe-signature');
const provider = getPayments();
let event;
try {
event = await provider.parseWebhook(raw, signature);
} catch (e) {
return NextResponse.json({ error: e instanceof Error ? e.message : 'Bad webhook' }, { status: 400 });
}
if (event.type === 'checkout.completed' && event.userId) {
const currentPeriodEnd = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
await db.subscription.upsert({
where: { userId: event.userId },
update: { plan: event.plan ?? 'pro', status: 'active', provider: provider.name, currentPeriodEnd },
create: { userId: event.userId, plan: event.plan ?? 'pro', status: 'active', provider: provider.name, currentPeriodEnd },
});
await recordAudit({ actorId: event.userId, action: 'billing.activated', target: event.plan ?? 'pro' });
} else if (event.type === 'subscription.canceled' && event.userId) {
await db.subscription.update({ where: { userId: event.userId }, data: { status: 'canceled' } }).catch(() => undefined);
await recordAudit({ actorId: event.userId, action: 'billing.canceled', target: event.userId });
}
// Idempotent: re-delivered events simply re-apply the same upsert.
return NextResponse.json({ received: true });
}

7
app/api/health/route.ts Normal file
View file

@ -0,0 +1,7 @@
import { NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
export function GET() {
return NextResponse.json({ status: 'ok', service: 'templates2-base-next', time: new Date().toISOString() });
}

13
app/error.tsx Normal file
View file

@ -0,0 +1,13 @@
'use client';
export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
return (
<div className="flex min-h-screen flex-col items-center justify-center px-5 text-center">
<h1 className="text-xl font-semibold">Something went wrong</h1>
<p className="muted mt-2 text-sm">{error.message || 'An unexpected error occurred.'}</p>
<button type="button" className="btn-primary mt-8" onClick={reset}>
Try again
</button>
</div>
);
}

153
app/globals.css Normal file
View file

@ -0,0 +1,153 @@
@import "tailwindcss";
/* Theme is toggled by a `.dark` class on <html> (see ThemeProvider). */
@custom-variant dark (&:where(.dark, .dark *));
@theme {
--color-brand-50: #eef2ff;
--color-brand-100: #e0e7ff;
--color-brand-200: #c7d2fe;
--color-brand-400: #818cf8;
--color-brand-500: #6366f1;
--color-brand-600: #4f46e5;
--color-brand-700: #4338ca;
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
:root {
--surface: #ffffff;
--surface-muted: #f8fafc;
--border: #e2e8f0;
--text: #0f172a;
--text-muted: #52607a;
color-scheme: light;
}
.dark {
--surface: #0b1120;
--surface-muted: #111827;
--border: #1f2937;
--text: #e5e7eb;
--text-muted: #94a3b8;
color-scheme: dark;
}
* {
border-color: var(--border);
}
html,
body {
background: var(--surface);
color: var(--text);
}
body {
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
}
a {
color: inherit;
}
@layer components {
.page {
@apply mx-auto w-full max-w-6xl px-5;
}
.surface {
background: var(--surface);
}
.muted {
color: var(--text-muted);
}
.card {
@apply rounded-2xl border p-6;
background: var(--surface-muted);
border-color: var(--border);
}
/* All button variants share the base rule (Tailwind v4 cannot @apply a custom class). */
.btn,
.btn-primary,
.btn-secondary,
.btn-ghost,
.btn-danger {
@apply inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition;
}
.btn:disabled,
.btn-primary:disabled,
.btn-secondary:disabled,
.btn-ghost:disabled,
.btn-danger:disabled {
@apply cursor-not-allowed opacity-60;
}
.btn-primary {
@apply text-white;
background: var(--color-brand-600);
}
.btn-primary:hover:not(:disabled) {
background: var(--color-brand-700);
}
.btn-secondary {
@apply border;
background: var(--surface);
color: var(--text);
border-color: var(--border);
}
.btn-secondary:hover:not(:disabled) {
background: var(--surface-muted);
}
.btn-ghost {
color: var(--text-muted);
}
.btn-ghost:hover:not(:disabled) {
background: var(--surface-muted);
color: var(--text);
}
.btn-danger {
@apply bg-red-600 text-white;
}
.btn-danger:hover:not(:disabled) {
@apply bg-red-700;
}
.label {
@apply mb-1 block text-sm font-medium;
}
.input {
@apply w-full rounded-lg border px-3 py-2 text-sm outline-none;
background: var(--surface);
color: var(--text);
border-color: var(--border);
}
.input:focus {
border-color: var(--color-brand-500);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--color-brand-500) 25%, transparent);
}
.badge {
@apply inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold;
}
}
/* Visible keyboard focus everywhere (WCAG 2.4.7). */
:focus-visible {
outline: 2px solid var(--color-brand-500);
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}

31
app/layout.tsx Normal file
View file

@ -0,0 +1,31 @@
import type { Metadata } from 'next';
import './globals.css';
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000';
export const metadata: Metadata = {
metadataBase: new URL(siteUrl),
title: { default: 'Acme — ready-to-run app', template: '%s · Acme' },
description: 'A production-ready base app: auth, roles, payments, admin, SEO — working on day one.',
openGraph: {
type: 'website',
siteName: 'Acme',
url: '/',
title: 'Acme — ready-to-run app',
description: 'A production-ready base app: auth, roles, payments, admin, SEO.',
},
robots: { index: true, follow: true },
};
const themeScript = `try{var t=localStorage.getItem('theme');var d=t? t==='dark' : matchMedia('(prefers-color-scheme: dark)').matches;if(d)document.documentElement.classList.add('dark');}catch(e){}`;
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en" suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: themeScript }} />
</head>
<body className="min-h-screen antialiased">{children}</body>
</html>
);
}

10
app/loading.tsx Normal file
View file

@ -0,0 +1,10 @@
export default function Loading() {
return (
<div className="flex min-h-screen items-center justify-center">
<div className="flex items-center gap-3">
<span className="h-5 w-5 animate-spin rounded-full border-2 border-current border-t-transparent" aria-hidden />
<span className="muted text-sm">Loading…</span>
</div>
</div>
);
}

14
app/not-found.tsx Normal file
View file

@ -0,0 +1,14 @@
import Link from 'next/link';
export default function NotFound() {
return (
<div className="flex min-h-screen flex-col items-center justify-center px-5 text-center">
<p className="text-6xl font-bold">404</p>
<h1 className="mt-4 text-xl font-semibold">Page not found</h1>
<p className="muted mt-2">The page you are looking for does not exist.</p>
<Link href="/" className="btn-primary mt-8">
Back home
</Link>
</div>
);
}

9
app/robots.ts Normal file
View file

@ -0,0 +1,9 @@
import type { MetadataRoute } from 'next';
export default function robots(): MetadataRoute.Robots {
const base = (process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000').replace(/\/$/, '');
return {
rules: { userAgent: '*', allow: '/', disallow: ['/admin', '/dashboard', '/api'] },
sitemap: `${base}/sitemap.xml`,
};
}

12
app/sitemap.ts Normal file
View file

@ -0,0 +1,12 @@
import type { MetadataRoute } from 'next';
export default function sitemap(): MetadataRoute.Sitemap {
const base = (process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000').replace(/\/$/, '');
const now = new Date();
return [
{ url: `${base}/`, lastModified: now, changeFrequency: 'weekly', priority: 1 },
{ url: `${base}/pricing`, lastModified: now, changeFrequency: 'monthly', priority: 0.8 },
{ url: `${base}/legal/privacy`, lastModified: now, changeFrequency: 'yearly', priority: 0.3 },
{ url: `${base}/legal/terms`, lastModified: now, changeFrequency: 'yearly', priority: 0.3 },
];
}

24
components/AdminNav.tsx Normal file
View file

@ -0,0 +1,24 @@
import Link from 'next/link';
import { t } from '@/lib/i18n';
const items = [
{ href: '/admin', label: t('admin.overview') },
{ href: '/admin/users', label: t('admin.users') },
{ href: '/admin/audit', label: t('admin.audit') },
];
export function AdminNav() {
return (
<nav className="flex gap-1 md:flex-col" aria-label="Admin">
{items.map((item) => (
<Link
key={item.href}
href={item.href}
className="rounded-lg px-3 py-2 text-sm font-medium hover:bg-black/5 dark:hover:bg-white/10"
>
{item.label}
</Link>
))}
</nav>
);
}

79
components/AuthForm.tsx Normal file
View file

@ -0,0 +1,79 @@
'use client';
import { useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { Field } from '@/components/ui';
import { t } from '@/lib/i18n';
export function AuthForm({ mode }: { mode: 'login' | 'register' }) {
const router = useRouter();
const params = useSearchParams();
const next = params.get('next') || '/dashboard';
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setBusy(true);
setError(null);
const form = new FormData(e.currentTarget);
const body = Object.fromEntries(form.entries());
try {
const res = await fetch(`/api/auth/${mode}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) {
const data = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(data.error || `Request failed (${res.status})`);
}
router.push(next);
router.refresh();
} catch (err) {
setError(err instanceof Error ? err.message : 'Request failed');
setBusy(false);
}
}
const isRegister = mode === 'register';
return (
<div className="card">
<h1 className="text-xl font-semibold">{isRegister ? t('auth.registerTitle') : t('auth.loginTitle')}</h1>
<form className="mt-6 space-y-4" onSubmit={onSubmit} noValidate>
{isRegister && (
<Field label={t('auth.name')} htmlFor="name">
<input id="name" name="name" className="input" autoComplete="name" />
</Field>
)}
<Field label={t('auth.email')} htmlFor="email">
<input id="email" name="email" type="email" required className="input" autoComplete="email" />
</Field>
<Field label={t('auth.password')} htmlFor="password">
<input
id="password"
name="password"
type="password"
required
minLength={8}
className="input"
autoComplete={isRegister ? 'new-password' : 'current-password'}
/>
</Field>
{error && <p className="text-sm text-red-600">{error}</p>}
<button type="submit" className="btn-primary w-full" disabled={busy}>
{busy ? '…' : isRegister ? t('auth.submitRegister') : t('auth.submitLogin')}
</button>
</form>
<p className="muted mt-5 text-center text-sm">
{isRegister ? t('auth.hasAccount') : t('auth.noAccount')}{' '}
<Link href={isRegister ? '/login' : '/register'} className="font-medium text-brand-600 hover:underline">
{isRegister ? t('auth.submitLogin') : t('auth.submitRegister')}
</Link>
</p>
{!isRegister && <p className="muted mt-3 text-center text-xs">{t('auth.demoHint')}</p>}
</div>
);
}

25
components/SiteFooter.tsx Normal file
View file

@ -0,0 +1,25 @@
import Link from 'next/link';
import { t } from '@/lib/i18n';
export function SiteFooter() {
return (
<footer className="border-t" style={{ borderColor: 'var(--border)' }}>
<div className="page flex flex-col items-center justify-between gap-4 py-8 text-sm sm:flex-row">
<p className="muted">
© {new Date().getFullYear()} {t('brand.name')}
</p>
<nav className="flex gap-5" aria-label="Footer">
<Link href="/pricing" className="muted hover:opacity-80">
{t('nav.pricing')}
</Link>
<Link href="/legal/privacy" className="muted hover:opacity-80">
Privacy
</Link>
<Link href="/legal/terms" className="muted hover:opacity-80">
Terms
</Link>
</nav>
</div>
</footer>
);
}

49
components/SiteHeader.tsx Normal file
View file

@ -0,0 +1,49 @@
import Link from 'next/link';
import { getCurrentUser } from '@/lib/server/auth';
import { t } from '@/lib/i18n';
import { ThemeToggle } from './ThemeToggle';
export async function SiteHeader() {
const user = await getCurrentUser();
return (
<header className="border-b" style={{ borderColor: 'var(--border)' }}>
<div className="page flex h-16 items-center justify-between gap-4">
<Link href="/" className="text-lg font-bold tracking-tight">
{t('brand.name')}
</Link>
<nav className="hidden items-center gap-6 text-sm md:flex" aria-label="Main">
<Link href="/" className="muted hover:opacity-80">
{t('nav.home')}
</Link>
<Link href="/pricing" className="muted hover:opacity-80">
{t('nav.pricing')}
</Link>
{user && (
<Link href="/dashboard" className="muted hover:opacity-80">
{t('nav.dashboard')}
</Link>
)}
{user?.role === 'admin' && (
<Link href="/admin" className="muted hover:opacity-80">
{t('nav.admin')}
</Link>
)}
</nav>
<div className="flex items-center gap-2">
<ThemeToggle />
{user ? (
<form action="/api/auth/logout" method="post">
<button type="submit" className="btn-secondary">
{t('nav.logout')}
</button>
</form>
) : (
<Link href="/login" className="btn-primary">
{t('nav.login')}
</Link>
)}
</div>
</div>
</header>
);
}

View file

@ -0,0 +1,41 @@
'use client';
import { useEffect, useState } from 'react';
type Theme = 'light' | 'dark';
function apply(theme: Theme) {
document.documentElement.classList.toggle('dark', theme === 'dark');
try {
localStorage.setItem('theme', theme);
} catch {
/* ignore */
}
}
export function ThemeToggle() {
const [theme, setTheme] = useState<Theme>('light');
useEffect(() => {
const current = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
setTheme(current);
}, []);
function toggle() {
const next: Theme = theme === 'dark' ? 'light' : 'dark';
setTheme(next);
apply(next);
}
return (
<button
type="button"
className="btn-secondary"
onClick={toggle}
aria-label={theme === 'dark' ? 'Switch to light theme' : 'Switch to dark theme'}
>
<span aria-hidden>{theme === 'dark' ? '☾' : '☀'}</span>
<span className="hidden sm:inline">{theme === 'dark' ? 'Dark' : 'Light'}</span>
</button>
);
}

View file

@ -0,0 +1,43 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export function UpgradeButton({ plan, label, disabled }: { plan: string; label: string; disabled?: boolean }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function upgrade() {
setBusy(true);
setError(null);
try {
const res = await fetch('/api/billing/checkout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ plan }),
});
if (res.status === 401) {
router.push('/login?next=/pricing');
return;
}
if (!res.ok) throw new Error(`Checkout failed (${res.status})`);
const data = (await res.json()) as { url: string };
router.push(data.url.replace(/^https?:\/\/[^/]+/, ''));
router.refresh();
} catch (e) {
setError(e instanceof Error ? e.message : 'Checkout failed');
} finally {
setBusy(false);
}
}
return (
<div className="mt-6">
<button type="button" className="btn-primary w-full" onClick={upgrade} disabled={busy || disabled}>
{busy ? 'Working…' : label}
</button>
{error && <p className="mt-2 text-sm text-red-600">{error}</p>}
</div>
);
}

View file

@ -0,0 +1,44 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
export function UserActions({ id, role }: { id: string; role: string }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function update(nextRole: string) {
setBusy(true);
await fetch(`/api/admin/users/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ role: nextRole }),
});
setBusy(false);
router.refresh();
}
async function remove() {
if (!window.confirm('Delete this user? This cannot be undone.')) return;
setBusy(true);
await fetch(`/api/admin/users/${id}`, { method: 'DELETE' });
setBusy(false);
router.refresh();
}
return (
<div className="flex justify-end gap-2">
<button
type="button"
className="btn-secondary"
disabled={busy}
onClick={() => update(role === 'admin' ? 'user' : 'admin')}
>
{role === 'admin' ? 'Make user' : 'Make admin'}
</button>
<button type="button" className="btn-danger" disabled={busy} onClick={remove}>
Delete
</button>
</div>
);
}

68
components/ui/index.tsx Normal file
View file

@ -0,0 +1,68 @@
import type { ReactNode } from 'react';
export function Card({ title, children, actions }: { title?: ReactNode; children: ReactNode; actions?: ReactNode }) {
return (
<section className="card">
{(title || actions) && (
<header className="mb-4 flex items-center justify-between gap-4">
{title ? <h2 className="text-lg font-semibold">{title}</h2> : <span />}
{actions}
</header>
)}
{children}
</section>
);
}
const badgeTones: Record<string, string> = {
neutral: 'bg-slate-200 text-slate-800 dark:bg-slate-700 dark:text-slate-100',
success: 'bg-emerald-600 text-white',
warning: 'bg-amber-300 text-black',
danger: 'bg-red-600 text-white',
brand: 'bg-brand-600 text-white',
};
export function Badge({ children, tone = 'neutral' }: { children: ReactNode; tone?: keyof typeof badgeTones }) {
return <span className={`badge ${badgeTones[tone] ?? badgeTones.neutral}`}>{children}</span>;
}
const alertTones: Record<string, string> = {
info: 'border-brand-400 bg-brand-50 text-brand-700 dark:bg-brand-700/20 dark:text-brand-100',
success: 'border-emerald-500 bg-emerald-50 text-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-100',
warning: 'border-amber-400 bg-amber-50 text-black',
error: 'border-red-500 bg-red-50 text-red-800 dark:bg-red-900/30 dark:text-red-100',
};
export function Alert({ children, tone = 'info' }: { children: ReactNode; tone?: keyof typeof alertTones }) {
return (
<div role="status" className={`rounded-lg border px-4 py-3 text-sm ${alertTones[tone] ?? alertTones.info}`}>
{children}
</div>
);
}
export function Field({
label,
htmlFor,
hint,
children,
}: {
label: string;
htmlFor: string;
hint?: string;
children: ReactNode;
}) {
return (
<div>
<label className="label" htmlFor={htmlFor}>
{label}
</label>
{children}
{hint && <p className="muted mt-1 text-xs">{hint}</p>}
</div>
);
}
export function EmptyState({ children }: { children?: ReactNode }) {
return <p className="muted py-6 text-center text-sm">{children ?? 'Nothing here yet.'}</p>;
}

23
docker/Dockerfile Normal file
View file

@ -0,0 +1,23 @@
# Build stage
FROM node:22-alpine AS build
WORKDIR /app
RUN apk add --no-cache libc6-compat openssl
COPY package.json package-lock.json* ./
RUN npm ci || npm install
COPY . .
RUN npx prisma generate && npm run build
# Runtime stage
FROM node:22-alpine AS runtime
WORKDIR /app
ENV NODE_ENV=production
RUN apk add --no-cache openssl && addgroup -S app && adduser -S app -G app
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
COPY --from=build /app/prisma ./prisma
USER app
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD wget -qO- http://127.0.0.1:3000/api/health || exit 1
CMD ["node", "server.js"]

15
docker/docker-compose.yml Normal file
View file

@ -0,0 +1,15 @@
services:
app:
build:
context: ..
dockerfile: docker/Dockerfile
ports:
- "3000:3000"
environment:
DATABASE_URL: "file:./prod.db"
NEXT_PUBLIC_SITE_URL: "http://localhost:3000"
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/api/health"]
interval: 30s
timeout: 5s
retries: 3

20
lib/env.ts Normal file
View file

@ -0,0 +1,20 @@
import { z } from 'zod';
const schema = z.object({
DATABASE_URL: z.string().default('file:./dev.db'),
NEXT_PUBLIC_SITE_URL: z.string().url().default('http://localhost:3000'),
STRIPE_SECRET_KEY: z.string().optional().default(''),
STRIPE_WEBHOOK_SECRET: z.string().optional().default(''),
RESEND_API_KEY: z.string().optional().default(''),
EMAIL_FROM: z.string().default('Acme <noreply@example.com>'),
});
const parsed = schema.safeParse(process.env);
if (!parsed.success) {
console.error('Invalid environment:', parsed.error.flatten().fieldErrors);
throw new Error('Invalid environment configuration');
}
export const env = parsed.data;
export const isProd = process.env.NODE_ENV === 'production';

19
lib/i18n.ts Normal file
View file

@ -0,0 +1,19 @@
import en from '@/messages/en.json';
export const DEFAULT_LOCALE = 'en';
export const messages = { en } as const;
export type Locale = keyof typeof messages;
type Vars = Record<string, string | number>;
/** Tiny dictionary lookup: t('nav.pricing') with optional {name} interpolation. */
export function t(key: string, vars?: Vars, locale: Locale = DEFAULT_LOCALE): string {
const dict = messages[locale] as Record<string, unknown>;
const value = key.split('.').reduce<unknown>((acc, part) => {
if (acc && typeof acc === 'object') return (acc as Record<string, unknown>)[part];
return undefined;
}, dict);
if (typeof value !== 'string') return key;
if (!vars) return value;
return value.replace(/\{(\w+)\}/g, (_, name: string) => String(vars[name] ?? `{${name}}`));
}

10
lib/password.ts Normal file
View file

@ -0,0 +1,10 @@
import bcrypt from 'bcryptjs';
/** Pure password helpers (no server-only import) so they are unit-testable. */
export function hashPassword(plain: string): Promise<string> {
return bcrypt.hash(plain, 10);
}
export function verifyPassword(plain: string, hash: string): Promise<boolean> {
return bcrypt.compare(plain, hash);
}

41
lib/plans.ts Normal file
View file

@ -0,0 +1,41 @@
export type PlanId = 'free' | 'pro';
export type Plan = {
id: PlanId;
name: string;
price: number;
/** Monthly included usage per metric. */
limits: { seats: number; apiCalls: number };
features: string[];
};
export const PLANS: Record<PlanId, Plan> = {
free: {
id: 'free',
name: 'Free',
price: 0,
limits: { seats: 2, apiCalls: 1_000 },
features: ['Up to 2 members', '1,000 API calls / month', 'Community support'],
},
pro: {
id: 'pro',
name: 'Pro',
price: 29,
limits: { seats: 25, apiCalls: 100_000 },
features: ['Up to 25 members', '100,000 API calls / month', 'Priority support'],
},
};
export const PLAN_IDS: PlanId[] = ['free', 'pro'];
export function isPlanId(value: unknown): value is PlanId {
return value === 'free' || value === 'pro';
}
export function getPlan(value: unknown): Plan {
return isPlanId(value) ? PLANS[value] : PLANS.free;
}
export function withinLimit(plan: unknown, metric: keyof Plan['limits'], used: number): boolean {
return used < getPlan(plan).limits[metric];
}

15
lib/server/audit.ts Normal file
View file

@ -0,0 +1,15 @@
import 'server-only';
import { db } from './db';
export type AuditInput = { actorId?: string | null; action: string; target?: string; meta?: unknown };
export async function recordAudit({ actorId, action, target, meta }: AuditInput): Promise<void> {
await db.auditLog.create({
data: {
actorId: actorId ?? null,
action,
target: target ?? null,
meta: meta === undefined ? null : JSON.stringify(meta),
},
});
}

64
lib/server/auth.ts Normal file
View file

@ -0,0 +1,64 @@
import 'server-only';
import { cookies } from 'next/headers';
import { redirect } from 'next/navigation';
import { randomBytes } from 'node:crypto';
import { db } from './db';
export { hashPassword, verifyPassword } from '@/lib/password';
export const SESSION_COOKIE = 'w4c_session';
const TTL_MS = 30 * 24 * 60 * 60 * 1000;
export type SessionUser = {
id: string;
email: string;
name: string | null;
role: string;
};
/** Create a session row and set the httpOnly cookie (works in Route Handlers and Server Actions). */
export async function createSession(userId: string): Promise<string> {
const token = randomBytes(32).toString('hex');
const expiresAt = new Date(Date.now() + TTL_MS);
await db.session.create({ data: { token, userId, expiresAt } });
const store = await cookies();
store.set(SESSION_COOKIE, token, {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
path: '/',
expires: expiresAt,
});
return token;
}
export async function destroySession(): Promise<void> {
const store = await cookies();
const token = store.get(SESSION_COOKIE)?.value;
if (token) await db.session.deleteMany({ where: { token } });
store.delete(SESSION_COOKIE);
}
export async function getCurrentUser(): Promise<SessionUser | null> {
const store = await cookies();
const token = store.get(SESSION_COOKIE)?.value;
if (!token) return null;
const session = await db.session.findUnique({ where: { token }, include: { user: true } });
if (!session || session.expiresAt < new Date()) return null;
const { id, email, name, role } = session.user;
return { id, email, name, role };
}
/** Page guard: redirect to /login when unauthenticated. */
export async function requireUser(): Promise<SessionUser> {
const user = await getCurrentUser();
if (!user) redirect('/login');
return user;
}
/** Page guard: require the admin role. */
export async function requireAdmin(): Promise<SessionUser> {
const user = await requireUser();
if (user.role !== 'admin') redirect('/dashboard');
return user;
}

8
lib/server/db.ts Normal file
View file

@ -0,0 +1,8 @@
import { PrismaClient } from '@prisma/client';
// A single PrismaClient per process (avoids exhausting connections in dev HMR).
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const db = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db;

44
lib/server/email.ts Normal file
View file

@ -0,0 +1,44 @@
import 'server-only';
import { env } from '@/lib/env';
export type EmailMessage = { to: string; subject: string; html: string };
export type EmailResult = { id: string; provider: string };
export interface EmailProvider {
name: string;
send(message: EmailMessage): Promise<EmailResult>;
}
/** Default provider: no keys needed — logs the message and returns a synthetic id. */
export class LogProvider implements EmailProvider {
name = 'log';
async send(message: EmailMessage): Promise<EmailResult> {
console.log(`[email:log] to=${message.to} subject="${message.subject}"`);
return { id: `log_${Date.now().toString(36)}`, provider: this.name };
}
}
/** Real provider, activated by RESEND_API_KEY. */
export class ResendProvider implements EmailProvider {
name = 'resend';
constructor(private apiKey: string, private from: string) {}
async send(message: EmailMessage): Promise<EmailResult> {
const res = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: { Authorization: `Bearer ${this.apiKey}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ from: this.from, to: message.to, subject: message.subject, html: message.html }),
});
if (!res.ok) throw new Error(`Resend error ${res.status}: ${await res.text()}`);
const data = (await res.json()) as { id: string };
return { id: data.id, provider: this.name };
}
}
export function getEmail(): EmailProvider {
if (env.RESEND_API_KEY) return new ResendProvider(env.RESEND_API_KEY, env.EMAIL_FROM);
return new LogProvider();
}
export function sendEmail(message: EmailMessage): Promise<EmailResult> {
return getEmail().send(message);
}

86
lib/server/payments.ts Normal file
View file

@ -0,0 +1,86 @@
import 'server-only';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { env } from '@/lib/env';
export type CheckoutInput = { userId: string; email: string; plan: string; successUrl: string; cancelUrl: string };
export type CheckoutResult = { id: string; url: string };
export type WebhookEvent = { type: 'checkout.completed' | 'subscription.canceled' | 'ignored'; userId?: string; plan?: string };
export interface PaymentProvider {
name: string;
createCheckout(input: CheckoutInput): Promise<CheckoutResult>;
parseWebhook(rawBody: string, signature: string | null): Promise<WebhookEvent>;
}
/**
* Zero-config provider. It never redirects off-site: the checkout route marks the
* subscription active directly, so "plan → checkout → return → active" works with no keys.
*/
export class MockProvider implements PaymentProvider {
name = 'mock';
async createCheckout(input: CheckoutInput): Promise<CheckoutResult> {
const id = `mock_${input.userId.slice(0, 8)}_${input.plan}_${Date.now().toString(36)}`;
return { id, url: `${input.successUrl}?billing=success&provider=mock&plan=${encodeURIComponent(input.plan)}` };
}
async parseWebhook(rawBody: string): Promise<WebhookEvent> {
try {
const data = JSON.parse(rawBody) as { type?: string; userId?: string; plan?: string };
if (!data.type) return { type: 'ignored' };
return { type: data.type as WebhookEvent['type'], userId: data.userId, plan: data.plan };
} catch {
return { type: 'ignored' };
}
}
}
/** Stripe provider over the REST API (no SDK dependency), activated by STRIPE_SECRET_KEY. */
export class StripeProvider implements PaymentProvider {
name = 'stripe';
constructor(private secretKey: string, private webhookSecret: string) {}
async createCheckout(input: CheckoutInput): Promise<CheckoutResult> {
const body = new URLSearchParams();
body.set('mode', 'subscription');
body.set('success_url', input.successUrl);
body.set('cancel_url', input.cancelUrl);
body.set('client_reference_id', input.userId);
body.set('customer_email', input.email);
body.set('line_items[0][price]', input.plan);
body.set('line_items[0][quantity]', '1');
const res = await fetch('https://api.stripe.com/v1/checkout/sessions', {
method: 'POST',
headers: { Authorization: `Bearer ${this.secretKey}`, 'Content-Type': 'application/x-www-form-urlencoded' },
body,
});
if (!res.ok) throw new Error(`Stripe error ${res.status}: ${await res.text()}`);
const data = (await res.json()) as { id: string; url: string };
return { id: data.id, url: data.url };
}
async parseWebhook(rawBody: string, signature: string | null): Promise<WebhookEvent> {
if (!this.webhookSecret) throw new Error('STRIPE_WEBHOOK_SECRET is not configured');
if (!verifyStripeSignature(rawBody, signature, this.webhookSecret)) return { type: 'ignored' };
const event = JSON.parse(rawBody) as { type?: string; data?: { object?: { client_reference_id?: string } } };
if (event.type === 'checkout.session.completed') {
return { type: 'checkout.completed', userId: event.data?.object?.client_reference_id };
}
if (event.type === 'customer.subscription.deleted') return { type: 'subscription.canceled' };
return { type: 'ignored' };
}
}
// Minimal Stripe signature check (t=timestamp,v1=signature) to make webhooks idempotent + trusted.
function verifyStripeSignature(payload: string, header: string | null, secret: string): boolean {
if (!header) return false;
const parts = Object.fromEntries(header.split(',').map((p) => p.split('=') as [string, string]));
if (!parts.t || !parts.v1) return false;
const expected = createHmac('sha256', secret).update(`${parts.t}.${payload}`).digest('hex');
const a = Buffer.from(expected);
const b = Buffer.from(parts.v1);
return a.length === b.length && timingSafeEqual(a, b);
}
export function getPayments(): PaymentProvider {
if (env.STRIPE_SECRET_KEY) return new StripeProvider(env.STRIPE_SECRET_KEY, env.STRIPE_WEBHOOK_SECRET);
return new MockProvider();
}

21
lib/utils.ts Normal file
View file

@ -0,0 +1,21 @@
/** Join conditional class names. */
export function cn(...parts: Array<string | false | null | undefined>): string {
return parts.filter(Boolean).join(' ');
}
export function formatCurrency(amount: number, currency = 'USD'): string {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount);
}
export function formatDate(value: Date | string): string {
const d = typeof value === 'string' ? new Date(value) : value;
return new Intl.DateTimeFormat('en-US', { dateStyle: 'medium' }).format(d);
}
export function slugify(value: string): string {
return value
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
}

71
messages/en.json Normal file
View file

@ -0,0 +1,71 @@
{
"brand": { "name": "Acme" },
"nav": {
"home": "Home",
"pricing": "Pricing",
"dashboard": "Dashboard",
"admin": "Admin",
"login": "Sign in",
"register": "Create account",
"logout": "Sign out"
},
"home": {
"title": "Ship your product, not your boilerplate",
"subtitle": "A ready-to-run base app: authentication, roles, payments, admin and SEO — working on day one.",
"cta": "Get started",
"secondaryCta": "View pricing",
"featuresTitle": "Everything included",
"features": {
"auth": { "title": "Auth & roles", "body": "Email + password, httpOnly sessions, role guards on every route." },
"billing": { "title": "Payments", "body": "Checkout works with a mock provider and no keys; Stripe activates from env." },
"admin": { "title": "Admin panel", "body": "A role-gated shell with a dashboard and CRUD primitives." },
"seo": { "title": "SEO & a11y", "body": "Metadata, sitemap, robots and AA contrast out of the box." }
}
},
"pricing": {
"title": "Simple pricing",
"subtitle": "Start free. Upgrade when you grow.",
"perMonth": "/ month",
"choose": "Choose plan",
"current": "Current plan",
"upgraded": "Your plan is now active."
},
"auth": {
"loginTitle": "Sign in",
"registerTitle": "Create your account",
"email": "Email",
"password": "Password",
"name": "Name",
"submitLogin": "Sign in",
"submitRegister": "Create account",
"noAccount": "No account yet?",
"hasAccount": "Already have an account?",
"demoHint": "Demo: admin@example.com / user@example.com — password \"password\"."
},
"dashboard": {
"title": "Dashboard",
"welcome": "Welcome, {name}",
"plan": "Your plan",
"usage": "Usage"
},
"admin": {
"title": "Admin",
"overview": "Overview",
"users": "Users",
"audit": "Audit log",
"totalUsers": "Total users",
"activeSubs": "Active subscriptions",
"makeAdmin": "Make admin",
"makeUser": "Make user",
"delete": "Delete"
},
"common": {
"loading": "Loading…",
"empty": "Nothing here yet.",
"error": "Something went wrong.",
"retry": "Try again",
"cancel": "Cancel",
"save": "Save",
"delete": "Delete"
}
}

28
middleware.ts Normal file
View file

@ -0,0 +1,28 @@
import { NextResponse, type NextRequest } from 'next/server';
// Keep in sync with lib/server/auth.ts (middleware runs on the edge runtime and must not
// import the server-only auth module).
const SESSION_COOKIE = 'w4c_session';
const PROTECTED = ['/dashboard', '/admin'];
/**
* Coarse gate: unauthenticated visitors are redirected to /login before the page renders,
* so the response is a real 307 (not a streamed client redirect). Role checks stay in the
* page/layout guards, which remain authoritative.
*/
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const isProtected = PROTECTED.some((p) => pathname === p || pathname.startsWith(`${p}/`));
if (!isProtected) return NextResponse.next();
if (request.cookies.get(SESSION_COOKIE)) return NextResponse.next();
const url = request.nextUrl.clone();
url.pathname = '/login';
url.search = '';
url.searchParams.set('next', pathname);
return NextResponse.redirect(url);
}
export const config = {
matcher: ['/dashboard/:path*', '/admin/:path*'],
};

26
next.config.ts Normal file
View file

@ -0,0 +1,26 @@
import type { NextConfig } from 'next';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.dirname(fileURLToPath(import.meta.url));
const nextConfig: NextConfig = {
output: 'standalone',
outputFileTracingRoot: root,
poweredByHeader: false,
reactStrictMode: true,
async headers() {
return [
{
source: '/:path*',
headers: [
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
],
},
];
},
};
export default nextConfig;

8771
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

46
package.json Normal file
View file

@ -0,0 +1,46 @@
{
"name": "templates2-base-next",
"version": "2.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:e2e": "node tests/e2e/smoke.mjs",
"db:push": "prisma db push --skip-generate",
"db:seed": "prisma db seed",
"db:setup": "prisma db push --skip-generate && prisma db seed",
"postinstall": "prisma generate"
},
"prisma": {
"seed": "tsx prisma/seed.ts"
},
"dependencies": {
"@prisma/client": "^6.3.0",
"bcryptjs": "^2.4.3",
"next": "^15.2.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"zod": "^3.24.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.0.0",
"@types/bcryptjs": "^2.4.6",
"@types/node": "^22.10.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"eslint": "^8.57.1",
"eslint-config-next": "^15.2.0",
"postcss": "^8.4.49",
"prisma": "^6.3.0",
"tailwindcss": "^4.0.0",
"tsx": "^4.19.0",
"typescript": "^5.7.0",
"vitest": "^2.1.8"
}
}

5
postcss.config.mjs Normal file
View file

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

58
prisma/schema.prisma Normal file
View file

@ -0,0 +1,58 @@
// Templates2 Base — core data model shared by every case.
// SQLite in development (file:./dev.db); switch the datasource url to Postgres in production.
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id String @id @default(cuid())
email String @unique
passwordHash String
name String?
role String @default("user") // user | admin
createdAt DateTime @default(now())
sessions Session[]
subscription Subscription?
auditLogs AuditLog[]
}
model Session {
id String @id @default(cuid())
token String @unique
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
expiresAt DateTime
createdAt DateTime @default(now())
@@index([userId])
}
model Subscription {
id String @id @default(cuid())
userId String @unique
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
plan String @default("free") // free | pro
status String @default("active") // active | canceled | past_due
provider String @default("mock") // mock | stripe
currentPeriodEnd DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
model AuditLog {
id String @id @default(cuid())
actorId String?
actor User? @relation(fields: [actorId], references: [id], onDelete: SetNull)
action String
target String?
meta String?
createdAt DateTime @default(now())
@@index([actorId])
}

51
prisma/seed.ts Normal file
View file

@ -0,0 +1,51 @@
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
const db = new PrismaClient();
async function main() {
const password = await bcrypt.hash('password', 10);
const admin = await db.user.upsert({
where: { email: 'admin@example.com' },
update: { role: 'admin' },
create: { email: 'admin@example.com', name: 'Admin User', role: 'admin', passwordHash: password },
});
const user = await db.user.upsert({
where: { email: 'user@example.com' },
update: {},
create: { email: 'user@example.com', name: 'Demo User', role: 'user', passwordHash: password },
});
await db.subscription.upsert({
where: { userId: admin.id },
update: {},
create: { userId: admin.id, plan: 'pro', status: 'active', provider: 'mock' },
});
await db.subscription.upsert({
where: { userId: user.id },
update: {},
create: { userId: user.id, plan: 'free', status: 'active', provider: 'mock' },
});
if ((await db.auditLog.count()) === 0) {
await db.auditLog.createMany({
data: [
{ actorId: admin.id, action: 'seed', target: 'system', meta: 'Initial demo data' },
{ actorId: admin.id, action: 'user.create', target: user.email, meta: 'Seeded demo user' },
],
});
}
console.log(`Seeded: ${admin.email} (admin), ${user.email} (user) — password: "password"`);
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await db.$disconnect();
});

4
public/favicon.svg Normal file
View file

@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="32" height="32">
<rect width="32" height="32" rx="7" fill="#4f46e5"/>
<path d="M9 22V10h3.2l3.8 7 3.8-7H22v12h-2.6v-7.2L16 21.6h-1.2L11.6 14.8V22H9z" fill="#fff"/>
</svg>

After

Width:  |  Height:  |  Size: 242 B

75
tests/e2e/smoke.mjs Normal file
View file

@ -0,0 +1,75 @@
#!/usr/bin/env node
/**
* End-to-end smoke test — drives the running server over HTTP (no browser needed).
* Start the app first (`npm start`), then: QA_BASE_URL=http://127.0.0.1:3000 node tests/e2e/smoke.mjs
* The QA harness runs this automatically while the server is up.
*/
const BASE = (process.env.QA_BASE_URL || 'http://127.0.0.1:3000').replace(/\/$/, '');
const jar = new Map();
const failures = [];
function store(res) {
const list = typeof res.headers.getSetCookie === 'function' ? res.headers.getSetCookie() : [];
for (const raw of list) {
const pair = raw.split(';')[0];
const eq = pair.indexOf('=');
if (eq > 0) jar.set(pair.slice(0, eq), pair.slice(eq + 1));
}
}
async function req(path, { method = 'GET', body } = {}) {
const headers = {};
if (body !== undefined) headers['Content-Type'] = 'application/json';
if (jar.size) headers.cookie = [...jar.entries()].map(([k, v]) => `${k}=${v}`).join('; ');
const res = await fetch(BASE + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: 'manual' });
store(res);
const json = await res.clone().json().catch(() => null);
return { status: res.status, json };
}
function check(name, cond, detail = '') {
if (cond) console.log(` ok ${name}`);
else { console.log(` FAIL ${name}${detail ? ` — ${detail}` : ''}`); failures.push(name); }
}
async function run() {
const email = `smoke_${Date.now().toString(36)}@example.com`;
const health = await req('/api/health');
check('health 200', health.status === 200 && health.json?.status === 'ok', `status=${health.status}`);
const reg = await req('/api/auth/register', { method: 'POST', body: { email, password: 'password123', name: 'Smoke' } });
check('register 201', reg.status === 201, `status=${reg.status}`);
const regMe = await req('/api/auth/me');
check('session after register', regMe.status === 200 && regMe.json?.user?.email === email, `status=${regMe.status}`);
const newUserAdmin = await req('/api/admin/users');
check('non-admin blocked from admin API', newUserAdmin.status === 403, `status=${newUserAdmin.status}`);
const mailProvider = (await req('/api/billing/checkout', { method: 'POST', body: { plan: 'pro' } }));
check('mock checkout returns a url', mailProvider.status === 200 && String(mailProvider.json?.url).includes('billing=success'), `status=${mailProvider.status}`);
await req('/api/auth/logout', { method: 'POST' });
const afterLogout = await req('/api/auth/me');
check('logout clears session', afterLogout.status === 401, `status=${afterLogout.status}`);
const adminLogin = await req('/api/auth/login', { method: 'POST', body: { email: 'admin@example.com', password: 'password' } });
check('seeded admin can sign in', adminLogin.status === 200 && adminLogin.json?.user?.role === 'admin', `status=${adminLogin.status}`);
const users = await req('/api/admin/users');
check('admin sees users', users.status === 200 && Array.isArray(users.json?.users) && users.json.users.length >= 2, `status=${users.status}`);
const webhook = await req('/api/billing/webhook', { method: 'POST', body: { type: 'checkout.completed', userId: adminLogin.json?.user?.id, plan: 'pro' } });
check('mock webhook accepted', webhook.status === 200, `status=${webhook.status}`);
await req('/api/auth/logout', { method: 'POST' });
const userLogin = await req('/api/auth/login', { method: 'POST', body: { email: 'user@example.com', password: 'password' } });
check('seeded user can sign in', userLogin.status === 200 && userLogin.json?.user?.role === 'user', `status=${userLogin.status}`);
const forbidden = await req('/api/admin/users');
check('member forbidden on admin API', forbidden.status === 403, `status=${forbidden.status}`);
console.log(failures.length ? `\n${failures.length} check(s) failed` : '\nAll e2e checks passed');
process.exit(failures.length ? 1 : 0);
}
run().catch((e) => { console.error(e); process.exit(1); });

19
tests/unit/auth.test.ts Normal file
View file

@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest';
import { hashPassword, verifyPassword } from '@/lib/password';
import { slugify } from '@/lib/utils';
describe('password hashing', () => {
it('round-trips a password', async () => {
const hash = await hashPassword('password');
expect(hash).not.toBe('password');
expect(await verifyPassword('password', hash)).toBe(true);
expect(await verifyPassword('wrong', hash)).toBe(false);
});
});
describe('slugify', () => {
it('produces a url-safe slug', () => {
expect(slugify('Hello, World!')).toBe('hello-world');
expect(slugify(' Already-slug ')).toBe('already-slug');
});
});

22
tests/unit/plans.test.ts Normal file
View file

@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest';
import { getPlan, isPlanId, PLANS, withinLimit } from '@/lib/plans';
describe('plans', () => {
it('recognises valid plan ids only', () => {
expect(isPlanId('free')).toBe(true);
expect(isPlanId('pro')).toBe(true);
expect(isPlanId('enterprise')).toBe(false);
expect(isPlanId(undefined)).toBe(false);
});
it('falls back to the free plan for unknown values', () => {
expect(getPlan('nonsense').id).toBe('free');
expect(getPlan('pro').id).toBe('pro');
});
it('enforces usage limits inclusively below the cap', () => {
expect(withinLimit('free', 'seats', PLANS.free.limits.seats - 1)).toBe(true);
expect(withinLimit('free', 'seats', PLANS.free.limits.seats)).toBe(false);
expect(withinLimit('pro', 'apiCalls', 50_000)).toBe(true);
});
});

21
tsconfig.json Normal file
View file

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

1
tsconfig.tsbuildinfo Normal file

File diff suppressed because one or more lines are too long

12
vitest.config.ts Normal file
View file

@ -0,0 +1,12 @@
import { defineConfig } from 'vitest/config';
import { fileURLToPath } from 'node:url';
export default defineConfig({
resolve: {
alias: { '@': fileURLToPath(new URL('.', import.meta.url)) },
},
test: {
include: ['tests/unit/**/*.test.ts'],
environment: 'node',
},
});