Merge branch 'main' into fix/disable-stub-portal-buttons

This commit is contained in:
groombook-cto[bot]
2026-03-28 03:55:22 +00:00
committed by GitHub
36 changed files with 695 additions and 131 deletions
+5 -6
View File
@@ -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",
@@ -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",
+1 -2
View File
@@ -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();
});
+1
View File
@@ -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",
+5 -2
View File
@@ -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<AppEnv>();
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<AppEnv>();
app.use("*", async (c, next) => {
c.set("jwtPayload", { sub: staffRow.oidcSub ?? "" });
c.set("jwtPayload", { sub: staffRow.userId ?? "" });
c.set("staff", staffRow);
await next();
});
+14 -1
View File
@@ -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,13 +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
// Manager-only: admin settings, reports, invoices, impersonation
// Staff CRUD: all roles may READ; manager-only for CREATE/UPDATE/DELETE
api.on(["GET"], "/staff/*", requireRole("manager", "receptionist", "groomer"));
api.use("/staff/*", requireRole("manager"));
api.use("/admin/*", requireRole("manager"));
api.use("/reports/*", requireRole("manager"));
+48
View File
@@ -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"],
});
+20 -39
View File
@@ -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<typeof createRemoteJWKSet> | 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();
};
+29 -9
View File
@@ -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<AppEnv> = async (
c,
@@ -41,34 +40,55 @@ export const resolveStaffMiddleware: MiddlewareHandler<AppEnv> = async (
await next();
return;
}
// Treat X-Dev-User-Id as the staff database id (the frontend stores staff.id)
// Treat X-Dev-User-Id as the Better-Auth user ID first
const [row] = await db
.select()
.from(staff)
.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 (!row) {
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();
};
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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";
+1
View File
@@ -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,
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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,
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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";
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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";
+8 -8
View File
@@ -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) =>
+9
View File
@@ -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: {
+1
View File
@@ -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",
+24 -13
View File
@@ -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<boolean | null>(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 <DevLoginSelector />;
}
// 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 <Navigate to="/login" replace />;
}
// Public booking redirect pages — no auth or portal chrome needed
if (location.pathname === "/booking/confirmed") {
return <BookingConfirmedPage />;
@@ -165,6 +157,25 @@ export function App() {
return <BookingErrorPage />;
}
// Still loading auth state
if (authDisabled === null || sessionLoading) return null;
// Dev mode: show login selector
if (authDisabled && location.pathname === "/login") {
return <DevLoginSelector />;
}
// Dev mode: use dev login selector
if (authDisabled && !getDevUser()) {
return <Navigate to="/login" replace />;
}
// Production mode: if no session, redirect to Authentik sign-in
if (!authDisabled && !session) {
signIn.social({ provider: "authentik" });
return null;
}
return (
<BrandingProvider>
{location.pathname.startsWith("/admin") ? (
+34 -1
View File
@@ -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;
+7
View File
@@ -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;
+3
View File
@@ -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);
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />