e2dc230b7f
PR #139 (a2b09ba) ported the GRO-2013 owner-bypass into the deployed ./src/routes/pets.ts but did NOT port the rbac auto-provision change. As a result, on UAT (api:2026.06.01-4e9c4c5) the owner-bypass code is unreachable for any Better-Auth email/password customer: ./src/middleware/rbac.ts (the deployed tree) only auto-provisions staff rows when account.providerId IN ('authentik','google','github') for jwt.sub. The UAT customer uat-customer@groombook.dev has a row in the Better-Auth `user` table but no row in `account` for those providers, so resolveStaffMiddleware falls through to: 403 "Forbidden: no staff record found for authenticated user" before pets.ts ever runs. The canonical apps/api/src/middleware/rbac.ts already has a Better-Auth user-table fallback. This commit mirrors that branch into the deployed ./src/middleware/rbac.ts. Behaviour ========= - New: when no staff row exists for jwt.sub but the Better-Auth `user` table has a row whose id matches jwt.sub, INSERT a minimal role='groomer', isSuperUser=false, active=true staff row, set it on the request context, and continue. - The legacy OIDC `account` branch is kept as a fallback for backwards compatibility with any pre-Better-Auth OIDC sessions whose user row may not yet exist in `user`. - Lookup order: staff (userId) -> staff (oidcSub) -> staff (email, user_id IS NULL) -> Better-Auth user -> OIDC account -> 403. - Name derivation: userRow.name -> jwt.name -> email prefix -> "Unknown". Tests ===== src/__tests__/rbac.test.ts: - Mock @groombook/db rewritten to be table-aware so SELECTs from `user`/`account`/`staff` route to distinct lookup queues, and insert(staff).values(...).returning() is supported. - buildApp() helper gains an optional jwtOverride param so tests can set jwt.email/name explicitly. - 5 new cases under "resolveStaffMiddleware — auto-provision": 1. Better-Auth user found -> staff row provisioned with role=groomer 2. INSERT returns no row -> 500 "auto-provision failed" 3. Better-Auth branch runs without jwt.email (regression of the pre-fix gate) 4. OIDC fallback still works when user row is missing but account row exists 5. Neither user nor account row -> 403 with "no staff record" message Existing rbac.test.ts cases all keep passing (15 prior cases retained). Full pnpm test on apps/api: 572/572 pass. pnpm typecheck: clean. Scope ===== - ./src/middleware/rbac.ts only — apps/api/src/middleware/rbac.ts already has this branch and is unchanged. - No schema/migration changes; staff and user tables are unchanged. - pre-existing lint error in src/__tests__/petProfileSummary.test.ts:167 (`servicesTable` declared/assigned but never read) introduced by PR #139a2b09bais NOT addressed here — it is out of this PR's scope. Resolves: GRO-2052 Refs: GRO-2013, GRO-2050, GRO-2035 Co-Authored-By: Paperclip <noreply@paperclip.ing>
287 lines
8.6 KiB
TypeScript
287 lines
8.6 KiB
TypeScript
import type { MiddlewareHandler } from "hono";
|
|
import { and, eq, getDb, sql, staff, account, user } from "@groombook/db";
|
|
|
|
export type StaffRole = "groomer" | "receptionist" | "manager";
|
|
export type StaffRow = typeof staff.$inferSelect;
|
|
|
|
export interface AppEnv {
|
|
Variables: {
|
|
jwtPayload: { sub: string; email?: string; name?: string };
|
|
staff: StaffRow;
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 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 (Better-Auth
|
|
* user ID), or falls back to the first manager in the DB.
|
|
*/
|
|
export const resolveStaffMiddleware: MiddlewareHandler<AppEnv> = async (
|
|
c,
|
|
next
|
|
) => {
|
|
// Better-Auth\'s own routes handle their own auth — skip staff resolution
|
|
// OOBE setup routes also handle their own auth — staff record is created during setup
|
|
if (c.req.path.startsWith("/api/auth/") || c.req.path.startsWith("/api/setup")) {
|
|
await next();
|
|
return;
|
|
}
|
|
|
|
const db = getDb();
|
|
|
|
if (process.env.AUTH_DISABLED === "true") {
|
|
const devUserId = c.req.header("X-Dev-User-Id");
|
|
if (!devUserId) {
|
|
// No header — fall back to first manager
|
|
const [manager] = await db
|
|
.select()
|
|
.from(staff)
|
|
.where(eq(staff.role, "manager"))
|
|
.limit(1);
|
|
if (!manager) {
|
|
return c.json({ error: "Forbidden: no staff records found" }, 403);
|
|
}
|
|
c.set("staff", { ...manager, isSuperUser: manager.isSuperUser ?? false });
|
|
await next();
|
|
return;
|
|
}
|
|
// 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, isSuperUser: row.isSuperUser ?? false });
|
|
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", { ...fallbackRow, isSuperUser: fallbackRow.isSuperUser ?? false });
|
|
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 (fallbackRow) {
|
|
c.set("staff", fallbackRow);
|
|
await next();
|
|
return;
|
|
}
|
|
// Auto-link by email: staff record exists with matching email but no userId
|
|
if (jwt.email) {
|
|
const [byEmail] = await db
|
|
.select()
|
|
.from(staff)
|
|
.where(and(eq(staff.email, jwt.email), sql`${staff.userId} IS NULL`));
|
|
if (byEmail) {
|
|
await db
|
|
.update(staff)
|
|
.set({ userId: jwt.sub, updatedAt: new Date() })
|
|
.where(eq(staff.id, byEmail.id));
|
|
c.set("staff", { ...byEmail, userId: jwt.sub });
|
|
await next();
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Auto-provision for Better-Auth users (GRO-2052): the user signed in via
|
|
// Better-Auth (email/password, magic link, etc.), so a row exists in `user`
|
|
// for jwt.sub but no `account` provider row is required. Create a minimal
|
|
// groomer staff record on first login. This is the primary auto-provision
|
|
// path; the OIDC branch below remains as a fallback for legacy accounts
|
|
// that exist in `account` but not in `user`.
|
|
const [userRow] = await db
|
|
.select({ id: user.id, name: user.name, email: user.email })
|
|
.from(user)
|
|
.where(eq(user.id, jwt.sub))
|
|
.limit(1);
|
|
if (userRow) {
|
|
const emailPrefix = userRow.email ? userRow.email.split("@")[0] : "Unknown";
|
|
const name = userRow.name?.trim() || jwt.name?.trim() || emailPrefix;
|
|
|
|
const [newStaff] = await db
|
|
.insert(staff)
|
|
.values({
|
|
userId: jwt.sub,
|
|
email: userRow.email ?? jwt.email ?? "",
|
|
name,
|
|
role: "groomer",
|
|
isSuperUser: false,
|
|
active: true,
|
|
} as Parameters<typeof db.insert>[0] extends { values: infer V } ? V : never)
|
|
.returning()!;
|
|
|
|
if (!newStaff) {
|
|
return c.json({ error: "Forbidden: auto-provision failed" }, 500);
|
|
}
|
|
|
|
console.log(
|
|
`[rbac] auto-provisioned staff record for Better-Auth user: ${jwt.sub} -> staff:${newStaff.id} (${name})`
|
|
);
|
|
c.set("staff", newStaff);
|
|
await next();
|
|
return;
|
|
}
|
|
|
|
// Auto-provision for OIDC users: check if jwt.sub has an OAuth/OIDC account
|
|
// (e.g. authentik). If so, create a groomer staff record on the fly. This
|
|
// is kept for backward compatibility with legacy OIDC sessions whose user
|
|
// row may not yet exist in the Better-Auth `user` table.
|
|
if (jwt.email) {
|
|
const [oidcAccount] = await db
|
|
.select({ id: account.id })
|
|
.from(account)
|
|
.where(
|
|
and(
|
|
eq(account.userId, jwt.sub),
|
|
sql`${account.providerId} IN (\'authentik\', \'google\', \'github\')`
|
|
)
|
|
)
|
|
.limit(1);
|
|
|
|
if (oidcAccount) {
|
|
// Derive name: prefer jwt.name, fall back to email prefix, then "Unknown"
|
|
const emailPrefix = jwt.email ? jwt.email.split("@")[0] : "Unknown";
|
|
const name = jwt.name?.trim() || emailPrefix;
|
|
|
|
const [newStaff] = await db
|
|
.insert(staff)
|
|
.values({
|
|
userId: jwt.sub,
|
|
email: (jwt.email ?? "") as string,
|
|
name,
|
|
role: "groomer",
|
|
isSuperUser: false,
|
|
active: true,
|
|
} as Parameters<typeof db.insert>[0] extends { values: infer V } ? V : never)
|
|
.returning()!;
|
|
|
|
if (!newStaff) {
|
|
return c.json({ error: "Forbidden: auto-provision failed" }, 500);
|
|
}
|
|
|
|
console.log(
|
|
`[rbac] auto-provisioned staff record for OIDC user: ${jwt.sub} -> staff:${newStaff.id} (${name})`
|
|
);
|
|
c.set("staff", newStaff);
|
|
await next();
|
|
return;
|
|
}
|
|
}
|
|
|
|
return c.json(
|
|
{ error: "Forbidden: no staff record found for authenticated user" },
|
|
403
|
|
);
|
|
};
|
|
|
|
/**
|
|
* Middleware factory that enforces one of the allowed roles.
|
|
* Must be applied after resolveStaffMiddleware.
|
|
*
|
|
* @example
|
|
* api.use("/staff/*", requireRole("manager"));
|
|
* api.use("/reports/*", requireRole("manager"));
|
|
*/
|
|
export function requireRole(
|
|
...allowedRoles: StaffRole[]
|
|
): MiddlewareHandler<AppEnv> {
|
|
return async (c, next) => {
|
|
const staffRow = c.get("staff");
|
|
if (!staffRow) {
|
|
return c.json({ error: "Forbidden: staff record not resolved" }, 403);
|
|
}
|
|
if (!(allowedRoles as string[]).includes(staffRow.role)) {
|
|
return c.json(
|
|
{
|
|
error: `Forbidden: role \'${staffRow.role}\' is not permitted to access this resource`,
|
|
},
|
|
403
|
|
);
|
|
}
|
|
await next();
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Middleware that allows access if the staff member has any of the allowed roles OR is a super user.
|
|
* Use for routes where managers OR super-users should have access.
|
|
*
|
|
* @example
|
|
* api.on(["POST", "PATCH", "DELETE"], "/staff/*", requireRoleOrSuperUser("manager"));
|
|
*/
|
|
export function requireRoleOrSuperUser(
|
|
...allowedRoles: StaffRole[]
|
|
): MiddlewareHandler<AppEnv> {
|
|
return async (c, next) => {
|
|
const staffRow = c.get("staff");
|
|
if (!staffRow) {
|
|
return c.json({ error: "Forbidden: staff record not resolved" }, 403);
|
|
}
|
|
const hasAllowedRole = (allowedRoles as string[]).includes(staffRow.role);
|
|
if (hasAllowedRole || staffRow.isSuperUser) {
|
|
await next();
|
|
return;
|
|
}
|
|
return c.json(
|
|
{
|
|
error: hasAllowedRole
|
|
? "Forbidden: super user privileges required"
|
|
: `Forbidden: role \'${staffRow.role}\' is not permitted`,
|
|
},
|
|
403
|
|
);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Middleware that enforces the staff member is a super user.
|
|
* Must be applied after resolveStaffMiddleware and (typically) after requireRole.
|
|
*
|
|
* @example
|
|
* api.use("/staff/*", requireRole("manager"));
|
|
* api.use("/staff/*", requireSuperUser());
|
|
*/
|
|
export function requireSuperUser(): MiddlewareHandler<AppEnv> {
|
|
return async (c, next) => {
|
|
const staffRow = c.get("staff");
|
|
if (!staffRow) {
|
|
return c.json({ error: "Forbidden: staff record not resolved" }, 403);
|
|
}
|
|
if (!staffRow.isSuperUser) {
|
|
return c.json(
|
|
{ error: "Forbidden: super user privileges required" },
|
|
403
|
|
);
|
|
}
|
|
await next();
|
|
};
|
|
}
|