Files
petvity/lib/auth/index.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

180 lines
6.3 KiB
TypeScript

import NextAuth from "next-auth";
import { DrizzleAdapter } from "@auth/drizzle-adapter";
import Credentials from "next-auth/providers/credentials";
import Google from "next-auth/providers/google";
import bcrypt from "bcryptjs";
import { and, eq, isNull, or } from "drizzle-orm";
import { getInstance } from "@/lib/db";
import { users } from "@/lib/db/schema";
import { loginSchema } from "@/lib/domain/auth";
import type { UserRole } from "./types";
import type { AdapterUser } from "next-auth/adapters";
import {
orangecatClient,
orangecatProvider,
withOrangecatIdentity,
type OrangecatUserStore,
} from "@bitbaum/accountkit/orangecat";
import "./types"; // ensure module augmentation is applied
import type { Session } from "next-auth";
import type { NextRequest } from "next/server";
import { roleAfterSignIn } from "./claims";
import { sharedAuth, sharedAuthEnabled } from "./shared/runtime";
import { sharedSession } from "./shared/session";
import { nextAuthClientCompat } from "./shared/bridge";
// Functional config pattern — DrizzleAdapter(getInstance()) is only called on
// the first actual request, never at module evaluation time. This prevents the
// Next.js build from throwing when DATABASE_URL is absent in CI/build env.
type Db = ReturnType<typeof getInstance>;
/** users.orangecat_sub is the only thing an OrangeCat login resolves on. */
function orangecatUserStore(db: Db): OrangecatUserStore<AdapterUser> {
return {
async findBySub(sub) {
const row = await db.query.users.findFirst({ where: eq(users.orangecatSub, sub) });
return row ?? null;
},
async emailTaken(email) {
const row = await db.query.users.findFirst({
where: eq(users.email, email),
columns: { id: true },
});
return Boolean(row);
},
async insert(data) {
const [row] = await db.insert(users).values(data).returning();
return row;
},
async attachSub(userId, sub) {
const rows = await db
.update(users)
.set({ orangecatSub: sub })
.where(
and(eq(users.id, userId), or(isNull(users.orangecatSub), eq(users.orangecatSub, sub))),
)
.returning({ id: users.id });
return rows.length > 0;
},
};
}
const nextAuth = NextAuth(() => {
const db = getInstance();
const orangecat = orangecatClient();
return {
adapter: withOrangecatIdentity(DrizzleAdapter(db), orangecatUserStore(db)),
session: { strategy: "jwt" },
pages: {
signIn: "/login",
error: "/login",
},
providers: [
// Absent (not broken) until the box has the client pair.
...(orangecat ? [orangecatProvider(orangecat)] : []),
// Kept for any Google-linked account; OrangeCat now carries Google in the UI.
// Mounted only with its client pair: without one Google answers
// invalid_client (client_id=undefined), which was live on 2026-10-30.
...(process.env.GOOGLE_CLIENT_ID && process.env.GOOGLE_CLIENT_SECRET
? [
Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
]
: []),
Credentials({
async authorize(credentials) {
const parsed = loginSchema.safeParse(credentials);
if (!parsed.success) return null;
const user = await db.query.users.findFirst({
where: eq(users.email, parsed.data.email),
});
if (!user?.password) return null;
const valid = await bcrypt.compare(parsed.data.password, user.password);
if (!valid) return null;
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
emailVerified: user.emailVerified,
} as {
id: string;
email: string;
name: string | null;
role: UserRole;
emailVerified: Date | null;
};
},
}),
],
callbacks: {
async jwt({ token, user, trigger, account }) {
if (user) {
token.id = user.id;
token.emailVerified = (user as { emailVerified?: Date | null }).emailVerified ?? null;
const existingRole = ((user as { role?: UserRole }).role ?? "pet_owner") as UserRole;
const effectiveRole = roleAfterSignIn(account?.provider, user.email, existingRole);
if (effectiveRole !== existingRole && user.id) {
await db.update(users).set({ role: effectiveRole }).where(eq(users.id, user.id));
}
token.role = effectiveRole;
}
// Re-read name + role from DB on any update trigger so settings changes
// and self-serve role upgrades take effect without re-login
if (trigger === "update" && token.id) {
const fresh = await db.query.users.findFirst({
where: eq(users.id, token.id as string),
columns: { name: true, role: true },
});
if (fresh) {
token.name = fresh.name;
token.role = fresh.role;
}
}
return token;
},
session({ session, token }) {
session.user.id = token.id as string;
session.user.role = token.role as UserRole;
session.user.emailVerified = (token.emailVerified as Date | null | undefined) ?? null;
// Propagate name from token (updated via trigger="update" when settings are saved)
if (token.name !== undefined) session.user.name = token.name as string | null;
return session;
},
},
};
});
export const { signIn, signOut } = nextAuth;
/**
* Who is signed in. One reader for both runtimes: AccountKit's shared session
* with AUTH_RUNTIME=accountkit, the Auth.js JWT otherwise. Same shape either
* way (docs/ACCOUNTKIT-MIGRATION.md).
*/
export async function auth(): Promise<Session | null> {
return sharedAuthEnabled() ? sharedSession() : nextAuth.auth();
}
/** /api/auth/*: AccountKit answers when the shared runtime is on. */
export const handlers = {
GET: async (request: NextRequest) =>
sharedAuthEnabled()
? ((await nextAuthClientCompat(request)) ?? sharedAuth.GET(request))
: nextAuth.handlers.GET(request),
POST: async (request: NextRequest) =>
sharedAuthEnabled()
? ((await nextAuthClientCompat(request)) ?? sharedAuth.POST(request))
: nextAuth.handlers.POST(request),
};