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

@@ -372,7 +372,7 @@ async function getFromRequest({ appConfiguration, request, userId }: { appConfig
if (process.env.NODE_ENV === "development") {
ip = "134.201.250.155";
}
const userAgent = request.headers.get("user-agent") ?? navigator.userAgent;
const userAgent = request.headers.get("user-agent") ?? "";
const httpReferrer = request.headers.get("referer")?.toString();
const ref = searchParams.get("ref")?.toString();
const via = searchParams.get("via")?.toString();
@@ -397,7 +397,7 @@ async function getFromRequest({ appConfiguration, request, userId }: { appConfig
const analytics: AnalyticsInfoDto = {
ip,
userAgent: AnalyticsHelper.getUserAgentDetails(userAgent),
userAgent: await AnalyticsHelper.getUserAgentDetails(userAgent),
referrer: {
http: httpReferrer,
via,
@@ -25,12 +25,16 @@ vi.mock("@hivegrid/db/auth-boundary.server", () => ({
vi.mock("~/utils/services/.server/billingStatusService", () => ({
getTenantBillingReadOnlyState: vi.fn(),
}));
vi.mock("~/utils/services/.server/tenantDeletionStatusService", () => ({
getTenantDeletionReadOnlyState: vi.fn(),
}));
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
import { getTenantMember } from "~/utils/db/tenants.db.server";
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
import { getUserInfo } from "~/utils/session.server";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { getTenantDeletionReadOnlyState } from "~/utils/services/.server/tenantDeletionStatusService";
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
import { getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { verifyUserHasPermission } from "./PermissionsService";
@@ -62,6 +66,7 @@ describe("verifyUserHasPermission billing read-only guard", () => {
vi.mocked(getTenantMember).mockResolvedValue({ status: TenantUserStatus.ACTIVE } as never);
vi.mocked(userHasPermission).mockResolvedValue(true);
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValue({ readOnly: false, status: null });
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValue({ readOnly: false, status: "none" });
});
it("blocks mutating tenant requests when billing is read-only", async () => {
@@ -89,3 +94,45 @@ describe("verifyUserHasPermission billing read-only guard", () => {
expect(userHasPermission).toHaveBeenCalledWith("user-1", "tenant-1", "app.settings.subscription.update");
});
});
describe("verifyUserHasPermission deletion_pending read-only guard (AK-P21)", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getUserInfo).mockResolvedValue(userInfo);
vi.mocked(getUser).mockResolvedValue(null);
vi.mocked(getIsSuperAdminByUserId).mockResolvedValue(false);
vi.mocked(getUserRoleInAdmin).mockResolvedValue(null);
vi.mocked(getPermissionName).mockResolvedValue({ id: "perm-1", name: "tasks.create" } as never);
vi.mocked(getTenantMember).mockResolvedValue({ status: TenantUserStatus.ACTIVE } as never);
vi.mocked(userHasPermission).mockResolvedValue(true);
// mockReset also drops un-consumed mockResolvedValueOnce queues from the
// billing describe above (clearAllMocks alone keeps them).
vi.mocked(getTenantBillingReadOnlyState).mockReset().mockResolvedValue({ readOnly: false, status: null });
vi.mocked(getTenantDeletionReadOnlyState).mockReset().mockResolvedValue({ readOnly: false, status: "none" });
});
it("blocks mutating tenant requests during the deletion grace window", async () => {
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValueOnce({ readOnly: true, status: "pending" });
await expectStatus(verifyUserHasPermission(request("POST", "/acme/tasks/new"), "tasks.create", "tenant-1"), 423);
expect(getTenantDeletionReadOnlyState).toHaveBeenCalledWith("tenant-1");
expect(userHasPermission).not.toHaveBeenCalled();
});
it("keeps the privacy area writable so the deletion can be withdrawn", async () => {
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValueOnce({ readOnly: true, status: "pending" });
await expect(
verifyUserHasPermission(request("POST", "/acme/settings/privacy/deletion"), "privacy.tenant_deletion", "tenant-1")
).resolves.toBe(true);
expect(getTenantDeletionReadOnlyState).not.toHaveBeenCalled();
});
it("does not run the deletion guard on read-only requests", async () => {
await expect(verifyUserHasPermission(request("GET", "/acme/tasks"), "tasks.create", "tenant-1")).resolves.toBe(true);
expect(getTenantDeletionReadOnlyState).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,75 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({ getPermissionName: vi.fn() }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
findPermissionByUser: vi.fn(),
userHasPermission: vi.fn(),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenantMember: vi.fn() }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn() }));
vi.mock("~/utils/services/.server/billingStatusService", () => ({
getTenantBillingReadOnlyState: vi.fn(),
}));
vi.mock("~/utils/services/.server/tenantDeletionStatusService", () => ({
getTenantDeletionReadOnlyState: vi.fn(),
}));
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
import { findPermissionByUser, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { getTenantMember } from "~/utils/db/tenants.db.server";
import { getUserInfo } from "~/utils/session.server";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { getTenantDeletionReadOnlyState } from "~/utils/services/.server/tenantDeletionStatusService";
import { getUserPermission, verifyUserHasPermission } from "./PermissionsService";
describe("tenant authorization without platform-admin bypass", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getPermissionName).mockResolvedValue({ id: "permission_1", name: "app.settings.members.view" } as never);
vi.mocked(findPermissionByUser).mockResolvedValue(null);
vi.mocked(userHasPermission).mockResolvedValue(false);
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
vi.mocked(getTenantMember).mockResolvedValue({ status: TenantUserStatus.ACTIVE } as never);
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValue({ readOnly: false } as never);
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValue({ readOnly: false, status: "none" });
});
it("does not grant a tenant permission without a tenant role", async () => {
await expect(
getUserPermission({ userId: "user_1", permissionName: "app.settings.members.view", tenantId: "tenant_1" }),
).resolves.toEqual({
permission: { id: "permission_1", name: "app.settings.members.view" },
userPermission: null,
});
expect(findPermissionByUser).toHaveBeenCalledWith("app.settings.members.view", "user_1", "tenant_1");
});
it("ignores retired platform role assignments when resolving tenant permissions", async () => {
vi.mocked(findPermissionByUser).mockResolvedValue(null);
await expect(
getUserPermission({ userId: "user_1", permissionName: "app.settings.members.view", tenantId: "tenant_1" }),
).resolves.toEqual({
permission: { id: "permission_1", name: "app.settings.members.view" },
userPermission: null,
});
expect(getPermissionName).toHaveBeenCalledWith("app.settings.members.view");
expect(findPermissionByUser).toHaveBeenCalledWith("app.settings.members.view", "user_1", "tenant_1");
});
it("denies an active staff user who lacks the requested tenant permission", async () => {
await expect(
verifyUserHasPermission(
new Request("https://app.example.test/acme/settings/members"),
"app.settings.members.view",
"tenant_1",
),
).rejects.toMatchObject({ status: 302 });
expect(userHasPermission).toHaveBeenCalledWith("user_1", "tenant_1", "app.settings.members.view");
});
});
@@ -24,15 +24,19 @@ vi.mock("~/utils/session.server", () => ({
getUserInfo: vi.fn(),
}));
vi.mock("~/utils/loaders.middleware", () => ({
getIsSuperAdminByUserId: vi.fn(),
vi.mock("~/utils/app/HostRouting.server", () => ({
getHostRoutingContextFromRequest: vi.fn((request: Request) => (new URL(request.url).hostname.startsWith("admin.") ? "admin" : "app")),
}));
vi.mock("~/services/admin/admin-identity.server", () => ({
requireAdminIdentityPermission: vi.fn(),
}));
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
import { userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { getTenantMember } from "~/utils/db/tenants.db.server";
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { getUserInfo } from "~/utils/session.server";
import {
buildPermissionDeniedUrl,
@@ -44,7 +48,7 @@ import {
const mocks = {
getPermissionName: vi.mocked(getPermissionName),
getTenantMember: vi.mocked(getTenantMember),
getIsSuperAdminByUserId: vi.mocked(getIsSuperAdminByUserId),
requireAdminIdentityPermission: vi.mocked(requireAdminIdentityPermission),
getUserInfo: vi.mocked(getUserInfo),
userHasPermission: vi.mocked(userHasPermission),
};
@@ -64,7 +68,7 @@ describe("verifyUserHasPermission", () => {
mocks.getUserInfo.mockResolvedValue({ userId: "user_123" });
mocks.getPermissionName.mockResolvedValue({ id: "perm_123", name: permissionName, description: "Dashboard" });
mocks.getTenantMember.mockResolvedValue({ id: "tenant_user_123", status: TenantUserStatus.ACTIVE } as Awaited<ReturnType<typeof getTenantMember>>);
mocks.getIsSuperAdminByUserId.mockResolvedValue(false);
mocks.requireAdminIdentityPermission.mockResolvedValue({ adminUserId: "admin_123" } as never);
mocks.userHasPermission.mockResolvedValue(true);
});
@@ -135,19 +139,18 @@ describe("verifyUserHasPermission", () => {
expect(mocks.userHasPermission).toHaveBeenCalledTimes(1);
});
it("redirects denied admin permissions without tenant scope", async () => {
mocks.userHasPermission.mockResolvedValue(false);
it("delegates admin-host checks to dedicated AdminRBAC without reading tenant roles", async () => {
await expect(verifyUserHasPermission(new Request("https://admin.example.com/users?jwt=secret"), "admin.users.view", null)).resolves.toBe(true);
expect(mocks.requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.view");
expect(mocks.getUserInfo).not.toHaveBeenCalled();
expect(mocks.userHasPermission).not.toHaveBeenCalled();
});
let location: string | null = null;
try {
await verifyUserHasPermission(new Request("https://admin.example.com/users?jwt=secret"), "admin.users.view", null);
} catch (error) {
location = await expectRedirect(error);
}
expect(location).toBe("/unauthorized/admin.users.view?redirect=%2Fusers");
expect(location).not.toContain("jwt=secret");
expect(mocks.userHasPermission).toHaveBeenCalledWith("user_123", null, "admin.users.view");
it("preserves the AdminRBAC 404 denial contract", async () => {
mocks.requireAdminIdentityPermission.mockRejectedValueOnce(Response.json({}, { status: 404 }));
await expect(verifyUserHasPermission(new Request("https://admin.example.com/users"), "admin.users.view", null)).rejects.toMatchObject({
status: 404,
});
});
});
@@ -1,17 +1,19 @@
import { redirect } from "react-router";
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { isAdminPermissionName } from "@hivegrid/db/admin-permissions";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
import { findPermissionByUser, getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { findPermissionByUser, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
import { getTenantMember } from "~/utils/db/tenants.db.server";
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
import { getUserInfo } from "~/utils/session.server";
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
import { getTenantDeletionReadOnlyState } from "~/utils/services/.server/tenantDeletionStatusService";
import { getHostRoutingContextFromRequest } from "~/utils/app/HostRouting.server";
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
const OPERATOR_ADMIN_BYPASS_DESCRIPTION = "Operator admin tenant permission bypass";
const BILLING_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "billing:status.readOnly" } };
const DELETION_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "settings.privacy.deletion.readOnly" } };
function isMutatingRequest(request: Request): boolean {
return !["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase());
@@ -22,34 +24,40 @@ export function isBillingReadOnlyBypassPath(requestUrl: string): boolean {
return /\/settings\/subscription\/?$/.test(pathname);
}
/**
* AK-P21 — during the tenant-deletion grace window the privacy area stays
* writable: admins must be able to withdraw the request and pull a GDPR
* export; users must be able to manage their account deletion.
*/
export function isDeletionReadOnlyBypassPath(requestUrl: string): boolean {
const pathname = new URL(requestUrl).pathname;
return /\/settings\/privacy(\/|$)/.test(pathname);
}
export async function assertTenantWritableForRequest(request: Request, tenantId: string | null) {
if (!tenantId || !isMutatingRequest(request) || isBillingReadOnlyBypassPath(request.url)) {
if (!tenantId || !isMutatingRequest(request)) {
return;
}
const billingState = await getTenantBillingReadOnlyState(tenantId);
if (billingState.readOnly) {
throw Response.json(BILLING_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
if (!isBillingReadOnlyBypassPath(request.url)) {
const billingState = await getTenantBillingReadOnlyState(tenantId);
if (billingState.readOnly) {
throw Response.json(BILLING_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
}
}
// AK-P21 deletion_pending read-only: reuse of the AK-P20 frozen mechanism.
if (!isDeletionReadOnlyBypassPath(request.url)) {
const deletionState = await getTenantDeletionReadOnlyState(tenantId);
if (deletionState.readOnly) {
throw Response.json(DELETION_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
}
}
}
export async function getUserPermission({ userId, permissionName, tenantId }: { userId: string; permissionName: string; tenantId?: string | null }) {
if (tenantId) {
const user = await getUser(userId);
const isOperatorAdmin = !!user?.admin || (await getIsSuperAdminByUserId(userId)) || !!(await getUserRoleInAdmin(userId, DefaultAdminRoles.SuperAdmin));
if (isOperatorAdmin) {
return {
permission: { id: "operator-admin-bypass", name: permissionName, description: OPERATOR_ADMIN_BYPASS_DESCRIPTION },
userPermission: permissionName,
};
}
}
const permission = await getPermissionName(permissionName);
if (!permission) {
return { permission, userPermission: undefined };
}
if (tenantId && (await getIsSuperAdminByUserId(userId))) {
return { permission, userPermission: permission.name };
}
// const userRoles = await getUserRoles(userId ?? undefined, tenantId ?? null);
// let userPermission: Permission | undefined = undefined;
// userRoles.forEach((userRole) => {
@@ -102,6 +110,13 @@ export function shapePermissionCheckResult({
}
export async function verifyUserHasPermission(request: Request, permissionName: DefaultPermission, tenantId: string | null = null) {
if (getHostRoutingContextFromRequest(request) === "admin") {
if (!isAdminPermissionName(permissionName)) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
await requireAdminIdentityPermission(request, permissionName);
return true;
}
// if (permissionName.startsWith("entity.")) {
// return true;
// }
@@ -112,15 +127,6 @@ export async function verifyUserHasPermission(request: Request, permissionName:
throw Error("Unauthorized");
}
await assertTenantWritableForRequest(request, tenantId);
if (tenantId) {
const user = await getUser(userInfo.userId);
const isOperatorAdmin =
!!user?.admin || (await getIsSuperAdminByUserId(userInfo.userId)) || !!(await getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin));
if (isOperatorAdmin) {
shapePermissionCheckResult({ allowed: true, permissionName, tenantId });
return true;
}
}
const permission = await getPermissionName(permissionName);
if (!permission) {
shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" });
@@ -1,148 +0,0 @@
import { TFunction } from "i18next";
import { EntityWithDetails } from "../../db/entities/entities.db.server";
import { RowWithDetails, getRowById } from "../../db/entities/rows.db.server";
import ApiHelper, { ApiFormatOptions } from "../ApiHelper";
import RowHelper from "../RowHelper";
import { getTenant } from "../../db/tenants.db.server";
import { RowAsJson } from "../TemplateApiHelper";
async function fetchRowWithRelationships({
rowId,
scope,
entities,
processedRows = new Set<string>(),
backlog = [], // This will be used to store the deferred relationships to be fetched later.
}: {
rowId: string;
scope: { entityId?: string; tenantId: string | null };
entities: EntityWithDetails[];
processedRows?: Set<string>;
backlog?: { rowId: string; relation: "parent" | "child"; attachTo: RowWithDetails; scope: { entityId?: string; tenantId: string | null } }[];
}): Promise<RowWithDetails | null> {
if (processedRows.has(rowId)) {
return null;
}
processedRows.add(rowId);
const row = await getRowById(rowId, scope);
if (!row) {
return null;
}
// Fetch parent relationships.
for (const parentRow of row.parentRows) {
backlog.push({ rowId: parentRow.parent.id, relation: "parent", attachTo: row, scope: { entityId: parentRow.parent.entityId, tenantId: parentRow.parent.tenantId } });
}
// Fetch child relationships.
for (const childRow of row.childRows) {
backlog.push({ rowId: childRow.child.id, relation: "child", attachTo: row, scope: { entityId: childRow.child.entityId, tenantId: childRow.child.tenantId } });
}
// Process the backlog.
while (backlog.length > 0) {
const { rowId: backlogRowId, relation, attachTo, scope: backlogScope } = backlog.shift()!;
if (relation === "parent") {
const parent = await fetchRowWithRelationships({ rowId: backlogRowId, scope: backlogScope, entities, processedRows, backlog });
if (parent) {
const parentRow = attachTo.parentRows.find((p) => p.parent.id === backlogRowId);
if (parentRow) {
parentRow.parent = parent;
}
}
} else if (relation === "child") {
const child = await fetchRowWithRelationships({ rowId: backlogRowId, scope: backlogScope, entities, processedRows, backlog });
if (child) {
const childRow = attachTo.childRows.find((c) => c.child.id === backlogRowId);
if (childRow) {
childRow.child = child;
}
}
}
}
return row;
}
async function getRowInApiFormatWithRecursiveRelationships({
entities,
rowId,
scope,
t,
options,
}: {
entities: EntityWithDetails[];
rowId: string;
scope: { entityId?: string; tenantId: string | null };
t: TFunction;
options: ApiFormatOptions;
}): Promise<RowAsJson | null> {
const row = await fetchRowWithRelationships({ rowId, scope, entities });
if (!row) {
return null;
}
pruneDuplicateRows(row);
const entity = entities.find((entity) => entity.id === row.entityId);
if (!entity) {
throw new Error(`Entity ${row.entityId} not found.`);
}
const apiFormat = ApiHelper.getApiFormatWithRelationships({ entities, item: row, options });
return {
id: row.id,
name: RowHelper.getTextDescription({ entity, item: row, t }),
entityId: entity.id,
tenant: row.tenantId ? await getTenant(row.tenantId) : null,
data: {
[entity.name]: apiFormat,
},
};
}
function pruneDuplicateRows(mainRow: RowWithDetails): void {
const seenRowIds: Set<string> = new Set();
let currentLevelRows: RowWithDetails[] = [mainRow];
while (currentLevelRows.length > 0) {
const nextLevelRows: RowWithDetails[] = [];
for (const row of currentLevelRows) {
if (!row) continue;
// Process parent rows
if (row.parentRows) {
for (let i = row.parentRows.length - 1; i >= 0; i--) {
const parent = row.parentRows[i].parent;
if (seenRowIds.has(parent.id)) {
row.parentRows.splice(i, 1); // Remove this parent
} else {
nextLevelRows.push(parent as RowWithDetails);
}
}
}
// Process child rows
if (row.childRows) {
for (let i = row.childRows.length - 1; i >= 0; i--) {
const child = row.childRows[i].child;
if (seenRowIds.has(child.id)) {
row.childRows.splice(i, 1); // Remove this child
} else {
nextLevelRows.push(child as RowWithDetails);
}
}
}
// Mark the row as seen
seenRowIds.add(row.id);
}
// Move to the next level
currentLevelRows = nextLevelRows;
}
}
export default {
getRowInApiFormatWithRecursiveRelationships,
};
@@ -0,0 +1,53 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("platform", () => ({
default: {
name: "Example Browser",
version: "1.2.3",
os: { family: "Example OS", version: "4.5.6" },
},
}));
import { createAnonymousAnalyticsPayload, getUserAgentDetails } from "./AnalyticsHelper";
describe("getUserAgentDetails", () => {
it("loads browser details on demand and classifies the supplied user agent", async () => {
await expect(getUserAgentDetails("Mozilla/5.0 (iPhone; Mobile)")).resolves.toEqual({
type: "mobile",
os: { family: "Example OS", version: "4.5.6" },
browser: { name: "Example Browser", version: "1.2.3" },
});
});
});
describe("anonymous analytics payload", () => {
it("never forwards authenticated user or portal identity fields", () => {
expect(
createAnonymousAnalyticsPayload(
{
userAnalyticsId: "visitor-1",
userId: "user-1",
portalId: "portal-1",
portalUserId: "portal-user-1",
ip: "192.0.2.1",
referrer: { source: "newsletter" },
region: { country: "DE" },
},
{
type: "desktop",
os: { family: "Example OS", version: "4.5.6" },
browser: { name: "Example Browser", version: "1.2.3" },
}
)
).toEqual({
userAnalyticsId: "visitor-1",
referrer: { source: "newsletter" },
region: { country: "DE" },
userAgent: {
type: "desktop",
os: { family: "Example OS", version: "4.5.6" },
browser: { name: "Example Browser", version: "1.2.3" },
},
});
});
});
@@ -1,4 +1,3 @@
import platform from "platform";
import { CookieCategory } from "~/application/cookies/CookieCategory";
import CookieHelper from "./CookieHelper";
import { AppRootData } from "../data/useRootData";
@@ -14,7 +13,9 @@ type AnalyticsProps = {
};
export async function addPageView({ url, rootData, route }: AnalyticsProps) {
if (rootData.analytics && CookieHelper.hasConsent(rootData.userSession, CookieCategory.ANALYTICS)) {
const analytics = rootData.analytics;
const userAnalyticsId = analytics?.userAnalyticsId;
if (analytics && userAnalyticsId && CookieHelper.hasConsent(rootData.userSession, CookieCategory.ANALYTICS)) {
// console.log("[PAGE VIEW]", JSON.stringify({ url, analytics: rootData.analytics }));
try {
await fetch(new URL(apiPath("analytics/page-views", { mode: "host-aware" }), rootData.apiBaseUrl), {
@@ -23,10 +24,7 @@ export async function addPageView({ url, rootData, route }: AnalyticsProps) {
body: JSON.stringify({
url,
route,
analytics: {
...rootData.analytics,
userAgent: getUserAgentDetails(),
},
analytics: createAnonymousAnalyticsPayload({ ...analytics, userAnalyticsId }, await getUserAgentDetails()),
}),
});
} catch (e: any) {
@@ -44,7 +42,9 @@ type EventProps = AnalyticsProps & {
value: string;
};
export async function addEvent({ url, route, action, category, label, value, rootData }: EventProps) {
if (rootData.analytics && CookieHelper.hasConsent(rootData.userSession, CookieCategory.ANALYTICS)) {
const analytics = rootData.analytics;
const userAnalyticsId = analytics?.userAnalyticsId;
if (analytics && userAnalyticsId && CookieHelper.hasConsent(rootData.userSession, CookieCategory.ANALYTICS)) {
// console.log("[EVENT]", JSON.stringify({ action, category, label, value, url, analytics: rootData.analytics }));
try {
await fetch(new URL(apiPath("analytics/events", { mode: "host-aware" }), rootData.apiBaseUrl), {
@@ -57,10 +57,7 @@ export async function addEvent({ url, route, action, category, label, value, roo
value,
url,
route,
analytics: {
...rootData.analytics,
userAgent: getUserAgentDetails(),
},
analytics: createAnonymousAnalyticsPayload({ ...analytics, userAnalyticsId }, await getUserAgentDetails()),
}),
});
} catch (e: any) {
@@ -70,7 +67,23 @@ export async function addEvent({ url, route, action, category, label, value, roo
}
}
function getUserAgentDetails(userAgent?: string) {
export function createAnonymousAnalyticsPayload(
analytics: NonNullable<AppRootData["analytics"]> & { userAnalyticsId: string },
userAgent: Awaited<ReturnType<typeof getUserAgentDetails>>
) {
return {
userAnalyticsId: analytics.userAnalyticsId,
...(analytics.referrer ? { referrer: analytics.referrer } : {}),
...(analytics.region ? { region: analytics.region } : {}),
userAgent,
};
}
export async function getUserAgentDetails(userAgent?: string) {
// `platform` is ~16 KiB minified and this helper is part of the root route.
// Load the parser only after analytics consent caused an event to be sent,
// keeping it out of every visitor's hydration graph.
const { default: platform } = await import("platform");
const deviceType = () => {
if (!userAgent) {
return undefined;
@@ -17,7 +17,6 @@ function permissionsData(patch: Partial<AppOrAdminData> = {}): AppOrAdminData {
isSuperAdmin: false,
myGroups: [],
onboardingSession: null,
tenantTypes: [],
...patch,
};
}
@@ -1,11 +1,35 @@
import { describe, expect, it } from "vitest";
import Constants from "~/application/Constants";
import { getPaginationFromCurrentUrl } from "./RowPaginationHelper";
import { getPaginationFromCurrentUrl, getTotalPages } from "./RowPaginationHelper";
function paginationFor(query: string) {
return getPaginationFromCurrentUrl(new URLSearchParams(query));
}
describe("getTotalPages", () => {
it("never renders NaN when an upstream provider reports no page size", () => {
// Regression guard for the admin notification tables, which showed "1/NAN"
// whenever the provider call returned nothing (0 / 0).
expect(getTotalPages(0, 0)).toBe(1);
expect(getTotalPages(undefined, undefined)).toBe(1);
expect(getTotalPages(null, null)).toBe(1);
expect(getTotalPages(Number.NaN, Number.NaN)).toBe(1);
});
it("keeps at least one page for an empty result set", () => {
expect(getTotalPages(0, 10)).toBe(1);
});
it("rounds partial pages up", () => {
expect(getTotalPages(41, 10)).toBe(5);
expect(getTotalPages(40, 10)).toBe(4);
});
it("falls back to the default page size for non-positive sizes", () => {
expect(getTotalPages(25, -5)).toBe(Math.ceil(25 / Constants.DEFAULT_PAGE_SIZE));
});
});
describe("RowPaginationHelper", () => {
it("defaults invalid pagination params before they reach database queries", () => {
expect(paginationFor("page=abc&pageSize=abc")).toMatchObject({
@@ -12,6 +12,18 @@ export function getPaginationFromCurrentUrl(urlSearchParams: URLSearchParams): {
};
}
/**
* Total page count for a paginated result set, safe against the two inputs that
* otherwise reach the UI as "1/NAN": a missing page size (`0/0` → `NaN`) and an
* absent total (upstream provider returned nothing). There is always at least
* one page, because an empty list still renders as page 1 of 1.
*/
export function getTotalPages(totalItems: number | null | undefined, pageSize: number | null | undefined): number {
const total = Number.isFinite(totalItems) ? Number(totalItems) : 0;
const size = Number.isFinite(pageSize) && Number(pageSize) > 0 ? Number(pageSize) : Constants.DEFAULT_PAGE_SIZE;
return Math.max(1, Math.ceil(total / size));
}
export function getFiltersFromCurrentUrl(request: Request, properties: FilterablePropertyDto[]): FiltersDto {
const url = new URL(request.url);
properties.forEach((property) => {
@@ -8,7 +8,6 @@ const selectSimpleTenantProperties = {
icon: true,
logo: true,
deactivatedReason: true,
types: true,
active: true,
theme: true,
themeConfig: true,
@@ -28,7 +27,6 @@ const includeTenantWithDetails = {
},
},
},
types: true,
};
const includeTenantWithUsage = {
@@ -43,7 +41,6 @@ const includeTenantWithUsage = {
products: { include: { ...TenantSubscriptionProductModelHelper.includeTenantSubscriptionProductDetails } },
},
},
types: true,
_count: true,
};
@@ -15,7 +15,6 @@ const selectWithAvatar = {
lastName: true,
avatar: true,
phone: true,
admin: true,
defaultTenantId: true,
createdAt: true,
locale: true,