From c7def9465b9a5de2dfdd9b8c6f50d79c7ca70ed9 Mon Sep 17 00:00:00 2001 From: Gaurav Ghosh Date: Thu, 22 Oct 2026 18:25:18 +0530 Subject: [PATCH 1/3] feat: restore community forum in a Next.js workspace - Port legacy forum feeds, search, threads, voting, profiles, and moderation - Restore authentication without exposing login or signup links - Move schemas and migration history into the shared database package - Connect Astro navigation to the separately hosted forum - Add environment configuration and automatic Vercel migrations - Integrate workspace commands, CI checks, and forum/auth tests --- .env.example | 14 +- .github/workflows/ci.yml | 1 + README.md | 96 +- .../src/components/layout/NavLinks.astro | 13 + apps/nextjs/auth-schema.config.ts | 6 + apps/nextjs/eslint.config.mjs | 5 + apps/nextjs/next.config.ts | 8 + apps/nextjs/package.json | 48 + apps/nextjs/postcss.config.mjs | 1 + apps/nextjs/scripts/vercel-build.mjs | 33 + .../nextjs/src/app/api/auth/[...all]/route.ts | 29 + apps/nextjs/src/app/error.tsx | 17 + apps/nextjs/src/app/forum/actions.ts | 72 + apps/nextjs/src/app/forum/comments/page.tsx | 32 + apps/nextjs/src/app/forum/error.tsx | 12 + .../src/app/forum/item/[publicId]/page.tsx | 79 + apps/nextjs/src/app/forum/layout.tsx | 59 + apps/nextjs/src/app/forum/loading.tsx | 7 + apps/nextjs/src/app/forum/moderation/page.tsx | 63 + apps/nextjs/src/app/forum/page.tsx | 57 + apps/nextjs/src/app/forum/submit/page.tsx | 21 + .../src/app/forum/user/[username]/page.tsx | 73 + apps/nextjs/src/app/globals.css | 131 ++ apps/nextjs/src/app/icon.png | Bin 0 -> 4435 bytes apps/nextjs/src/app/layout.tsx | 63 + apps/nextjs/src/app/login/page.tsx | 15 + apps/nextjs/src/app/not-found.tsx | 12 + apps/nextjs/src/app/page.tsx | 5 + apps/nextjs/src/app/signup/page.tsx | 15 + apps/nextjs/src/components/auth/AuthForm.tsx | 224 +++ apps/nextjs/src/components/auth/AuthNav.tsx | 71 + .../src/components/common/ThemeScript.tsx | 8 + .../src/components/forum/ForumComments.tsx | 175 ++ .../src/components/forum/ForumControls.tsx | 279 +++ .../src/components/forum/ForumDisplay.tsx | 154 ++ .../nextjs/src/components/forum/ForumForm.tsx | 94 ++ .../src/components/forum/ForumTopics.tsx | 44 + .../src/components/layout/ThemeToggle.tsx | 30 + apps/nextjs/src/components/layout/styles.ts | 2 + apps/nextjs/src/components/ui/button.tsx | 57 + apps/nextjs/src/hooks/use-theme.ts | 50 + apps/nextjs/src/lib/auth-client.ts | 9 + apps/nextjs/src/lib/auth-errors.ts | 35 + apps/nextjs/src/lib/auth-options.ts | 41 + apps/nextjs/src/lib/auth.ts | 35 + apps/nextjs/src/lib/db.ts | 12 + apps/nextjs/src/lib/forum-store.ts | 436 +++++ apps/nextjs/src/lib/forum-validation.ts | 109 ++ apps/nextjs/src/lib/forum.ts | 22 + apps/nextjs/src/lib/theme.ts | 21 + apps/nextjs/src/styles/fonts.css | 16 + apps/nextjs/src/types/forum.ts | 59 + apps/nextjs/tests/auth.test.ts | 253 +++ apps/nextjs/tests/deployment.test.ts | 96 ++ apps/nextjs/tests/forum.test.ts | 520 ++++++ apps/nextjs/tsconfig.json | 18 + apps/nextjs/vercel.json | 6 + package.json | 14 +- packages/db/drizzle-dev.config.ts | 15 + packages/db/drizzle-prod.config.ts | 15 + packages/db/drizzle.config.ts | 16 + packages/db/drizzle/0000_init.sql | 56 + .../db/drizzle/0001_shallow_giant_man.sql | 136 ++ packages/db/drizzle/meta/0000_snapshot.json | 393 +++++ packages/db/drizzle/meta/0001_snapshot.json | 1493 +++++++++++++++++ packages/db/drizzle/meta/_journal.json | 20 + packages/db/package.json | 16 +- packages/db/scripts/forum-moderator.mjs | 46 + packages/db/src/schema/auth.ts | 95 ++ packages/db/src/schema/forum.ts | 263 +++ packages/db/src/schema/index.ts | 4 + packages/db/tests/migrations.test.ts | 68 + packages/env/load.d.mts | 5 + packages/env/src/index.ts | 7 +- pnpm-lock.yaml | 594 ++++++- turbo.json | 12 +- 76 files changed, 7055 insertions(+), 76 deletions(-) create mode 100644 apps/nextjs/auth-schema.config.ts create mode 100644 apps/nextjs/eslint.config.mjs create mode 100644 apps/nextjs/next.config.ts create mode 100644 apps/nextjs/package.json create mode 100644 apps/nextjs/postcss.config.mjs create mode 100644 apps/nextjs/scripts/vercel-build.mjs create mode 100644 apps/nextjs/src/app/api/auth/[...all]/route.ts create mode 100644 apps/nextjs/src/app/error.tsx create mode 100644 apps/nextjs/src/app/forum/actions.ts create mode 100644 apps/nextjs/src/app/forum/comments/page.tsx create mode 100644 apps/nextjs/src/app/forum/error.tsx create mode 100644 apps/nextjs/src/app/forum/item/[publicId]/page.tsx create mode 100644 apps/nextjs/src/app/forum/layout.tsx create mode 100644 apps/nextjs/src/app/forum/loading.tsx create mode 100644 apps/nextjs/src/app/forum/moderation/page.tsx create mode 100644 apps/nextjs/src/app/forum/page.tsx create mode 100644 apps/nextjs/src/app/forum/submit/page.tsx create mode 100644 apps/nextjs/src/app/forum/user/[username]/page.tsx create mode 100644 apps/nextjs/src/app/globals.css create mode 100644 apps/nextjs/src/app/icon.png create mode 100644 apps/nextjs/src/app/layout.tsx create mode 100644 apps/nextjs/src/app/login/page.tsx create mode 100644 apps/nextjs/src/app/not-found.tsx create mode 100644 apps/nextjs/src/app/page.tsx create mode 100644 apps/nextjs/src/app/signup/page.tsx create mode 100644 apps/nextjs/src/components/auth/AuthForm.tsx create mode 100644 apps/nextjs/src/components/auth/AuthNav.tsx create mode 100644 apps/nextjs/src/components/common/ThemeScript.tsx create mode 100644 apps/nextjs/src/components/forum/ForumComments.tsx create mode 100644 apps/nextjs/src/components/forum/ForumControls.tsx create mode 100644 apps/nextjs/src/components/forum/ForumDisplay.tsx create mode 100644 apps/nextjs/src/components/forum/ForumForm.tsx create mode 100644 apps/nextjs/src/components/forum/ForumTopics.tsx create mode 100644 apps/nextjs/src/components/layout/ThemeToggle.tsx create mode 100644 apps/nextjs/src/components/layout/styles.ts create mode 100644 apps/nextjs/src/components/ui/button.tsx create mode 100644 apps/nextjs/src/hooks/use-theme.ts create mode 100644 apps/nextjs/src/lib/auth-client.ts create mode 100644 apps/nextjs/src/lib/auth-errors.ts create mode 100644 apps/nextjs/src/lib/auth-options.ts create mode 100644 apps/nextjs/src/lib/auth.ts create mode 100644 apps/nextjs/src/lib/db.ts create mode 100644 apps/nextjs/src/lib/forum-store.ts create mode 100644 apps/nextjs/src/lib/forum-validation.ts create mode 100644 apps/nextjs/src/lib/forum.ts create mode 100644 apps/nextjs/src/lib/theme.ts create mode 100644 apps/nextjs/src/styles/fonts.css create mode 100644 apps/nextjs/src/types/forum.ts create mode 100644 apps/nextjs/tests/auth.test.ts create mode 100644 apps/nextjs/tests/deployment.test.ts create mode 100644 apps/nextjs/tests/forum.test.ts create mode 100644 apps/nextjs/tsconfig.json create mode 100644 apps/nextjs/vercel.json create mode 100644 packages/db/drizzle-dev.config.ts create mode 100644 packages/db/drizzle-prod.config.ts create mode 100644 packages/db/drizzle.config.ts create mode 100644 packages/db/drizzle/0000_init.sql create mode 100644 packages/db/drizzle/0001_shallow_giant_man.sql create mode 100644 packages/db/drizzle/meta/0000_snapshot.json create mode 100644 packages/db/drizzle/meta/0001_snapshot.json create mode 100644 packages/db/drizzle/meta/_journal.json create mode 100644 packages/db/scripts/forum-moderator.mjs create mode 100644 packages/db/src/schema/auth.ts create mode 100644 packages/db/src/schema/forum.ts create mode 100644 packages/db/src/schema/index.ts create mode 100644 packages/db/tests/migrations.test.ts create mode 100644 packages/env/load.d.mts diff --git a/.env.example b/.env.example index 648bb17..f752844 100644 --- a/.env.example +++ b/.env.example @@ -1,15 +1,25 @@ # Optional for the public site. Copy this file to .env at the repository root. # All workspace commands load root .env files; process variables take precedence. -# Neon PostgreSQL connection string; leave blank until database features are added. +# Neon runtime connection string; required for the forum, optional for Astro. # Example: postgresql://USER:PASSWORD@HOST/DATABASE?sslmode=require DATABASE_URL= -# Shared auth factories are ready for future use; no auth routes are mounted. +# Direct connections for migration and moderator commands. Never used interchangeably. +DEV_DATABASE_URL= +PROD_DATABASE_URL= + +# Authentication is hosted by the Next.js forum app. # Generate a secret with: openssl rand -base64 32 BETTER_AUTH_SECRET= BETTER_AUTH_URL=http://localhost:3000 +# Cross-app links. Development defaults to localhost ports 3000 and 4321. +# Set the forum's full /forum URL on the Astro Vercel project to show its nav link. +PUBLIC_FORUM_URL= +# Defaults to https://manipalosf.org in production. +PUBLIC_SITE_URL= + # Resend API key and a sender address on your verified domain. # Local email previews do not need these values. RESEND_API_KEY= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2151fed..7737516 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,6 +22,7 @@ jobs: - run: pnpm typecheck - run: pnpm lint - run: pnpm test + - run: pnpm db:check - run: pnpm build - run: node scripts/prepare-vercel.mjs - run: node scripts/verify-vercel.mjs diff --git a/README.md b/README.md index 8d94f03..5597fca 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Manipal OSF website -The Manipal OSF website lives in a pnpm and Turborepo monorepo modeled on [create-t3-turbo](https://github.com/t3-oss/create-t3-turbo). The public website uses Astro components and TypeScript browser scripts, with Vercel ISR for live GitHub data. +The Manipal OSF website lives in a pnpm and Turborepo monorepo modeled on [create-t3-turbo](https://github.com/t3-oss/create-t3-turbo). The public website uses Astro components and TypeScript browser scripts, with Vercel ISR for live GitHub data. A separate Next.js app hosts the community forum. ## Development @@ -11,7 +11,7 @@ pnpm install pnpm dev ``` -Open http://localhost:4321. The public website needs no service credentials. An optional `GITHUB_TOKEN` increases the GitHub API rate limit for statistics. +Open http://localhost:4321 for the public site or http://localhost:3000/forum for the forum. The public website needs no service credentials. An optional `GITHUB_TOKEN` increases the GitHub API rate limit for statistics. ```sh pnpm typecheck @@ -19,11 +19,13 @@ pnpm lint pnpm test pnpm build # Vercel deployment output pnpm build:local # Node production build -pnpm start # Serve the Node build on port 4321 +pnpm start # Serve the Astro Node build on port 4321 +pnpm start:forum # Serve the Next.js production build on port 3000 +pnpm dev:forum # Run just the forum pnpm format ``` -`dev` starts workspaces under `apps/`. `build`, `lint`, `typecheck`, and `test` use Turbo's dependency graph and cache. Development servers and email previews are uncached. Turbo caches `dist/`, `.astro/`, and `.vercel/output/` build artifacts. Environment changes invalidate task caches. +`dev` starts workspaces under `apps/`. `build`, `lint`, `typecheck`, and `test` use Turbo's dependency graph and cache. Development servers and email previews are uncached. Turbo caches `dist/`, `.astro/`, and `.vercel/output/`, and `.next/` build artifacts (excluding the Next.js compiler cache). Environment changes invalidate task caches. To target the website directly: @@ -37,6 +39,7 @@ pnpm build --filter=@apps/astro... | Location | Package | Responsibility | | ---------------- | ----------------- | ------------------------------------------------------------- | | `apps/astro` | `@apps/astro` | Astro website, content, public assets, and site-specific code | +| `apps/nextjs` | `@apps/nextjs` | Next.js community forum and authentication | | `packages/env` | `@packages/env` | T3 Env validation and root environment loading | | `packages/db` | `@packages/db` | Lazy Neon HTTP / Drizzle database clients | | `packages/auth` | `@packages/auth` | Configurable Better Auth factory | @@ -60,16 +63,20 @@ cp .env.example .env Import `env` from `@packages/env` in server code. T3 Env and Zod validate supplied values, treat empty strings as unset, and prevent access to server variables in browser code. The filesystem loader is separate at `@packages/env/load`; do not import it into application runtime code. -| Variable | Purpose | -| -------------------- | --------------------------------------------------------------- | -| `DATABASE_URL` | Optional Neon PostgreSQL URL (`postgres://` or `postgresql://`) | -| `BETTER_AUTH_SECRET` | Optional auth secret, at least 32 characters | -| `BETTER_AUTH_URL` | Optional auth origin for a future app instance | -| `RESEND_API_KEY` | Required when calling the website's `getResend()` | -| `RESEND_FROM_EMAIL` | Optional sender address on a verified Resend domain | -| `GITHUB_TOKEN` | Optional higher GitHub API rate limit | - -All current variables are server-side. Keep `.env*` ignored except the credential-free example. When adding variables, update the shared validation schema, example file, and Turbo environment inputs together. Future apps can compose their own validation from this package as their requirements diverge. +| Variable | Purpose | +| -------------------- | ----------------------------------------------------------------------------------------------------------- | +| `DATABASE_URL` | Optional Neon PostgreSQL URL (`postgres://` or `postgresql://`) | +| `BETTER_AUTH_SECRET` | Optional auth secret, at least 32 characters | +| `BETTER_AUTH_URL` | Forum auth origin, such as `http://localhost:3000` | +| `DEV_DATABASE_URL` | Direct development connection for migrations/moderator commands | +| `PROD_DATABASE_URL` | Direct production connection for migrations/moderator commands | +| `PUBLIC_FORUM_URL` | Full forum URL shown in Astro navigation; development defaults to `http://localhost:3000/forum` | +| `PUBLIC_SITE_URL` | Forum link back to Astro; defaults to local Astro in development and `https://manipalosf.org` in production | +| `RESEND_API_KEY` | Required when calling the website's `getResend()` | +| `RESEND_FROM_EMAIL` | Optional sender address on a verified Resend domain | +| `GITHUB_TOKEN` | Optional higher GitHub API rate limit | + +Only the two `PUBLIC_` link settings are public; credentials remain server-side. Migration URLs are read only by database tooling and never by application runtime code. Keep `.env*` ignored except the credential-free example. When adding variables, update the shared validation schema, example file, and Turbo environment inputs together. Future apps can compose their own validation from this package as their requirements diverge. ## Database and authentication @@ -77,15 +84,58 @@ All current variables are server-side. Keep `.env*` ignored except the credentia `@packages/auth` exports `createAuth({ db, schema, options })`. Supply an explicit Drizzle auth schema and app-specific `secret`, `baseURL`, and `trustedOrigins`; `options` also accepts Better Auth providers, plugins, and session configuration. The factory preserves plugin and additional-field inference, uses the PostgreSQL Drizzle adapter, and disables interactive transactions. It does not establish a global auth singleton or shared cookie domain. -The website does not instantiate auth or mount auth endpoints. Auth tables, login methods, schema generation, migrations, and login pages remain deferred. When implementing them, generate the schema from the final auth configuration, keep tables and migrations in `packages/db`, and mount the framework-specific handler inside the consuming app. Set each app's URL and trusted origins explicitly. Drizzle Kit is owned by the database package; migration commands will be added with the actual schema. +Astro does not mount authentication. The Next.js app instantiates the shared factory with the username plugin, app-specific origins, and schemas exported by `@packages/db/schema/auth`. The full schema is available at `@packages/db/schema`; the generic `createDb` and `getDb` APIs remain available. + +### Forum setup + +Set `DATABASE_URL`, `BETTER_AUTH_SECRET`, and `BETTER_AUTH_URL` at the repository root, with runtime and migration connections pointing to the same database. Set `DEV_DATABASE_URL` to the direct development connection, then run: + +```sh +pnpm db:migrate:dev +pnpm dev +``` + +Open `/signup` or `/login` directly on the Next.js origin. Signup requires a name, email, unique username (3–30 letters, digits, underscores, or dots), and an 8–128 character password. Login accepts email or username. Successful authentication returns to a validated local forum destination. Login/signup links are intentionally absent throughout the UI, including the auth forms. Signed-in members see their username and Logout. Anonymous visitors can read, but participation requires a session. + +The auth handler lives at `/api/auth/[...all]`. Cookies are scoped to the forum host; the two apps do not share sessions. OAuth, password recovery, email verification, and profile editing are not included. Without database credentials, forum pages display an unavailable message and auth endpoints return a sanitized 503. Both apps still build. + +### Forum behavior + +The forum ports `feat/forum-legacy`: Top/New/Ask/Show feeds, search, pagination, link/text submissions, threaded replies, reversible upvotes, author editing/deletion, member activity/karma, reports, and moderation. User content is plain text with HTTP(S) links. Deleted comments retain their replies; hidden discussions conceal their replies; locked discussions reject new replies. Forum and auth pages use `noindex` metadata. + +Internal forum keys remain PostgreSQL BIGINT identities mapped to JavaScript `bigint`; public post/comment IDs remain 16-character NanoIDs. Preserve the comment-integrity trigger, indexes, database constraints, atomic writes, and the per-account rate limits in the ported schema/store. Signup cannot grant moderator access. Moderator actions require reasons and create audit records. + +```sh +pnpm forum:moderator add your_username # DEV_DATABASE_URL +pnpm forum:moderator remove your_username +pnpm forum:moderator add your_username prod # PROD_DATABASE_URL +``` + +### Schema and migrations + +Schemas and committed migration history live in `packages/db`. The legacy SQL, journal, and snapshots are preserved, so an existing migrated database does not need to be recreated. Subsequent changes must use additive migrations; never rewrite applied history. Keep generated auth tables separate from forum tables. + +```sh +pnpm auth:generate # Pinned auth@1.7.7 CLI, matching Better Auth +pnpm db:generate # Generate SQL from the shared schema +pnpm db:check # Check migration-history consistency +pnpm db:migrate # Alias for db:migrate:dev +pnpm db:migrate:dev # Requires DEV_DATABASE_URL +pnpm db:migrate:prod # Requires PROD_DATABASE_URL +pnpm test:forum # Forum, auth, and deployment tests +pnpm test:auth +pnpm test:db +``` + +Generation and history checks do not connect to a database. Migration and moderator commands load root environment files for the explicitly selected stage, honor injected values, and never fall back to another stage's URL or `DATABASE_URL`. Tests apply migrations twice to disposable PGlite databases, exercising actual PostgreSQL queries without Neon credentials. ## Shared UI and Tailwind -Import Astro components from `@packages/ui/components/avatar` and `@packages/ui/components/badge`, and `cn` from `@packages/ui/lib/utils`. The unused button and extra avatar components have been removed. There is no React/shadcn component-generation command. +Import Astro components from `@packages/ui/components/avatar` and `@packages/ui/components/badge`, and `cn` from `@packages/ui/lib/utils`. The unused button and extra avatar components have been removed. Next.js keeps its React forum controls inside its own app and reuses the shared `cn` helper; the Astro component exports remain framework-specific. `@tooling/tailwind/styles.css` provides Tailwind v4, animation imports, theme tokens, the `data-theme` dark variant, common base styles, and shared UI source registration. Applications import this CSS and register their own source directory with `@source`. The website retains its Nord light and Catppuccin dark palettes and self-hosted Cascadia Code font. -The website ships Astro HTML with small browser modules for theme switching, map controls, reading progress, and timeline effects. MapLibre is loaded near the viewport, with campus links available when the map cannot load. React remains in the email package for React Email templates. +The website ships Astro HTML with small browser modules for theme switching, map controls, reading progress, and timeline effects. MapLibre is loaded near the viewport, with campus links available when the map cannot load. React is used by the Next.js forum and React Email templates. ## Email templates @@ -105,6 +155,14 @@ Content pages, feeds, metadata, and social preview PNGs are prerendered. Home an For a local production server, run `pnpm build:local`, then `pnpm start`. The local build explicitly selects `@astrojs/node`; the default `pnpm build` selects `@astrojs/vercel`. You can override the local server's interface and port using `HOST` and `PORT`. -Add future applications under `apps/`, name them `@apps/`, declare shared packages using `workspace:*`, and extend shared tooling. Each future app should have its own Vercel project, environment values, and app-specific deployment configuration. The root config remains specific to the current website; it does not deploy every app. For a project rooted in a new app directory, enable access to files outside that root so shared packages are available. Do not reuse the website's root build and output settings for another app. +Add future applications under `apps/`, name them `@apps/`, declare shared packages using `workspace:*`, and extend shared tooling. Each app has its own Vercel project, environment values, and app-specific deployment configuration. The root config remains specific to the current website; it does not deploy every app. For a project rooted in a new app directory, enable access to files outside that root so shared packages are available. Do not reuse the website's root build and output settings for another app. + +### Forum deployment + +Create a separate Vercel project with Root Directory `apps/nextjs`, framework Next.js, Node.js 24, and access to files outside the root directory enabled. Use its app-local `vercel.json`; the repository-root configuration deploys Astro. Set `ENABLE_EXPERIMENTAL_COREPACK=1` and the forum's database/auth settings. `BETTER_AUTH_URL` must match the browser-facing forum origin; use HTTPS in production. + +The forum's `build:vercel` script runs the shared history check, migrations, and the Next.js build in order. `VERCEL_ENV=production` selects `PROD_DATABASE_URL`; `preview` and `development` select `DEV_DATABASE_URL`. Missing/unknown environments, missing migration URLs, and failed steps stop deployment. Ordinary `pnpm build`, CI builds, and Astro deployments never migrate live databases. Migrations remain applied if a later build fails, so keep changes compatible with the prior deployment. + +Set `PUBLIC_FORUM_URL` on the Astro project to the deployed forum's full `/forum` URL. Without it, production Astro omits the Forum link; development uses localhost. `PUBLIC_SITE_URL` customizes the forum's link back to the public site. Cross-app navigation uses ordinary links; no proxy or shared cookie domain is needed. -GitHub Actions installs with the frozen lockfile and runs typecheck, lint, content/GitHub and service-package tests, the Vercel production build, and execution of the packaged server functions with GitHub offline. No live database, migration, email, or deployment is required for these checks. +GitHub Actions installs with the frozen lockfile and runs typecheck, lint, tests, migration-history checks, both production builds, and the existing Astro packaged-function checks. No live database, migration, email, or deployment is required for CI. Live deployment and Neon validation require separately configured infrastructure. diff --git a/apps/astro/src/components/layout/NavLinks.astro b/apps/astro/src/components/layout/NavLinks.astro index 182253f..e58edc7 100644 --- a/apps/astro/src/components/layout/NavLinks.astro +++ b/apps/astro/src/components/layout/NavLinks.astro @@ -1,6 +1,10 @@ --- import { activeNavItem, navItems } from '@/lib/site'; +import { env } from '@packages/env'; const active = activeNavItem(Astro.url.pathname); +const forumUrl = + env.PUBLIC_FORUM_URL ?? + (import.meta.env.DEV ? 'http://localhost:3000/forum' : undefined); --- { @@ -16,3 +20,12 @@ const active = activeNavItem(Astro.url.pathname); )) } +{ + forumUrl && ( +
  • + + Forum + +
  • + ) +} diff --git a/apps/nextjs/auth-schema.config.ts b/apps/nextjs/auth-schema.config.ts new file mode 100644 index 0000000..89914dd --- /dev/null +++ b/apps/nextjs/auth-schema.config.ts @@ -0,0 +1,6 @@ +import { betterAuth } from 'better-auth/minimal'; +import { authOptions } from './src/lib/auth-options'; + +// Tooling only: schema generation needs the plugins, never live credentials. +// The CLI's --adapter and --dialect flags select Drizzle/PostgreSQL. +export const auth = betterAuth(authOptions); diff --git a/apps/nextjs/eslint.config.mjs b/apps/nextjs/eslint.config.mjs new file mode 100644 index 0000000..cdcf865 --- /dev/null +++ b/apps/nextjs/eslint.config.mjs @@ -0,0 +1,5 @@ +import { defineConfig } from 'eslint/config'; +import next from '@next/eslint-plugin-next'; +import react from '@tooling/eslint/react'; + +export default defineConfig([...react, next.configs['core-web-vitals']]); diff --git a/apps/nextjs/next.config.ts b/apps/nextjs/next.config.ts new file mode 100644 index 0000000..9e75f8d --- /dev/null +++ b/apps/nextjs/next.config.ts @@ -0,0 +1,8 @@ +import type { NextConfig } from 'next'; +import '@packages/env'; + +const config: NextConfig = { + reactStrictMode: true, +}; + +export default config; diff --git a/apps/nextjs/package.json b/apps/nextjs/package.json new file mode 100644 index 0000000..7ae74d3 --- /dev/null +++ b/apps/nextjs/package.json @@ -0,0 +1,48 @@ +{ + "name": "@apps/nextjs", + "private": true, + "type": "module", + "scripts": { + "dev": "with-env development next dev --port 3000", + "build": "with-env production next build", + "build:vercel": "node scripts/vercel-build.mjs", + "start": "with-env production next start --port 3000", + "lint": "eslint .", + "typecheck": "with-env production next typegen && tsc --noEmit", + "test": "tsx --test tests/*.test.ts", + "auth:generate": "pnpm dlx auth@1.7.7 generate --config ./auth-schema.config.ts --adapter drizzle --dialect postgresql --output ../../packages/db/src/schema/auth.ts --yes" + }, + "dependencies": { + "@base-ui/react": "1.8.0", + "@fontsource-variable/cascadia-code": "5.3.0", + "@packages/auth": "workspace:*", + "@packages/db": "workspace:*", + "@packages/env": "workspace:*", + "@packages/ui": "workspace:*", + "better-auth": "1.7.7", + "class-variance-authority": "0.7.1", + "drizzle-orm": "catalog:", + "lucide-react": "1.52.0", + "nanoid": "6.0.2", + "next": "16.4.0", + "react": "catalog:", + "react-dom": "catalog:", + "server-only": "0.0.1", + "zod": "catalog:" + }, + "devDependencies": { + "@better-auth/drizzle-adapter": "1.7.7", + "@electric-sql/pglite": "0.5.10", + "@next/eslint-plugin-next": "16.4.0", + "@tooling/eslint": "workspace:*", + "@tooling/tailwind": "workspace:*", + "@tooling/typescript": "workspace:*", + "@types/node": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "eslint": "catalog:", + "postcss": "catalog:", + "tsx": "4.23.15", + "typescript": "catalog:" + } +} diff --git a/apps/nextjs/postcss.config.mjs b/apps/nextjs/postcss.config.mjs new file mode 100644 index 0000000..47b83e4 --- /dev/null +++ b/apps/nextjs/postcss.config.mjs @@ -0,0 +1 @@ +export { default } from '@tooling/tailwind/postcss'; diff --git a/apps/nextjs/scripts/vercel-build.mjs b/apps/nextjs/scripts/vercel-build.mjs new file mode 100644 index 0000000..10bccc5 --- /dev/null +++ b/apps/nextjs/scripts/vercel-build.mjs @@ -0,0 +1,33 @@ +import { spawnSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +let migration; +switch (process.env.VERCEL_ENV) { + case 'production': + migration = 'db:migrate:prod'; + break; + case 'preview': + case 'development': + migration = 'db:migrate:dev'; + break; + default: + console.error('VERCEL_ENV must be production, preview, or development.'); + process.exit(1); +} + +const root = fileURLToPath(new URL('../../../', import.meta.url)); +for (const args of [ + ['--filter', '@packages/db', 'db:check'], + ['--filter', '@packages/db', migration], + ['--filter', '@apps/nextjs', 'build'], +]) { + const result = spawnSync('pnpm', args, { cwd: root, stdio: 'inherit' }); + if (result.error) { + console.error( + `Unable to run pnpm ${args.join(' ')}: ${result.error.message}`, + ); + } + if (result.status !== 0) { + process.exit(result.status ?? 1); + } +} diff --git a/apps/nextjs/src/app/api/auth/[...all]/route.ts b/apps/nextjs/src/app/api/auth/[...all]/route.ts new file mode 100644 index 0000000..d38f036 --- /dev/null +++ b/apps/nextjs/src/app/api/auth/[...all]/route.ts @@ -0,0 +1,29 @@ +import { toNextJsHandler } from 'better-auth/next-js'; +import { AuthConfigurationError, getAuth } from '@/lib/auth'; + +export const runtime = 'nodejs'; + +async function handleAuth(request: Request) { + try { + const handlers = toNextJsHandler(getAuth()); + return await handlers[request.method === 'GET' ? 'GET' : 'POST'](request); + } catch (error) { + const unavailable = error instanceof AuthConfigurationError; + if (!unavailable) console.error('Authentication request failed.'); + + return Response.json( + { + code: unavailable ? 'AUTH_UNAVAILABLE' : 'AUTH_REQUEST_FAILED', + message: unavailable + ? 'Authentication is currently unavailable. Please try again later.' + : 'We could not complete your request. Please try again.', + }, + { + status: unavailable ? 503 : 500, + headers: { 'Cache-Control': 'no-store' }, + }, + ); + } +} + +export { handleAuth as GET, handleAuth as POST }; diff --git a/apps/nextjs/src/app/error.tsx b/apps/nextjs/src/app/error.tsx new file mode 100644 index 0000000..9092010 --- /dev/null +++ b/apps/nextjs/src/app/error.tsx @@ -0,0 +1,17 @@ +'use client'; + +export default function ErrorPage({ reset }: { reset: () => void }) { + return ( +
    +

    Something went wrong

    +

    Please try again in a moment.

    + +
    + ); +} diff --git a/apps/nextjs/src/app/forum/actions.ts b/apps/nextjs/src/app/forum/actions.ts new file mode 100644 index 0000000..e8dd77a --- /dev/null +++ b/apps/nextjs/src/app/forum/actions.ts @@ -0,0 +1,72 @@ +'use server'; + +import { revalidatePath } from 'next/cache'; +import { z } from 'zod'; +import { getForumContext } from '@/lib/forum'; +import { ForumError } from '@/lib/forum-store'; +import type { ForumActionResult } from '@/types/forum'; + +export async function forumAction(form: FormData): Promise { + try { + const { store, viewer } = await getForumContext(); + if (!store) return { error: 'The forum database is not configured yet.' }; + if (!viewer) + return { error: 'Your session has ended. Log in again to participate.' }; + const input = Object.fromEntries(form.entries()); + let location: string | undefined; + let success = 'Saved.'; + switch (input.action) { + case 'post': { + const id = await store.createPost(viewer, input); + location = `/forum/item/${id}`; + break; + } + case 'comment': { + const id = await store.createComment(viewer, { + ...input, + parentId: input.parentId || undefined, + }); + location = `/forum/item/${input.postId}#comment-${id}`; + success = 'Comment posted.'; + break; + } + case 'vote': + await store.vote(viewer, { ...input, voted: input.voted === 'true' }); + break; + case 'edit': + await store.edit(viewer, input); + break; + case 'delete': + await store.remove(viewer, input); + success = 'Deleted.'; + break; + case 'report': + await store.report(viewer, input); + success = 'Report received. Thank you.'; + break; + case 'moderate': + await store.moderate(viewer, { + ...input, + reportId: input.reportId || undefined, + }); + break; + default: + return { error: 'Unknown forum action.' }; + } + revalidatePath('/forum', 'layout'); + return { success, location }; + } catch (error) { + if (error instanceof z.ZodError) + return { error: error.issues[0]?.message ?? 'Check your input.' }; + if (error instanceof ForumError) return { error: error.message }; + // Keep database errors, statements, and account information out of responses. + console.error( + 'Forum action failed', + error instanceof Error ? error.name : 'Unknown error', + ); + return { + error: + 'Could not save your changes. Your draft is still here. Please try again.', + }; + } +} diff --git a/apps/nextjs/src/app/forum/comments/page.tsx b/apps/nextjs/src/app/forum/comments/page.tsx new file mode 100644 index 0000000..9744038 --- /dev/null +++ b/apps/nextjs/src/app/forum/comments/page.tsx @@ -0,0 +1,32 @@ +import { getForumContext } from '@/lib/forum'; +import { forumPage } from '@/lib/forum-store'; +import ForumComments from '@/components/forum/ForumComments'; +import { + ForumPagination, + ForumUnavailable, +} from '@/components/forum/ForumDisplay'; + +export default async function CommentsPage({ + searchParams, +}: { + searchParams: Promise<{ page?: string }>; +}) { + const { store, viewer, moderator } = await getForumContext(); + if (!store) return ; + const result = await store.comments({ + viewer, + page: forumPage((await searchParams).page), + }); + return ( + <> +

    Recent comments

    + + + + ); +} diff --git a/apps/nextjs/src/app/forum/error.tsx b/apps/nextjs/src/app/forum/error.tsx new file mode 100644 index 0000000..52d2c5a --- /dev/null +++ b/apps/nextjs/src/app/forum/error.tsx @@ -0,0 +1,12 @@ +'use client'; + +export default function ForumError({ reset }: { reset: () => void }) { + return ( +
    +

    We could not load the forum. Please try again.

    + +
    + ); +} diff --git a/apps/nextjs/src/app/forum/item/[publicId]/page.tsx b/apps/nextjs/src/app/forum/item/[publicId]/page.tsx new file mode 100644 index 0000000..e5a8f91 --- /dev/null +++ b/apps/nextjs/src/app/forum/item/[publicId]/page.tsx @@ -0,0 +1,79 @@ +import { notFound } from 'next/navigation'; +import { getForumContext } from '@/lib/forum'; +import { + PostRow, + ForumUnavailable, + SafeText, +} from '@/components/forum/ForumDisplay'; +import { ContentControls } from '@/components/forum/ForumControls'; +import ForumComments from '@/components/forum/ForumComments'; +import ForumForm from '@/components/forum/ForumForm'; + +export default async function ItemPage({ + params, +}: { + params: Promise<{ publicId: string }>; +}) { + const { publicId } = await params; + const { store, viewer, moderator } = await getForumContext(); + if (!store) return ; + const post = await store.post(publicId, viewer); + if (!post) notFound(); + const { comments } = await store.comments({ postId: publicId, viewer }); + return ( +
    +

    {post.title}

    + + {post.body && ( +
    + +
    + )} + {viewer && !post.deleted && ( +
    + +
    + )} +
    + {post.hidden ? ( +

    + This discussion has been hidden by a moderator. +

    + ) : post.deleted ? ( +

    + The author deleted this submission. Existing replies remain below. +

    + ) : post.locked ? ( +

    + This discussion is locked to new replies. +

    + ) : viewer ? ( + +