Files
petvity/proxy.ts
T
CatoandClaude 2d3609c13e feat(auth): stage AccountKit beside Auth.js, switch off (#156)
Petvity moves from Auth.js to @bitbaum/accountkit one reversible step at a
time, as evig and kivvi do. Nothing changes while AUTH_RUNTIME is unset.

- Migration 0008: AccountKit's tables under an `auth_` prefix, plus the
  users <-> auth_users mirror functions, inert until attached.
- scripts/db/accountkit-import.sql: accounts under their own ids, bcrypt
  hashes byte for byte, verification kept, orangecat_sub as an `orangecat`
  account row; refuses collisions, drift or a live shared runtime, then
  attaches the triggers. The rehearsal CLI always rolls back.
- lib/auth/shared/: the runtime (ids: 'uuid', legacy bcrypt, AccountKit
  0.16.0), a session reader re-read from `users` on every request, a bridge
  that answers next-auth/react including "Sign in with OrangeCat", and a
  Petvity row for a person AccountKit creates itself. AccountKit's own
  credential endpoints stay closed; Petvity's writers stay the only ones.
- lib/auth/claims.ts: the ADMIN_EMAILS promotion rule, written once.
- The proxy has one routing function and two session sources.
- browser-smoke.yml runs the account journey once per runtime; the
  AccountKit leg first runs the rehearsal and the real-database journeys.

docs/ACCOUNTKIT-MIGRATION.md records what is left before switching.


Claude-Session: https://claude.ai/code/session_019MDtmud6zcK4rStBGmYSML

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 08:31:55 +01:00

127 lines
5.5 KiB
TypeScript

import { auth } from "@/lib/auth/edge";
import createIntlMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";
import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
import { POST_LOGIN_PATH } from "@/lib/config/auth";
import { withoutSessionCookie } from "@/lib/auth/session-cookie";
import { sharedAuthEnabled } from "@/lib/auth/shared/runtime";
import { sharedSessionFor } from "@/lib/auth/shared/session";
import type { Session } from "next-auth";
const intlMiddleware = createIntlMiddleware(routing);
// All portal routes live under /portal/ so this stays a single prefix entry.
// IMPORTANT: New portal routes must be nested under /portal/ — do not add
// individual paths here.
const PORTAL_PREFIXES = ["/portal", "/admin"];
// API routes that require authentication (pet/health data, etc.)
// /api/auth/* is handled separately (always public)
// /api/account (registration) and /api/public/* are intentionally public
const PRIVATE_API_PREFIXES = [
"/api/pets",
// Health *data*. The liveness probe is /api/healthz, deliberately outside
// this prefix so it stays reachable without a session.
"/api/health",
"/api/vaccinations",
"/api/medications",
"/api/vets",
"/api/sitters",
"/api/groomers",
"/api/sellers",
"/api/bookings",
"/api/availability",
// Writes files to disk — never reachable without a session.
"/api/uploads",
"/api/reviews",
// Account orders. /api/shop/* is the guest counterpart and is deliberately
// NOT listed: requiring a session there would delete guest checkout, which
// is the whole point of it. It self-guards with a rate limit and, for
// payment, an unguessable order token.
"/api/orders",
// /api/cron/* is intentionally NOT gated — cron routes self-authenticate via
// the CRON_SECRET bearer (box systemd timers; loki install-app-crons.sh).
"/api/admin",
];
// Non-localized auth pages — bypass intl routing entirely
// (/demo signs visitors into the shared demo account; logged-in users are
// bounced to their dashboard like on any auth page)
const AUTH_PATHS = ["/login", "/register", "/forgot-password", "/reset-password", "/demo"];
// Non-localized public pages — bypass intl routing AND don't redirect logged-in users.
// /unsubscribe is here so the email link works whether the recipient is logged in or not.
const PUBLIC_BYPASS_PATHS = ["/unsubscribe"];
/** Petvity's routing for one request, given who (if anyone) is signed in. */
function route(req: NextRequest, session: Session | null) {
const { pathname } = req.nextUrl;
const dest = session?.user?.role === "admin" ? "/admin/users" : POST_LOGIN_PATH;
// ── NextAuth API routes — always public ──────────────────────────────────
if (pathname.startsWith("/api/auth")) {
return NextResponse.next();
}
// ── Portal / admin / private API ─────────────────────────────────────────
const isPrivate =
PORTAL_PREFIXES.some((p) => pathname === p || pathname.startsWith(p + "/")) ||
PRIVATE_API_PREFIXES.some((p) => pathname === p || pathname.startsWith(p + "/"));
if (isPrivate) {
if (!session) {
const loginUrl = new URL("/login", req.url);
loginUrl.searchParams.set("returnTo", pathname);
return NextResponse.redirect(loginUrl);
}
if (pathname.startsWith("/admin") && session.user.role !== "admin") {
return NextResponse.redirect(new URL(POST_LOGIN_PATH, req.url));
}
return NextResponse.next();
}
// ── Non-localized auth pages ─────────────────────────────────────────────
// These live at /login, /register etc. — serve directly, skip intl routing.
// Redirect already-logged-in users to their dashboard.
if (AUTH_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
if (session) return NextResponse.redirect(new URL(dest, req.url));
return NextResponse.next();
}
// ── Non-localized public pages — pass through regardless of auth state ──
if (PUBLIC_BYPASS_PATHS.some((p) => pathname === p || pathname.startsWith(p + "/"))) {
return NextResponse.next();
}
// ── API routes not already handled above — pass through, no locale routing
if (pathname.startsWith("/api/")) {
return NextResponse.next();
}
// ── Marketing site: locale routing ───────────────────────────────────────
return intlMiddleware(req);
}
// As a proxy, Auth.js calls this with (request, event) and always resolves to
// a Response; its overloads only describe the route-handler form.
const authJsProxy = auth((req) => route(req, req.auth)) as unknown as (
req: NextRequest,
ev: NextFetchEvent,
) => Promise<Response>;
// Reads the session, never re-issues it: see lib/auth/session-cookie.ts. With
// AUTH_RUNTIME=accountkit the session is a database row read through AccountKit
// (docs/ACCOUNTKIT-MIGRATION.md); otherwise the Auth.js JWT.
export default async function proxy(req: NextRequest, ev: NextFetchEvent) {
const response = sharedAuthEnabled()
? await route(req, await sharedSessionFor(req.headers))
: await authJsProxy(req, ev);
return withoutSessionCookie(response);
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon|icon|opengraph-image|robots\\.txt|sitemap\\.xml|.*\\..*).*)",
],
};