Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,46 +1,111 @@
import type { LoaderFunctionArgs } from "react-router";
import type { AdminDashboardVM } from "@hivegrid/view-models";
import {
isAdminRoleKey,
isAdminPermissionName,
type AdminPermissionName,
type AdminRoleKey,
} from "@hivegrid/db/admin-permissions";
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
import { getTranslations } from "~/locale/i18next.server";
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
import { adminGetAllTenantsWithUsage, type TenantWithUsage } from "~/utils/db/tenants.db.server";
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import PeriodHelper from "~/utils/helpers/PeriodHelper";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getAdminDashboardStats } from "~/utils/services/adminDashboardService";
import { getAdminDashboardOverview, getAdminDashboardStats, type AdminDashboardOverview } from "~/utils/services/adminDashboardService";
import type { Stat } from "~/application/dtos/stats/Stat";
import type { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
import { loadPersonalizedAdminDashboard } from "~/services/admin/admin-dashboard-personalization.server";
import { db } from "~/utils/db.server";
export type AdminDashboardLoaderData = {
title: string;
stats: Stat[];
tenants: {
items: TenantWithUsage[];
pagination: PaginationDto;
};
dashboard: AdminDashboardVM;
superOverview: {
stats: Stat[];
overview: AdminDashboardOverview;
tenants: {
items: TenantWithUsage[];
pagination: PaginationDto;
};
} | null;
};
type AdminDashboardDataArgs = Pick<LoaderFunctionArgs, "request" | "params">;
export async function loadAdminDashboardRouteData({ request, params }: AdminDashboardDataArgs) {
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.dashboard");
const urlSearchParams = new URL(request.url).searchParams;
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const { t } = await time(getTranslations(request), "getTranslations");
const { stats, tenants } = await time(
promiseHash({
stats: time(
getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) }),
"admin.dashboard.details.getAdminDashboardStats"
),
tenants: time(adminGetAllTenantsWithUsage(undefined, currentPagination), "admin.dashboard.details.adminGetAllTenantsWithUsage"),
const { t, locale } = await time(getTranslations(request), "getTranslations");
const { dashboard, superOverview } = await time(
runAsAdminIdentity(request, ADMIN_AREA_ACCESS.dashboard, async (session) => {
const [permissionNames, roleRows] = await Promise.all([
listAdminPermissionNames(session.adminUserId),
db.adminUserRole.findMany({
where: {
adminUserId: session.adminUserId,
role: { active: true },
},
select: { role: { select: { systemKey: true } } },
orderBy: { createdAt: "asc" },
}),
]);
const permissions = permissionNames.filter(isAdminPermissionName);
const roleKeys = roleRows
.map((row) => row.role.systemKey)
.filter((roleKey): roleKey is AdminRoleKey =>
Boolean(roleKey && isAdminRoleKey(roleKey))
);
const dashboard = await loadPersonalizedAdminDashboard({
adminUserId: session.adminUserId,
roleKeys,
permissions: permissions as AdminPermissionName[],
locale,
});
const superOverview = roleKeys.includes("super_admin")
? await loadSuperAdminOverview(request, t, time)
: null;
return { dashboard, superOverview };
}),
"admin.dashboard.details"
"admin.dashboard.personalized"
);
const data: AdminDashboardLoaderData = {
title: `${t("app.sidebar.dashboard")} | ${process.env.APP_NAME}`,
stats,
tenants,
dashboard,
superOverview,
};
return { data, headers: getServerTimingHeader() };
}
async function loadSuperAdminOverview(
request: Request,
t: (key: string) => string,
time: <T>(promise: Promise<T>, name: string) => Promise<T>
) {
const currentPagination = getPaginationFromCurrentUrl(
new URL(request.url).searchParams
);
return time(
promiseHash({
stats: time(
getAdminDashboardStats({
t,
gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }),
}),
"admin.dashboard.details.getAdminDashboardStats"
),
overview: time(
getAdminDashboardOverview(),
"admin.dashboard.details.getAdminDashboardOverview"
),
tenants: time(
adminGetAllTenantsWithUsage(undefined, currentPagination),
"admin.dashboard.details.adminGetAllTenantsWithUsage"
),
}),
"admin.dashboard.super"
);
}
@@ -6,19 +6,20 @@ function readAdminDataSource() {
return readRepoFile("apps/web/app/utils/data/.server/adminData.ts");
}
describe("admin data MFA enforcement boundary", () => {
describe("admin data Authentik MFA assurance boundary", () => {
test("does not import MFA secret or recovery-code storage directly", () => {
const source = readAdminDataSource();
expect(source).not.toMatch(/mfaRecoveryCode|totpSecret|encryptedTotpSecret/i);
});
test("routes shared admin loader through the MFA enforcement boundary", () => {
test("accepts only a validated tenantless AdminSession", () => {
const source = readAdminDataSource();
expect(source).toContain("getUserTotpStatus");
expect(source).toContain("checkMfaStepUpState");
expect(source).toContain("enforceAdminMfa");
expect(source).toMatch(/if \(!mfaEnforcement\.allowed\) \{\s*throw redirect\(mfaEnforcement\.redirectTo\);\s*\}/);
expect(source).toContain("getValidatedServerSession");
expect(source).toContain('"adminUser" in validatedSession');
expect(source).toContain("validatedSession.adminUser");
expect(source).not.toContain("getUserTotpStatus");
expect(source).not.toContain("enforceAdminMfa");
});
});
@@ -1,81 +1,77 @@
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { TimeFunction } from "~/modules/metrics/services/.server/MetricTracker";
import OnboardingService from "~/modules/onboarding/services/OnboardingService";
import UrlUtils from "~/utils/app/UrlUtils";
import { getMyGroups } from "~/utils/db/permissions/groups.db.server";
import { getAllRolesWithoutPermissions } from "~/utils/db/permissions/roles.db.server";
import { getPermissionsByUser, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
import { getTenantsForUser as getMyTenants } from "@hivegrid/db/auth-boundary.server";
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
import { getUserTotpStatus } from "~/utils/db/users.db.server";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getUserInfo, getUserSession } from "~/utils/session.server";
import { AdminLoaderData } from "../useAdminData";
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
import { TFunction } from "i18next";
import type { TFunction } from "i18next";
import { redirect } from "react-router";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export async function loadAdminData({ request, t }: { request: Request; t: TFunction }, time: TimeFunction) {
import { adminGetAllActiveTenants } from "@hivegrid/db/auth-boundary.server";
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import type { TimeFunction } from "~/modules/metrics/services/.server/MetricTracker";
import UrlUtils from "~/utils/app/UrlUtils";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
import { getUserInfo, getValidatedServerSession } from "~/utils/session.server";
import type { AdminLoaderData } from "../useAdminData";
export async function loadAdminData({ request, t: _t }: { request: Request; t: TFunction }, time: TimeFunction) {
const userInfo = await time(getUserInfo(request), "getUserInfo");
const url = new URL(request.url);
if (UrlUtils.stripTrailingSlash(url.pathname) === `/admin`) {
if (UrlUtils.stripTrailingSlash(url.pathname) === "/admin") {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const user = await time(getUser(userInfo?.userId), "getUser");
const redirectTo = url.pathname + url.search;
if (!userInfo || !user) {
let searchParams = new URLSearchParams([["redirect", redirectTo]]);
if (!userInfo.userId) {
const searchParams = new URLSearchParams([["redirect", url.pathname + url.search]]);
throw redirect(`/login?${searchParams}`);
}
if (!user.admin) {
throw Response.json({ error: t("admin.errors.adminOnly") }, { status: 401 });
const validatedSession = await time(getValidatedServerSession(request, userInfo), "getValidatedAdminSession");
if (!validatedSession || !("adminUser" in validatedSession)) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const admin = validatedSession.adminUser;
const session = await time(getUserSession(request), "getUserSession");
const totpStatus = await time(getUserTotpStatus(user.id), "getUserTotpStatus");
const stepUp = checkMfaStepUpState(session, user.id);
const mfaEnforcement = enforceAdminMfa({
requestUrl: url,
userId: user.id,
isAdmin: Boolean(user.admin),
totpStatus,
stepUp,
redirectMode: "host-aware",
});
if (!mfaEnforcement.allowed) {
throw redirect(mfaEnforcement.redirectTo);
}
const myTenants = await time(getMyTenants(user.id), "getMyTenants");
const { allPermissions, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
promiseHash({
allPermissions: getPermissionsByUser(userInfo.userId, null),
superAdminRole: getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin),
allRoles: getAllRolesWithoutPermissions("admin"),
myGroups: getMyGroups(user.id, null),
onboardingSession: OnboardingService.getUserActiveOnboarding({ userId: user.id, tenantId: null, request }),
}),
const { permissions, roles, myTenants } = await time(
runWithRlsContext({ userId: admin.id }, async () => ({
permissions: await listAdminPermissionNames(admin.id),
roles: await db.adminRole.findMany({
where: { active: true },
select: { id: true, name: true, description: true },
orderBy: { name: "asc" },
}),
myTenants: await adminGetAllActiveTenants(),
})),
"loadAdminData.getDetails"
);
const isSuperAdmin = await runWithRlsContext({ userId: admin.id }, () =>
db.adminUserRole.findFirst({
where: { adminUserId: admin.id, role: { systemKey: "super_admin", active: true } },
select: { adminUserId: true },
})
);
const data: AdminLoaderData = {
user,
user: {
id: admin.id,
email: admin.email,
firstName: admin.firstName,
lastName: admin.lastName,
avatar: admin.avatar,
phone: null,
admin: { userId: admin.id },
defaultTenantId: null,
createdAt: validatedSession.createdAt,
locale: admin.locale,
lightOrDarkMode: null,
},
myTenants,
currentTenant: null,
// roles,
allRoles,
permissions: allPermissions.map((f) => f as DefaultPermission),
isSuperUser: !!superAdminRole,
isSuperAdmin: !!superAdminRole,
myGroups,
lng: user?.locale ?? userInfo.lng,
onboardingSession,
tenantTypes: await getAllTenantTypes(),
allRoles: roles,
permissions: permissions as DefaultPermission[],
isSuperUser: isSuperAdmin !== null,
isSuperAdmin: isSuperAdmin !== null,
myGroups: [],
lng: admin.locale ?? userInfo.lng,
onboardingSession: null,
};
return data;
}
@@ -0,0 +1,84 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
const state = vi.hoisted(() => ({ superAdmin: false }));
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "de" })) }));
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
getAuthUserWithoutPasswordById: vi.fn(async () => ({
id: "user_1",
admin: { ssoProvider: "authentik", ssoGroups: ["hivegrid-staff"] },
locale: "de",
})),
getTenantsForUser: vi.fn(async () => [{ id: "tenant_1", slug: "acme", name: "Member tenant" }]),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
adminGetAllActiveTenantSimple: vi.fn(async () => [
{ id: "tenant_1", slug: "acme", name: "Member tenant" },
{ id: "tenant_2", slug: "global", name: "Global tenant" },
]),
getTenantSimple: vi.fn(async () => ({ id: "tenant_1", slug: "acme", name: "Member tenant", deactivatedReason: null })),
getTenantUserType: vi.fn(async () => ({ type: TenantUserType.MEMBER })),
}));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: {} })) }));
vi.mock("~/utils/db/permissions/groups.db.server", () => ({ getMyGroups: vi.fn(async () => []) }));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRolesWithoutPermissions: vi.fn(async () => []) }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
getPermissionsByUser: vi.fn(async () => []),
getUserRoleInAdmin: vi.fn(async () => (state.superAdmin ? { id: "superadmin_assignment" } : null)),
getUserRoleInTenant: vi.fn(async () => null),
}));
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn(async () => []) }));
vi.mock("~/utils/services/.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(async () => ({ products: [] })),
getPlanFeatureUsage: vi.fn(async () => undefined),
}));
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn(async () => null) } }));
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({ resolveTenantProductAccessBatch: vi.fn(async () => []) }));
import { getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
import { adminGetAllActiveTenantSimple } from "~/utils/db/tenants.db.server";
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
import { loadAppData } from "./appData";
function load() {
return loadAppData({
request: new Request("https://app.example.test/acme/dashboard"),
params: { tenant: "acme" },
t: ((key: string) => key) as never,
});
}
describe("loadAppData operator boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
state.superAdmin = false;
});
it("keeps Authentik staff tenant-scoped despite having an AdminUser identity", async () => {
const data = await load();
expect(data.isSuperAdmin).toBe(false);
expect(data.currentRole).toBe(TenantUserType.MEMBER);
expect(data.myTenants).toHaveLength(1);
expect(getTenantsForUser).toHaveBeenCalledWith("user_1");
expect(adminGetAllActiveTenantSimple).not.toHaveBeenCalled();
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: false }));
});
it("grants global tenant enumeration and product bypass only to the SuperAdmin RBAC role", async () => {
state.superAdmin = true;
const data = await load();
expect(data.isSuperAdmin).toBe(true);
expect(data.currentRole).toBe(TenantUserType.ADMIN);
expect(data.myTenants).toHaveLength(2);
expect(adminGetAllActiveTenantSimple).toHaveBeenCalledOnce();
expect(getTenantsForUser).not.toHaveBeenCalled();
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: true }));
});
});
@@ -18,9 +18,8 @@ function deferred<T>(): Deferred<T> {
const mocks = vi.hoisted(() => {
const postDetails = {
tenantUser: deferred<{ type: TenantUserType }>(),
tenantTypes: deferred<unknown[]>(),
credits: deferred<unknown>(),
productAccess: deferred<{ allowed: boolean }>(),
productAccess: deferred<Array<readonly [string, { allowed: boolean }]>>(),
};
return { postDetails };
});
@@ -28,7 +27,11 @@ const mocks = vi.hoisted(() => {
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "en" })) }));
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
getAuthUserWithoutPasswordById: vi.fn(async () => ({ id: "user_1", admin: false, locale: "en" })),
getAuthUserWithoutPasswordById: vi.fn(async () => ({
id: "user_1",
admin: { ssoProvider: "authentik", ssoGroups: ["hivegrid-staff"] },
locale: "en",
})),
getTenantsForUser: vi.fn(async () => [{ id: "tenant_1", slug: "acme", name: "Acme" }]),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
@@ -44,20 +47,20 @@ vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
getUserRoleInAdmin: vi.fn(async () => null),
getUserRoleInTenant: vi.fn(async () => null),
}));
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn(() => mocks.postDetails.tenantTypes.promise) }));
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
vi.mock("~/utils/services/.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(async () => ({ products: [] })),
getPlanFeatureUsage: vi.fn(() => mocks.postDetails.credits.promise),
}));
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn(async () => null) } }));
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({
resolveTenantProductAccess: vi.fn(() => mocks.postDetails.productAccess.promise),
resolveTenantProductAccessBatch: vi.fn(() => mocks.postDetails.productAccess.promise),
}));
import { getTenantUserType } from "~/utils/db/tenants.db.server";
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
import { adminGetAllActiveTenantSimple, getTenantUserType } from "~/utils/db/tenants.db.server";
import { getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
import { getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
import { loadAppData } from "./appData";
async function flushAsyncWork() {
@@ -75,19 +78,20 @@ describe("loadAppData performance", () => {
await flushAsyncWork();
expect(getTenantUserType).toHaveBeenCalledWith("user_1", "tenant_1");
expect(getAllTenantTypes).toHaveBeenCalled();
expect(getPlanFeatureUsage).toHaveBeenCalledWith("tenant_1", "ai-credits");
expect(resolveTenantProductAccess).toHaveBeenCalled();
expect(resolveTenantProductAccessBatch).toHaveBeenCalledTimes(1);
expect(getTenantsForUser).toHaveBeenCalledWith("user_1");
expect(adminGetAllActiveTenantSimple).not.toHaveBeenCalled();
mocks.postDetails.tenantUser.resolve({ type: TenantUserType.MEMBER });
mocks.postDetails.tenantTypes.resolve([]);
mocks.postDetails.credits.resolve(undefined);
mocks.postDetails.productAccess.resolve({ allowed: true });
mocks.postDetails.productAccess.resolve([["dashboard", { allowed: true }]]);
await expect(result).resolves.toMatchObject({
currentRole: TenantUserType.MEMBER,
tenantTypes: [],
isSuperAdmin: false,
productAccess: expect.any(Object),
});
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: false }));
});
});
@@ -15,9 +15,10 @@ vi.mock("~/utils/db/permissions/groups.db.server", () => ({ getMyGroups: vi.fn()
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRolesWithoutPermissions: vi.fn() }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
getPermissionsByUser: vi.fn(),
getUserRoleInAdmin: vi.fn(),
getUserRoleInAdmin: vi.fn(async () => null),
getUserRoleInTenant: vi.fn(),
}));
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn() }));
vi.mock("~/utils/services/.server/subscriptionService", () => ({ getActiveTenantSubscriptions: vi.fn(), getPlanFeatureUsage: vi.fn() }));
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn() } }));
@@ -9,4 +9,15 @@ describe("loadAppData tenant role lookup", () => {
expect(source).toContain("getTenantUserType(userInfo.userId, tenantId)");
expect(source).not.toContain("getTenantUserType(tenantId, userInfo.userId)");
});
test("builds the shell billing banner from normalized subscription data", () => {
const source = readRepoFile("apps/web/app/utils/data/.server/appData.ts");
expect(source).toContain("billingBanner = buildSubscriptionBannerVM({");
expect(source).toContain("status: normalizeBillingSubscriptionStatus(mySubscription?.status");
expect(source).toContain("frozenAt: mySubscription?.frozenAt");
expect(source).toContain("cancelledAt: mySubscription?.cancelledAt");
expect(source).toContain("trialEndsAt: mySubscription?.trialEndsAt");
expect(source).toContain("billingBanner,");
});
});
@@ -9,12 +9,14 @@ import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import UrlUtils from "~/utils/app/UrlUtils";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { normalizeBillingSubscriptionStatus } from "@hivegrid/db/billing-domain.server";
import { buildSubscriptionBannerVM } from "@hivegrid/view-models";
import { getMyGroups } from "~/utils/db/permissions/groups.db.server";
import { getAllRolesWithoutPermissions } from "~/utils/db/permissions/roles.db.server";
import { getPermissionsByUser, getUserRoleInTenant, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
import { getUserEffectiveSeatType } from "~/utils/db/permissions/seatType.db.server";
import { adminGetAllActiveTenantSimple, getTenantSimple, getTenantUserType } from "~/utils/db/tenants.db.server";
import { getAuthUserWithoutPasswordById as getUser, getTenantsForUser as getMyTenants } from "@hivegrid/db/auth-boundary.server";
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getActiveTenantSubscriptions, getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
@@ -25,7 +27,7 @@ import { CreditTypes } from "~/modules/usage/dtos/CreditType";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { TFunction } from "i18next";
import { featureKeys, type FeatureKey } from "@hivegrid/entitlements";
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
import { WALKING_SKELETON_MODULE_KEY } from "~/modules/walkingSkeleton/constants";
// Every feature key the AppSidebar gates on via hasFeatureAccess() MUST be
@@ -43,8 +45,11 @@ const tenantNavigationFeatureKeys = [
featureKeys.tasks,
featureKeys.hr,
featureKeys.integrations,
featureKeys.telephony,
featureKeys.chat,
featureKeys.booking,
featureKeys.forms,
featureKeys.billing,
featureKeys.search,
featureKeys.automation,
featureKeys.emailMarketing,
@@ -52,6 +57,8 @@ const tenantNavigationFeatureKeys = [
featureKeys.api,
featureKeys.workflowEngine,
featureKeys.credits,
// Not a sidebar entry: gates the topbar "Mit KI verbinden" launcher (VD-MCP).
featureKeys.mcp,
] as const satisfies readonly FeatureKey[];
// R-P1c: Konnektor-Demo-Modul (kein Entitlement-FeatureKey) — speist das Sidebar-Gate der
@@ -86,13 +93,25 @@ export async function loadAppData({
);
const url = new URL(request.url);
const { user, currentTenant } = await time(
const operatorAdminPromise: Promise<boolean> =
preloadedIsOperatorAdmin !== undefined
? Promise.resolve(preloadedIsOperatorAdmin)
: userInfo?.userId
? getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin).then((role) => Boolean(role))
: Promise.resolve(false);
const {
user,
currentTenant,
operatorAdmin: operatorAdminValue,
} = await time(
promiseHash({
user: preloadedUser ? Promise.resolve(preloadedUser) : getUser(userInfo?.userId),
currentTenant: getTenantSimple(tenantId),
operatorAdmin: operatorAdminPromise,
}),
"loadAppData.getUserAndTenant"
);
const operatorAdmin = operatorAdminValue === true;
const redirectTo = url.pathname + url.search;
if (!userInfo || !user) {
@@ -111,52 +130,53 @@ export async function loadAppData({
if (UrlUtils.stripTrailingSlash(url.pathname) === UrlUtils.stripTrailingSlash(appPath({ tenantSlug: tenantPathSegment, mode: "host-aware" }))) {
throw redirect(`${appPath({ tenantSlug: currentTenant.slug, path: "dashboard", mode: "host-aware" })}${url.search}`);
}
const operatorAdmin = Boolean(user.admin) || Boolean(preloadedIsOperatorAdmin);
let { myTenants, mySubscription, allPermissions, superUserRole, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
let { myTenants, mySubscription, allPermissions, superUserRole, allRoles, myGroups, onboardingSession, effectiveSeatType } = await time(
promiseHash({
myTenants: time(operatorAdmin ? adminGetAllActiveTenantSimple() : getMyTenants(user.id), "loadAppData.getDetails.getMyTenants"),
mySubscription: time(getActiveTenantSubscriptions(tenantId), "loadAppData.getDetails.getActiveTenantSubscriptions"),
allPermissions: time(getPermissionsByUser(userInfo.userId, tenantId), "loadAppData.getDetails.getPermissionsByUser"),
superUserRole: time(getUserRoleInTenant(userInfo.userId, tenantId, DefaultAppRoles.SuperUser), "loadAppData.getDetails.getUserRoleInTenant"),
superAdminRole: time(getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin), "loadAppData.getDetails.getUserRoleInAdmin"),
allRoles: time(getAllRolesWithoutPermissions("app"), "loadAppData.getDetails.getAllRolesWithoutPermissions"),
myGroups: time(getMyGroups(user.id, currentTenant.id), "loadAppData.getDetails.getMyGroups"),
onboardingSession: time(
OnboardingService.getUserActiveOnboarding({ userId: user.id, tenantId: currentTenant.id, request }),
"loadAppData.getDetails.OnboardingService.getUserActiveOnboarding"
),
effectiveSeatType: time(getUserEffectiveSeatType(userInfo.userId, tenantId), "loadAppData.getDetails.getUserEffectiveSeatType"),
}),
"loadAppData.getDetails"
);
const { tenantUser, tenantTypes, credits, productAccessEntries } = await time(
const { tenantUser, credits, productAccessEntries } = await time(
promiseHash({
tenantUser: time(getTenantUserType(userInfo.userId, tenantId), "loadAppData.postDetails.getTenantUserType"),
tenantTypes: time(getAllTenantTypes(), "loadAppData.postDetails.getAllTenantTypes"),
credits:
CreditTypes.length > 0
? time(getPlanFeatureUsage(tenantId, DefaultFeatures.Credits), "loadAppData.postDetails.getPlanFeatureUsage")
: Promise.resolve(undefined as PlanFeatureUsageDto | undefined),
productAccessEntries: time(
Promise.all(
[...tenantNavigationFeatureKeys, ...tenantConnectorDemoModuleKeys].map(async (featureKey) => [
featureKey,
await resolveTenantProductAccess({
tenantId,
userId: userInfo.userId,
featureKey,
subscription: mySubscription,
tenantRolePermissionNames: allPermissions,
bypassTenantRolePermission: operatorAdmin || !!superAdminRole,
}),
] as const)
),
"loadAppData.postDetails.resolveTenantProductAccess"
resolveTenantProductAccessBatch({
tenantId,
userId: userInfo.userId,
featureKeys: [...tenantNavigationFeatureKeys, ...tenantConnectorDemoModuleKeys],
subscription: mySubscription,
tenantRolePermissionNames: allPermissions,
bypassTenantRolePermission: operatorAdmin,
}),
"loadAppData.postDetails.resolveTenantProductAccessBatch"
),
}),
"loadAppData.postDetails"
);
const currentRole = operatorAdmin ? TenantUserType.ADMIN : tenantUser?.type ?? TenantUserType.MEMBER;
const currentRole = operatorAdmin ? TenantUserType.ADMIN : (tenantUser?.type ?? TenantUserType.MEMBER);
const billingBanner = buildSubscriptionBannerVM({
status: normalizeBillingSubscriptionStatus(mySubscription?.status, {
frozenAt: mySubscription?.frozenAt,
cancelledAt: mySubscription?.cancelledAt,
}),
hasSubscription: mySubscription !== null,
trialEndsAt: mySubscription?.trialEndsAt,
});
const data: AppLoaderData = {
// i18n: i18n.translations,
user,
@@ -164,17 +184,18 @@ export async function loadAppData({
currentTenant,
currentRole,
mySubscription,
billingBanner,
// roles,
allRoles,
permissions: allPermissions.map((f) => f as DefaultPermission),
myGroups,
isSuperUser: !!superUserRole,
isSuperAdmin: !!superAdminRole,
isSuperAdmin: operatorAdmin,
lng: user?.locale ?? userInfo.lng,
onboardingSession,
tenantTypes,
credits,
productAccess: Object.fromEntries(productAccessEntries),
effectiveSeatType,
};
return data;
}
@@ -4,7 +4,8 @@ import { Params } from "react-router";
import { AnalyticsInfoDto } from "~/application/dtos/marketing/AnalyticsInfoDto";
import { ImpersonatingSessionDto } from "~/application/dtos/session/ImpersonatingSessionDto";
import { CookieCategory } from "~/application/cookies/CookieCategory";
import { remixI18Next, i18nCookie } from "~/locale/i18next.server";
import { enabledLocales, remixI18Next, i18nCookie } from "~/locale/i18next.server";
import { resolveEnabledLocale } from "~/locale/i18n";
import { resolveAnrede } from "~/locale/anrede.server";
import { getCurrentEnabledFlagNames } from "~/utils/services/.server/featureFlagsRequest.server";
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
@@ -13,12 +14,20 @@ import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import AnalyticsService from "~/utils/helpers/.server/AnalyticsService";
import CookieHelper from "~/utils/helpers/CookieHelper";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getUserInfo, getUserSession, setCSRFToken, createUserSession, commitSession } from "~/utils/session.server";
import { getUserInfo, getUserSession, getValidatedServerSession, setCSRFToken, createUserSession, commitSession } from "~/utils/session.server";
import { getAbsoluteApiUrl, getAbsoluteUrl, getBaseURL, getDomainName } from "~/utils/url.server";
import { createScopedLogger } from "~/utils/logger.server";
import { AppRootData } from "../useRootData";
import { CSP_NONCE_REQUEST_HEADER, buildDocumentContentSecurityPolicy, getRequestCspNonce } from "~/utils/security/contentSecurityPolicy";
import { getRequestDocumentContentSecurityPolicyOptions } from "~/utils/security/requestContentSecurityPolicy.server";
const rootDataLogger = createScopedLogger("root-data");
const browserBuildEnv = ((import.meta as unknown as { env?: Record<string, string | undefined> }).env ?? {}) as Record<string, string | undefined>;
export async function loadRootData({ request, params }: { request: Request; params: Params }) {
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "root");
const appConfigurationPromise = time(getAppConfiguration({ request }), "getAppConfiguration");
const localePromise = remixI18Next.getLocale(request);
const { userInfo, session, analyticsSession } = await time(
promiseHash({
userInfo: getUserInfo(request),
@@ -27,27 +36,91 @@ export async function loadRootData({ request, params }: { request: Request; para
}),
"loadRootData.session"
);
const user = userInfo.userId ? await getUser(userInfo.userId) : null;
const currentTenant = params.tenant ? await getTenantByIdOrSlug(params.tenant) : user?.defaultTenantId ? await getTenant(user.defaultTenantId) : null;
const [validatedSession, routeTenant] = await Promise.all([
userInfo.userId && !userInfo.impersonatingFromUserId ? getValidatedServerSession(request, userInfo) : Promise.resolve(null),
params.tenant ? getTenantByIdOrSlug(params.tenant) : Promise.resolve(null),
]);
const user =
validatedSession && "user" in validatedSession
? validatedSession.user
: validatedSession && "adminUser" in validatedSession
? {
id: validatedSession.adminUser.id,
email: validatedSession.adminUser.email,
firstName: validatedSession.adminUser.firstName,
lastName: validatedSession.adminUser.lastName,
avatar: validatedSession.adminUser.avatar,
phone: null,
admin: { userId: validatedSession.adminUser.id },
defaultTenantId: null,
createdAt: validatedSession.createdAt,
locale: validatedSession.adminUser.locale,
lightOrDarkMode: null,
}
: userInfo.userId
? await getUser(userInfo.userId)
: null;
const currentTenant = params.tenant ? routeTenant : user?.defaultTenantId ? await getTenant(user.defaultTenantId) : null;
const existingCsrf = session.get("csrf");
const csrf = typeof existingCsrf === "string" && existingCsrf.length > 0 ? existingCsrf : setCSRFToken(session);
let analytics: AnalyticsInfoDto | undefined = undefined;
const appConfiguration = await time(getAppConfiguration({ request }), "getAppConfiguration");
const [appConfiguration, detectedLocale] = await Promise.all([appConfigurationPromise, localePromise]);
const locale = resolveEnabledLocale({
enabledLocales,
userLocale: user?.locale,
cookieLocale: detectedLocale,
acceptLanguage: request.headers.get("Accept-Language"),
});
const hasAnalyticsConsent = CookieHelper.hasConsent(userInfo, CookieCategory.ANALYTICS);
if (appConfiguration.analytics.enabled && hasAnalyticsConsent) {
try {
analytics = await AnalyticsService.getFromRequest({ appConfiguration, request, userId: userInfo.userId ?? null });
} catch (e: any) {
// eslint-disable-next-line no-console
console.error(e.message);
}
}
const analyticsPromise: Promise<AnalyticsInfoDto | undefined> =
appConfiguration.analytics.enabled && hasAnalyticsConsent
? AnalyticsService.getFromRequest({ appConfiguration, request, userId: userInfo.userId ?? null }).catch((error: unknown) => {
rootDataLogger.warn({ err: { name: error instanceof Error ? error.name : "Error" } }, "analytics request enrichment failed");
return undefined;
})
: Promise.resolve(undefined);
const impersonatingSessionPromise: Promise<ImpersonatingSessionDto | null> =
userInfo.impersonatingFromAdminUserId && userInfo.impersonatingFromAdminEmail && userInfo.userId?.length > 0
? getUser(userInfo.userId).then((toUser) =>
toUser
? {
fromUser: { id: userInfo.impersonatingFromAdminUserId!, email: userInfo.impersonatingFromAdminEmail! },
toUser: { id: toUser.id, email: toUser.email },
}
: null
)
: userInfo.impersonatingFromUserId && userInfo.userId?.length > 0
? Promise.all([getUser(userInfo.impersonatingFromUserId), getUser(userInfo.userId)]).then(([fromUser, toUser]) =>
fromUser && toUser ? { fromUser, toUser } : null
)
: Promise.resolve(null);
const anredePromise = resolveAnrede(request, currentTenant);
const featureFlagsPromise = appConfiguration.featureFlags.enabled ? getCurrentEnabledFlagNames({ request, params }) : Promise.resolve([] as string[]);
const sessionCookiePromise = commitSession(session);
const [resolvedAnalytics, impersonatingSession, anrede, featureFlags, sessionCookie] = await Promise.all([
analyticsPromise,
impersonatingSessionPromise,
anredePromise,
featureFlagsPromise,
sessionCookiePromise,
]);
let analytics = resolvedAnalytics;
const webConfig = loadRequiredWebConfig();
const headers = new Headers();
const cspNonce = getRequestCspNonce(request);
if (cspNonce) {
headers.set(CSP_NONCE_REQUEST_HEADER, cspNonce);
headers.set(
"Content-Security-Policy",
buildDocumentContentSecurityPolicy(cspNonce, undefined, getRequestDocumentContentSecurityPolicyOptions(request, webConfig, process.env, browserBuildEnv))
);
}
let userAnalyticsId = analyticsSession.get("userAnalyticsId");
headers.append("Set-Cookie", await commitSession(session));
headers.append("Set-Cookie", sessionCookie);
if (hasAnalyticsConsent) {
if (!userAnalyticsId) {
userAnalyticsId = generateAnalyticsUserId();
@@ -62,27 +135,16 @@ export async function loadRootData({ request, params }: { request: Request; para
headers.append("Set-Cookie", await destroyAnalyticsSession(analyticsSession));
}
let impersonatingSession: ImpersonatingSessionDto | null = null;
if (userInfo.impersonatingFromUserId && userInfo.userId?.length > 0) {
const fromUser = await getUser(userInfo.impersonatingFromUserId);
const toUser = await getUser(userInfo.userId);
if (fromUser && toUser) {
impersonatingSession = { fromUser, toUser };
}
}
const locale = await remixI18Next.getLocale(request);
// Formality axis (du/Sie). Default "du" → `effectiveLng(locale, "du") === locale`,
// so the language handed to `useChangeLanguage` in root.tsx is unchanged and
// rendering stays byte-identical. The tenant's persisted default applies when
// no explicit cookie/param is present.
const anrede = await resolveAnrede(request, currentTenant);
const webConfig = loadRequiredWebConfig();
const data: AppRootData = {
metatags: [{ title: webConfig.appName }],
user,
currentTenant,
locale,
enabledLocales,
anrede,
theme: userInfo.theme || appConfiguration.app.theme,
serverUrl: getBaseURL(request),
@@ -90,7 +152,7 @@ export async function loadRootData({ request, params }: { request: Request; para
apiBaseUrl: getAbsoluteApiUrl(request, "/"),
routing: webConfig.routing,
domainName: getDomainName(request),
userSession: userInfo,
userSession: { ...userInfo, lng: locale },
authenticated: userInfo.userId?.length > 0,
debug: webConfig.nodeEnv === "development",
chatWebsiteId: webConfig.crisp.chatWebsiteId,
@@ -98,7 +160,9 @@ export async function loadRootData({ request, params }: { request: Request; para
csrf,
analytics,
analyticsToken: appConfiguration.analytics.enabled && hasAnalyticsConsent ? webConfig.analytics.token : undefined,
featureFlags: appConfiguration.featureFlags.enabled ? await getCurrentEnabledFlagNames({ request, params }) : [],
webPushVapidPublicKey: webConfig.webPush.vapidPublicKey,
cspNonce,
featureFlags,
impersonatingSession,
};
@@ -110,7 +174,8 @@ export async function loadRootData({ request, params }: { request: Request; para
...userInfo,
metrics: appConfiguration.metrics,
},
new URL(request.url).pathname + new URL(request.url).search
new URL(request.url).pathname + new URL(request.url).search,
{ request }
);
}