diff --git a/apps/api/package.json b/apps/api/package.json index ec2a70a..55c1c9d 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -12,18 +12,17 @@ "test": "vitest run" }, "dependencies": { + "@aws-sdk/client-s3": "^3.800.0", + "@aws-sdk/s3-request-presigner": "^3.800.0", "@groombook/db": "workspace:*", "@groombook/types": "workspace:*", "@hono/node-server": "^1.13.7", - "@hono/zod-validator": "^0.4.3", + "@hono/zod-validator": "^0.7.6", + "better-auth": "^1.5.6", "hono": "^4.6.17", - "jose": "^5.9.6", "node-cron": "^3.0.3", "nodemailer": "^6.9.16", - "openid-client": "^6.1.7", - "zod": "^3.24.1", - "@aws-sdk/client-s3": "^3.800.0", - "@aws-sdk/s3-request-presigner": "^3.800.0" + "zod": "^4.3.6" }, "devDependencies": { "@types/node": "^22.10.7", diff --git a/apps/api/src/__tests__/groomerIsolation.test.ts b/apps/api/src/__tests__/groomerIsolation.test.ts index f1bd97d..04f087f 100644 --- a/apps/api/src/__tests__/groomerIsolation.test.ts +++ b/apps/api/src/__tests__/groomerIsolation.test.ts @@ -15,6 +15,7 @@ import type { StaffRow } from "../middleware/rbac.js"; const MANAGER: StaffRow = { id: "staff-manager-id", oidcSub: "oidc-manager-sub", + userId: null, role: "manager", name: "Manager McManager", email: "manager@example.com", diff --git a/apps/api/src/__tests__/impersonation.test.ts b/apps/api/src/__tests__/impersonation.test.ts index 2ba232f..de7688d 100644 --- a/apps/api/src/__tests__/impersonation.test.ts +++ b/apps/api/src/__tests__/impersonation.test.ts @@ -1,6 +1,5 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { Hono } from "hono"; -import type { JwtPayload } from "../middleware/auth.js"; import type { AppEnv, StaffRow } from "../middleware/rbac.js"; import { buildStaff } from "@groombook/db/factories"; @@ -167,7 +166,7 @@ function createApp( if (!staffRow) { return c.json({ error: "Forbidden: no staff record found for authenticated user" }, 403); } - c.set("jwtPayload", { sub: staffRow.oidcSub } as JwtPayload); + c.set("jwtPayload", { sub: staffRow.oidcSub } as { sub: string; email?: string; name?: string }); c.set("staff", staffRow as unknown as StaffRow); await next(); }); diff --git a/apps/api/src/__tests__/petPhotos.test.ts b/apps/api/src/__tests__/petPhotos.test.ts index b4d2d6b..19b8564 100644 --- a/apps/api/src/__tests__/petPhotos.test.ts +++ b/apps/api/src/__tests__/petPhotos.test.ts @@ -7,6 +7,7 @@ import type { AppEnv, StaffRow } from "../middleware/rbac.js"; const MANAGER: StaffRow = { id: "staff-manager-id", oidcSub: "oidc-manager-sub", + userId: null, role: "manager", name: "Manager McManager", email: "manager@example.com", diff --git a/apps/api/src/__tests__/rbac.test.ts b/apps/api/src/__tests__/rbac.test.ts index b052507..e213ed7 100644 --- a/apps/api/src/__tests__/rbac.test.ts +++ b/apps/api/src/__tests__/rbac.test.ts @@ -8,6 +8,7 @@ import type { AppEnv, StaffRow } from "../middleware/rbac.js"; const MANAGER: StaffRow = { id: "staff-manager-id", oidcSub: "oidc-manager-sub", + userId: "ba-user-manager", role: "manager", name: "Manager McManager", email: "manager@example.com", @@ -21,6 +22,7 @@ const RECEPTIONIST: StaffRow = { ...MANAGER, id: "staff-receptionist-id", oidcSub: "oidc-receptionist-sub", + userId: "ba-user-receptionist", role: "receptionist", name: "Receptionist Rita", email: "receptionist@example.com", @@ -30,6 +32,7 @@ const GROOMER: StaffRow = { ...MANAGER, id: "staff-groomer-id", oidcSub: "oidc-groomer-sub", + userId: "ba-user-groomer", role: "groomer", name: "Groomer Gary", email: "groomer@example.com", @@ -89,7 +92,7 @@ function buildApp( ) { const app = new Hono(); app.use("*", async (c, next) => { - c.set("jwtPayload", { sub: staffLookupResult?.oidcSub ?? "unknown-sub" }); + c.set("jwtPayload", { sub: staffLookupResult?.userId ?? "unknown-sub" }); await next(); }); app.use("*", middleware); @@ -106,7 +109,7 @@ function buildWithStaff( ) { const app = new Hono(); app.use("*", async (c, next) => { - c.set("jwtPayload", { sub: staffRow.oidcSub ?? "" }); + c.set("jwtPayload", { sub: staffRow.userId ?? "" }); c.set("staff", staffRow); await next(); }); @@ -165,7 +168,7 @@ describe("resolveStaffMiddleware", () => { }); const res = await app.request("/test", { - headers: { "X-Dev-User-Id": GROOMER.oidcSub! }, + headers: { "X-Dev-User-Id": GROOMER.id }, }); expect(res.status).toBe(200); expect(capturedStaff!.role).toBe("groomer"); diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index f20f277..275c797 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -2,6 +2,8 @@ import { serve } from "@hono/node-server"; import { Hono } from "hono"; import { logger } from "hono/logger"; import { cors } from "hono/cors"; +import { toNodeHandler } from "better-auth/node"; +import { auth } from "./lib/auth.js"; import { clientsRouter } from "./routes/clients.js"; import { petsRouter } from "./routes/pets.js"; import { servicesRouter } from "./routes/services.js"; @@ -65,14 +67,24 @@ app.get("/api/branding", async (c) => { // Public iCal calendar feed — token auth in URL, no auth middleware required app.route("/api/calendar", calendarRouter); + +// Better-Auth handler — public, handles OAuth callbacks, session management +// Mounted BEFORE auth middleware so it's accessible without authentication +app.on(["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"], "/api/auth/**", (c) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const { incoming, outgoing } = c.env as any; + return toNodeHandler(auth)(incoming, outgoing); +}); + // Protected API routes const api = app.basePath("/api"); api.use("*", authMiddleware); api.use("*", resolveStaffMiddleware); // ── Role guards ──────────────────────────────────────────────────────────────── -// Manager-only: staff, admin settings, reports, invoices, impersonation -api.use("/staff/*", requireRole("manager")); +// Staff: all roles may read; only managers may write (POST/PUT/PATCH/DELETE) +api.on(["POST", "PUT", "PATCH", "DELETE"], "/staff/*", requireRole("manager")); +// Manager-only: admin settings, reports, invoices, impersonation api.use("/admin/*", requireRole("manager")); api.use("/reports/*", requireRole("manager")); api.use("/invoices/*", requireRole("manager")); diff --git a/apps/api/src/lib/auth.ts b/apps/api/src/lib/auth.ts new file mode 100644 index 0000000..3dda63b --- /dev/null +++ b/apps/api/src/lib/auth.ts @@ -0,0 +1,48 @@ +import { betterAuth } from "better-auth"; +import { drizzleAdapter } from "better-auth/adapters/drizzle"; +import { genericOAuth } from "better-auth/plugins"; +import { getDb } from "@groombook/db"; + +const OIDC_ISSUER = process.env.OIDC_ISSUER; +const OIDC_CLIENT_ID = process.env.OIDC_CLIENT_ID; +const OIDC_CLIENT_SECRET = process.env.OIDC_CLIENT_SECRET; +const BETTER_AUTH_SECRET = process.env.BETTER_AUTH_SECRET; +const BETTER_AUTH_URL = process.env.BETTER_AUTH_URL ?? "http://localhost:3000"; + +if (!BETTER_AUTH_SECRET && process.env.AUTH_DISABLED !== "true") { + throw new Error( + "[FATAL] BETTER_AUTH_SECRET environment variable is required when auth is enabled" + ); +} + +export const auth = betterAuth({ + database: drizzleAdapter(getDb(), { + provider: "pg", + }), + secret: BETTER_AUTH_SECRET, + baseURL: BETTER_AUTH_URL, + plugins: [ + genericOAuth({ + config: [ + { + providerId: "authentik", + clientId: OIDC_CLIENT_ID ?? "", + clientSecret: OIDC_CLIENT_SECRET ?? "", + discoveryUrl: OIDC_ISSUER + ? `${OIDC_ISSUER}/.well-known/openid-configuration` + : undefined, + scopes: ["openid", "profile", "email"], + }, + ], + }), + ], + session: { + expiresIn: 60 * 60 * 24 * 7, // 7 days + updateAge: 60 * 60 * 24, // 1 day + cookieCache: { + enabled: true, + maxAge: 5 * 60, // 5 minutes + }, + }, + trustedOrigins: [process.env.CORS_ORIGIN ?? "http://localhost:5173"], +}); diff --git a/apps/api/src/middleware/auth.ts b/apps/api/src/middleware/auth.ts index 44f4100..66ec3d4 100644 --- a/apps/api/src/middleware/auth.ts +++ b/apps/api/src/middleware/auth.ts @@ -1,34 +1,18 @@ import type { MiddlewareHandler } from "hono"; -import { createRemoteJWKSet, jwtVerify } from "jose"; +import { auth } from "../lib/auth.js"; -// Authentik OIDC configuration — loaded from env at startup -const OIDC_ISSUER = process.env.OIDC_ISSUER; -const OIDC_AUDIENCE = process.env.OIDC_AUDIENCE; - -let jwks: ReturnType | null = null; - -function getJwks() { - if (!OIDC_ISSUER) throw new Error("OIDC_ISSUER is not set"); - if (!jwks) { - jwks = createRemoteJWKSet( - new URL(`${OIDC_ISSUER}/application/o/groombook/jwks/`) - ); - } - return jwks; +export interface AuthUser { + id: string; + email: string; + name: string; } -export interface JwtPayload { - sub: string; - email?: string; - name?: string; -} - -// Guard: refuse to start with AUTH_DISABLED in production (fixes #22). +// Guard: refuse to start with AUTH_DISABLED in production. if (process.env.AUTH_DISABLED === "true") { if (process.env.NODE_ENV === "production") { console.error( "[FATAL] AUTH_DISABLED=true is not allowed in production. " + - "Remove AUTH_DISABLED from your environment and configure OIDC_ISSUER." + "Remove AUTH_DISABLED from your environment and configure Better-Auth." ); process.exit(1); } @@ -42,27 +26,24 @@ export const authMiddleware: MiddlewareHandler = async (c, next) => { if (process.env.AUTH_DISABLED === "true") { const devUserId = c.req.header("X-Dev-User-Id"); const sub = devUserId ?? "dev-user"; - c.set("jwtPayload", { sub } as JwtPayload); + c.set("jwtPayload", { sub } as { sub: string }); await next(); return; } - const authorization = c.req.header("Authorization"); - if (!authorization?.startsWith("Bearer ")) { + const session = await auth.api.getSession({ + headers: c.req.raw.headers, + }); + + if (!session) { return c.json({ error: "Unauthorized" }, 401); } - const token = authorization.slice(7); - - try { - const { payload } = await jwtVerify(token, getJwks(), { - issuer: OIDC_ISSUER, - audience: OIDC_AUDIENCE, - }); - - c.set("jwtPayload", payload as JwtPayload); - await next(); - } catch { - return c.json({ error: "Invalid or expired token" }, 401); - } + // Set jwtPayload with sub = Better-Auth user ID for backward compat with resolveStaffMiddleware + c.set("jwtPayload", { + sub: session.user.id, + email: session.user.email, + name: session.user.name, + }); + await next(); }; diff --git a/apps/api/src/middleware/rbac.ts b/apps/api/src/middleware/rbac.ts index 24a6753..1bc2228 100644 --- a/apps/api/src/middleware/rbac.ts +++ b/apps/api/src/middleware/rbac.ts @@ -1,13 +1,12 @@ import type { MiddlewareHandler } from "hono"; import { eq, getDb, staff } from "@groombook/db"; -import type { JwtPayload } from "./auth.js"; export type StaffRole = "groomer" | "receptionist" | "manager"; export type StaffRow = typeof staff.$inferSelect; export interface AppEnv { Variables: { - jwtPayload: JwtPayload; + jwtPayload: { sub: string; email?: string; name?: string }; staff: StaffRow; }; } @@ -16,8 +15,8 @@ export interface AppEnv { * Resolves the authenticated staff record from the DB and stores it in context. * Must be applied after authMiddleware on all protected routes. * - * Dev mode (AUTH_DISABLED=true): resolves staff by X-Dev-User-Id header (treated - * as oidcSub), or falls back to the first manager in the DB. + * Dev mode (AUTH_DISABLED=true): resolves staff by X-Dev-User-Id header (Better-Auth + * user ID), or falls back to the first manager in the DB. */ export const resolveStaffMiddleware: MiddlewareHandler = async ( c, @@ -41,34 +40,55 @@ export const resolveStaffMiddleware: MiddlewareHandler = async ( await next(); return; } - // Treat X-Dev-User-Id as the oidcSub + // Treat X-Dev-User-Id as the Better-Auth user ID first const [row] = await db .select() .from(staff) - .where(eq(staff.oidcSub, devUserId)); - if (!row) { + .where(eq(staff.userId, devUserId)); + if (row) { + c.set("staff", row); + await next(); + return; + } + // Fallback: if userId is null, treat X-Dev-User-Id as staff.id (dev login + // may send the primary key for staff records that predate the userId field) + const [fallbackRow] = await db + .select() + .from(staff) + .where(eq(staff.id, devUserId)); + if (!fallbackRow) { return c.json( { error: "Forbidden: no staff record found for X-Dev-User-Id" }, 403 ); } - c.set("staff", row); + c.set("staff", fallbackRow); await next(); return; } const jwt = c.get("jwtPayload"); const [row] = await db + .select() + .from(staff) + .where(eq(staff.userId, jwt.sub)); + if (row) { + c.set("staff", row); + await next(); + return; + } + // Fallback: staff records that predate the userId field may still have oidcSub + const [fallbackRow] = await db .select() .from(staff) .where(eq(staff.oidcSub, jwt.sub)); - if (!row) { + if (!fallbackRow) { return c.json( { error: "Forbidden: no staff record found for authenticated user" }, 403 ); } - c.set("staff", row); + c.set("staff", fallbackRow); await next(); }; diff --git a/apps/api/src/routes/appointmentGroups.ts b/apps/api/src/routes/appointmentGroups.ts index e2790a4..8ecbb45 100644 --- a/apps/api/src/routes/appointmentGroups.ts +++ b/apps/api/src/routes/appointmentGroups.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/appointments.ts b/apps/api/src/routes/appointments.ts index c693325..6ed72e2 100644 --- a/apps/api/src/routes/appointments.ts +++ b/apps/api/src/routes/appointments.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { randomBytes } from "node:crypto"; import { and, diff --git a/apps/api/src/routes/book.ts b/apps/api/src/routes/book.ts index 3b12089..d82823f 100644 --- a/apps/api/src/routes/book.ts +++ b/apps/api/src/routes/book.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/clients.ts b/apps/api/src/routes/clients.ts index d569247..fe639c5 100644 --- a/apps/api/src/routes/clients.ts +++ b/apps/api/src/routes/clients.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, exists, getDb, or, clients, appointments } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; diff --git a/apps/api/src/routes/dev.ts b/apps/api/src/routes/dev.ts index dfc5708..363da85 100644 --- a/apps/api/src/routes/dev.ts +++ b/apps/api/src/routes/dev.ts @@ -20,6 +20,7 @@ devRouter.get("/users", async (c) => { const staffList = await db .select({ id: staff.id, + userId: staff.userId, name: staff.name, email: staff.email, role: staff.role, diff --git a/apps/api/src/routes/groomingLogs.ts b/apps/api/src/routes/groomingLogs.ts index a89c2ed..81eeaf4 100644 --- a/apps/api/src/routes/groomingLogs.ts +++ b/apps/api/src/routes/groomingLogs.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { desc, eq, getDb, groomingVisitLogs } from "@groombook/db"; export const groomingLogsRouter = new Hono(); diff --git a/apps/api/src/routes/impersonation.ts b/apps/api/src/routes/impersonation.ts index 00feb9d..350f086 100644 --- a/apps/api/src/routes/impersonation.ts +++ b/apps/api/src/routes/impersonation.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/invoices.ts b/apps/api/src/routes/invoices.ts index 9994d7f..ee2f473 100644 --- a/apps/api/src/routes/invoices.ts +++ b/apps/api/src/routes/invoices.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, diff --git a/apps/api/src/routes/pets.ts b/apps/api/src/routes/pets.ts index 5bcb20e..a6b9982 100644 --- a/apps/api/src/routes/pets.ts +++ b/apps/api/src/routes/pets.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, exists, getDb, or, pets, appointments } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; import { diff --git a/apps/api/src/routes/portal.ts b/apps/api/src/routes/portal.ts index a40fd42..7003a43 100644 --- a/apps/api/src/routes/portal.ts +++ b/apps/api/src/routes/portal.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { and, eq, getDb, appointments, impersonationSessions, waitlistEntries } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; diff --git a/apps/api/src/routes/services.ts b/apps/api/src/routes/services.ts index 621a797..e9ccc44 100644 --- a/apps/api/src/routes/services.ts +++ b/apps/api/src/routes/services.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { eq, getDb, services } from "@groombook/db"; export const servicesRouter = new Hono(); diff --git a/apps/api/src/routes/settings.ts b/apps/api/src/routes/settings.ts index 2641c8c..55332e4 100644 --- a/apps/api/src/routes/settings.ts +++ b/apps/api/src/routes/settings.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { eq, getDb, businessSettings } from "@groombook/db"; export const settingsRouter = new Hono(); diff --git a/apps/api/src/routes/staff.ts b/apps/api/src/routes/staff.ts index 0aa6b70..3316c45 100644 --- a/apps/api/src/routes/staff.ts +++ b/apps/api/src/routes/staff.ts @@ -1,6 +1,6 @@ import { Hono } from "hono"; import { zValidator } from "@hono/zod-validator"; -import { z } from "zod"; +import { z } from "zod/v3"; import { randomBytes } from "node:crypto"; import { and, eq, getDb, ne, staff, appointments } from "@groombook/db"; import type { AppEnv } from "../middleware/rbac.js"; diff --git a/apps/e2e/tests/fixtures.ts b/apps/e2e/tests/fixtures.ts index d043cc1..8e02aa4 100644 --- a/apps/e2e/tests/fixtures.ts +++ b/apps/e2e/tests/fixtures.ts @@ -1,14 +1,14 @@ import { test as base } from "@playwright/test"; /** - * Custom test fixture that bypasses the dev login redirect for E2E tests. + * Custom test fixture that bypasses auth for E2E tests. * - * When AUTH_DISABLED=true, the app fetches /api/dev/config and redirects to - * /login if no dev-user is in localStorage. This fixture: - * 1. Mocks /api/dev/config to return authDisabled: false - * 2. Seeds localStorage with a dev user as a fallback + * When authDisabled=true, the app uses the dev login selector instead of + * Better Auth signIn.social(). This fixture: + * 1. Mocks /api/dev/config to return authDisabled: true + * 2. Seeds localStorage with a dev user so the selector auto-selects a session * - * This ensures E2E tests render pages directly without the login redirect. + * This ensures E2E tests render pages directly without the auth redirect. */ const MOCK_DEV_USERS = { staff: [ @@ -23,9 +23,9 @@ const MOCK_DEV_USERS = { export const test = base.extend({ page: async ({ page }, use) => { - // Mock the dev config endpoint so the app skips the auth-disabled redirect + // Mock the dev config endpoint so the app uses dev login selector (bypasses Better Auth) await page.route("**/api/dev/config", (route) => - route.fulfill({ json: { authDisabled: false } }) + route.fulfill({ json: { authDisabled: true } }) ); // Mock the dev users endpoint for login selector tests await page.route("**/api/dev/users", (route) => diff --git a/apps/e2e/tests/navigation.spec.ts b/apps/e2e/tests/navigation.spec.ts index 544518a..8221ede 100644 --- a/apps/e2e/tests/navigation.spec.ts +++ b/apps/e2e/tests/navigation.spec.ts @@ -10,6 +10,15 @@ test.beforeEach(async ({ page }) => { // Reports endpoints need shaped responses (not bare []) to avoid render crashes. await page.route("/api/**", (route) => { const url = route.request().url(); + if (url.includes("/api/dev/config")) { + return route.fulfill({ json: { authDisabled: true } }); + } + if (url.includes("/api/dev/users")) { + return route.fulfill({ json: { staff: [], clients: [] } }); + } + if (url.includes("/api/branding")) { + return route.fulfill({ json: { businessName: "GroomBook", logoUrl: null, theme: "default" } }); + } if (url.includes("/api/reports/summary")) { return route.fulfill({ json: { diff --git a/apps/web/package.json b/apps/web/package.json index 82c6707..bab5329 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -14,6 +14,7 @@ "dependencies": { "@groombook/types": "workspace:*", "@tailwindcss/vite": "^4.2.2", + "better-auth": "^1.0.0", "lucide-react": "^0.577.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index cdf9d1f..8840370 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -17,6 +17,7 @@ import { DevLoginSelector, getDevUser } from "./pages/DevLoginSelector.js"; import { DevSessionIndicator } from "./components/DevSessionIndicator.js"; import { BrandingProvider, useBranding } from "./BrandingContext.js"; import { GlobalSearch } from "./components/GlobalSearch.js"; +import { useSession, signIn } from "./lib/auth-client.js"; const NAV_LINKS = [ { to: "/admin", label: "Appointments" }, @@ -133,6 +134,10 @@ function AdminLayout() { export function App() { const location = useLocation(); const [authDisabled, setAuthDisabled] = useState(null); + const { data: rawSession, isPending: rawSessionLoading } = useSession(); + // In dev mode (authDisabled=true), session state is irrelevant - skip useSession result + const session = authDisabled ? null : rawSession; + const sessionLoading = authDisabled ? false : rawSessionLoading; useEffect(() => { fetch("/api/dev/config") @@ -141,19 +146,6 @@ export function App() { .catch(() => setAuthDisabled(false)); }, []); - // Show login selector page - if (location.pathname === "/login") { - return ; - } - - // While checking auth config, render nothing briefly - if (authDisabled === null) return null; - - // If auth is disabled and no dev user is selected, redirect to login selector - if (authDisabled && !getDevUser() && location.pathname !== "/login") { - return ; - } - // Public booking redirect pages — no auth or portal chrome needed if (location.pathname === "/booking/confirmed") { return ; @@ -165,6 +157,25 @@ export function App() { return ; } + // Still loading auth state + if (authDisabled === null || sessionLoading) return null; + + // Dev mode: show login selector + if (authDisabled && location.pathname === "/login") { + return ; + } + + // Dev mode: use dev login selector + if (authDisabled && !getDevUser()) { + return ; + } + + // Production mode: if no session, redirect to Authentik sign-in + if (!authDisabled && !session) { + signIn.social({ provider: "authentik" }); + return null; + } + return ( {location.pathname.startsWith("/admin") ? ( diff --git a/apps/web/src/__tests__/App.test.tsx b/apps/web/src/__tests__/App.test.tsx index 97434eb..ea5aea8 100644 --- a/apps/web/src/__tests__/App.test.tsx +++ b/apps/web/src/__tests__/App.test.tsx @@ -1,7 +1,8 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; import { render, screen, within, waitFor } from "@testing-library/react"; import { MemoryRouter } from "react-router-dom"; -import { App } from "../App.js"; +import { App } from "../App"; + // Mock fetch to return appropriate responses based on URL beforeEach(() => { @@ -44,6 +45,32 @@ async function renderApp(route = "/admin") { } describe("App navigation", () => { + // Use authDisabled=true (dev mode) so nav renders without needing Better Auth useSession() mock + beforeEach(() => { + localStorage.setItem("dev-user", JSON.stringify({ type: "staff", id: "s1", name: "Sarah" })); + global.fetch = vi.fn((url: string) => { + if (url === "/api/dev/config") { + return Promise.resolve({ + ok: true, + json: async () => ({ authDisabled: true }), + } as Response); + } + if (url === "/api/branding") { + return Promise.resolve({ + ok: true, + json: async () => ({ + businessName: "GroomBook", + primaryColor: "#4f8a6f", + accentColor: "#8b7355", + logoBase64: null, + logoMimeType: null, + }), + } as Response); + } + return Promise.resolve({ ok: true, json: async () => [] } as Response); + }) as unknown as typeof fetch; + }); + it("renders the Groom Book brand", async () => { const nav = await renderApp(); expect( @@ -124,6 +151,12 @@ describe("Dev login selector", () => { }), } as Response); } + if (url === "/api/auth/get-session") { + return Promise.resolve({ + ok: true, + json: async () => ({ user: null }), + } as Response); + } return Promise.resolve({ ok: true, json: async () => [] } as Response); }) as unknown as typeof fetch; diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts new file mode 100644 index 0000000..1a4587b --- /dev/null +++ b/apps/web/src/lib/auth-client.ts @@ -0,0 +1,7 @@ +import { createAuthClient } from "better-auth/react"; + +export const authClient = createAuthClient({ + baseURL: import.meta.env.VITE_API_URL ?? "http://localhost:3000", +}); + +export const { signIn, signOut, useSession } = authClient; \ No newline at end of file diff --git a/apps/web/src/lib/devFetch.ts b/apps/web/src/lib/devFetch.ts index 42078ce..02b974b 100644 --- a/apps/web/src/lib/devFetch.ts +++ b/apps/web/src/lib/devFetch.ts @@ -9,6 +9,9 @@ const originalFetch = window.fetch; * Intentionally mutates window.fetch — this is dev-only (AUTH_DISABLED=true). */ export function installDevFetchInterceptor() { + // In production, Better-Auth handles auth via cookies — no interception needed + if (!import.meta.env.DEV) return; + window.fetch = function (input: RequestInfo | URL, init?: RequestInit) { const user = getDevUser(); if (!user) return originalFetch(input, init); diff --git a/apps/web/src/pages/DevLoginSelector.tsx b/apps/web/src/pages/DevLoginSelector.tsx index e171613..6de753b 100644 --- a/apps/web/src/pages/DevLoginSelector.tsx +++ b/apps/web/src/pages/DevLoginSelector.tsx @@ -3,6 +3,7 @@ import { useNavigate } from "react-router-dom"; interface StaffUser { id: string; + userId: string | null; name: string; email: string; role: string; @@ -66,7 +67,7 @@ export function DevLoginSelector() { {staff.map((s) => ( diff --git a/apps/web/src/portal/sections/Dashboard.tsx b/apps/web/src/portal/sections/Dashboard.tsx index 2f82cc7..93ba1c4 100644 --- a/apps/web/src/portal/sections/Dashboard.tsx +++ b/apps/web/src/portal/sections/Dashboard.tsx @@ -77,7 +77,11 @@ export function Dashboard({ onNavigate, readOnly }: Props) { {!readOnly && (
-