Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,5 +1,5 @@
import { createCookieSessionStorage, redirect, Session } from "react-router";
import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@toolctrl/config";
import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@hivegrid/config";
import { randomBytes } from "crypto";
export type AnalyticsSession = {
@@ -1,88 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { EntitiesApi } from "./EntitiesApi";
import { findEntityByName, findEntityBySlug, getEntityByPrefix } from "../../db/entities/entities.db.server";
vi.mock("../../db/entities/entities.db.server", () => ({
findEntityByName: vi.fn(),
findEntityBySlug: vi.fn(),
getEntityByIdOrName: vi.fn(),
getEntityByPrefix: vi.fn(),
}));
vi.mock("../../services/.server/subscriptionService", () => ({
getPlanFeatureUsage: vi.fn(),
}));
describe("EntitiesApi.validateEntity", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(findEntityByName).mockResolvedValue(null);
vi.mocked(findEntityBySlug).mockResolvedValue(null);
vi.mocked(getEntityByPrefix).mockResolvedValue(null);
});
it("rejects entity slugs that would collide with canonical tenant child routes", async () => {
await expect(
EntitiesApi.validateEntity({
tenantId: null,
name: "settings",
slug: " Settings ",
order: null,
prefix: "set",
})
).resolves.toContain("Reserved entity slug ' Settings ' conflicts with a workspace route");
});
});
describe("EntitiesApi.getNoCodeRoutes", () => {
it("does not classify tenant slugs that only start with admin as admin routes", () => {
const routes = EntitiesApi.getNoCodeRoutes({
request: new Request("http://app.localhost:3000/adminish/g/sales/contact"),
params: { tenant: "adminish", group: "sales" },
});
expect(routes.list).toBe("/adminish/g/sales/:entity");
expect(routes.overview).toBe("/adminish/g/sales/:entity/:id");
});
it("uses existing no-code entity routes for admin grouped entity contexts", () => {
const routes = EntitiesApi.getNoCodeRoutes({
request: new Request("http://admin.localhost:3000/g/sales/contact"),
params: { group: "sales" },
});
expect(routes.list).toBe("/entities/:entity/no-code/:entity");
expect(routes.new).toBe("/entities/:entity/no-code/:entity/new");
expect(routes.overview).toBe("/entities/:entity/no-code/:entity/:id");
expect(routes.edit).toBe("/entities/:entity/no-code/:entity/:id/edit");
expect(routes.import).toBe("/entities/:entity/no-code/:entity/import");
expect(routes.export).toBe("/entities/:entity/no-code/:entity/export");
expect(routes.group).toBe("/entities/groups");
});
it("uses host context instead of removed admin path prefixes", () => {
const request = new Request("https://unknown.example.test/admin/entities/company/no-code/company");
const routes = EntitiesApi.getNoCodeRoutes({ request, params: { tenant: "acme" } });
expect(routes.list).toBe("/acme/:entity");
expect(routes.list).not.toBe("/entities/:entity/no-code/:entity");
});
it("does not treat removed tenant-prefixed runtime paths as app context for grouped routes", () => {
const request = new Request("https://unknown.example.test/app/acme/g/sales/company");
const routes = EntitiesApi.getNoCodeRoutes({ request, params: { tenant: "acme", group: "sales" } });
expect(routes.group).toBeUndefined();
expect(routes.list).toBe("/acme/:entity");
});
it("matches tenant CRM routes by exact path segment", () => {
const crmRequest = new Request("https://app.example.test/acme/crm/company");
const crmishRequest = new Request("https://app.example.test/acme/crmish/company");
expect(EntitiesApi.getNoCodeRoutes({ request: crmRequest, params: { tenant: "acme" } }).list).toBe("/acme/crm/:entity");
expect(EntitiesApi.getNoCodeRoutes({ request: crmishRequest, params: { tenant: "acme" } }).list).toBe("/acme/:entity");
});
});
@@ -1,190 +0,0 @@
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { EntityWithDetails, findEntityByName, findEntityBySlug, getEntityByIdOrName, getEntityByPrefix } from "../../db/entities/entities.db.server";
import { getPlanFeatureUsage } from "../../services/.server/subscriptionService";
import { Entity } from "@toolctrl/db/prisma-browser";
import { Params } from "react-router";
import { getAbsoluteUrl } from "../../url.server";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { getHostRoutingContextFromRequest } from "~/utils/app/HostRouting.server";
import { isReservedTenantChildRouteSlug } from "~/utils/services/tenantService";
export namespace EntitiesApi {
export type GetEntityData = {
entity: EntityWithDetails;
featureUsageEntity?: PlanFeatureUsageDto | undefined;
};
export type Routes = {
list?: string;
new?: string;
overview?: string;
edit?: string;
publicUrl?: string;
import?: string;
export?: string;
group?: string;
};
export async function get({ entity, tenantId, userId }: { entity: { id?: string; name?: string }; tenantId?: string | null; userId?: string }) {
const item = await getEntityByIdOrName({ tenantId, ...entity });
const featureUsageEntity = tenantId ? await getPlanFeatureUsage(tenantId, item.name) : undefined;
await fillSystemProperties({ entity: item, tenantId, userId });
const data: GetEntityData = {
entity: item,
featureUsageEntity,
};
return data;
}
export async function validateEntity({
tenantId,
name,
slug,
order,
prefix,
entity,
}: {
tenantId: string | null;
name: string;
slug: string;
order: number | null;
prefix: string;
entity?: Entity;
}) {
const errors: string[] = [];
if (isReservedTenantChildRouteSlug(slug)) {
errors.push(`Reserved entity slug '${slug}' conflicts with a workspace route`);
}
if (!entity || entity?.name !== name) {
const existingName = await findEntityByName({ tenantId, name });
if (existingName) {
errors.push(`Existing entity with name '${name}': ${existingName.slug}`);
}
}
if (!entity || entity?.slug !== slug) {
const existingSlug = await findEntityBySlug(slug);
if (existingSlug) {
errors.push(`Existing entity with slug '${slug}': ${existingSlug.slug}`);
}
}
// if (order) {
// if (!entity || entity?.order !== order) {
// const existingOrder = await getEntityByOrder(order);
// if (existingOrder) {
// errors.push(`Existing entity with order '${order}': ${existingOrder.slug}`);
// }
// }
// }
if (!entity || entity?.prefix !== prefix) {
const existingPrefix = await getEntityByPrefix(prefix);
if (existingPrefix) {
errors.push(`Existing entity with prefix '${prefix}': ${existingPrefix.slug}`);
}
}
return errors;
}
export function getNoCodeRoutes({ request, params }: { request: Request; params: Params }): EntitiesApi.Routes {
const url = new URL(request.url);
const hostContext = getHostRoutingContextFromRequest(request);
const isAdminRequest = hostContext === "admin";
const isAppRequest = hostContext === "app";
const adminRoute = (path: string) => adminPath(path, { mode: "host-aware" });
const tenantRoute = (path: string) => appPath({ tenantSlug: params?.tenant ?? "", path, mode: "host-aware" });
if (params.group) {
if (isAdminRequest) {
const routes: EntitiesApi.Routes = {
list: adminRoute("entities/:entity/no-code/:entity"),
new: adminRoute("entities/:entity/no-code/:entity/new"),
overview: adminRoute("entities/:entity/no-code/:entity/:id"),
edit: adminRoute("entities/:entity/no-code/:entity/:id/edit"),
import: adminRoute("entities/:entity/no-code/:entity/import"),
export: adminRoute("entities/:entity/no-code/:entity/export"),
publicUrl: getAbsoluteUrl(request, `/public/:entity/:id`),
group: adminRoute("entities/groups"),
};
return routes;
} else if (isAppRequest) {
const routes: EntitiesApi.Routes = {
list: tenantRoute(`g/${params.group}/:entity`),
new: tenantRoute(`g/${params.group}/:entity/new`),
overview: tenantRoute(`g/${params.group}/:entity/:id`),
edit: tenantRoute(`g/${params.group}/:entity/:id/edit`),
import: tenantRoute(`g/${params.group}/:entity/import`),
export: tenantRoute(`g/${params.group}/:entity/export`),
publicUrl: getAbsoluteUrl(request, `/public/:entity/:id`),
group: tenantRoute(`g/${params.group}`),
};
return routes;
}
} else if (isAdminRequest && isPathOrChild(url.pathname, "/crm")) {
const routes: EntitiesApi.Routes = {
list: adminRoute("crm/:entity"),
new: adminRoute("crm/:entity/new"),
overview: adminRoute("crm/:entity/:id"),
edit: adminRoute("crm/:entity/:id/edit"),
import: adminRoute("crm/:entity/import"),
export: adminRoute("crm/:entity/export"),
publicUrl: getAbsoluteUrl(request, `/public/:entity/:id`),
};
return routes;
} else if (isAdminRequest) {
const routes: EntitiesApi.Routes = {
list: adminRoute("entities/:entity/no-code/:entity"),
new: adminRoute("entities/:entity/no-code/:entity/new"),
overview: adminRoute("entities/:entity/no-code/:entity/:id"),
edit: adminRoute("entities/:entity/no-code/:entity/:id/edit"),
import: adminRoute("entities/:entity/no-code/:entity/import"),
export: adminRoute("entities/:entity/no-code/:entity/export"),
publicUrl: getAbsoluteUrl(request, `/public/:entity/:id`),
};
return routes;
} else if (params?.tenant && isPathOrChild(url.pathname, `/${params.tenant}/crm`)) {
const routes: EntitiesApi.Routes = {
list: tenantRoute("crm/:entity"),
new: tenantRoute("crm/:entity/new"),
overview: tenantRoute("crm/:entity/:id"),
edit: tenantRoute("crm/:entity/:id/edit"),
import: tenantRoute("crm/:entity/import"),
export: tenantRoute("crm/:entity/export"),
publicUrl: getAbsoluteUrl(request, `/public/:entity/:id`),
};
return routes;
}
const routes: EntitiesApi.Routes = {
list: tenantRoute(":entity"),
new: tenantRoute(":entity/new"),
overview: tenantRoute(":entity/:id"),
edit: tenantRoute(":entity/:id/edit"),
import: tenantRoute(":entity/import"),
export: tenantRoute(":entity/export"),
publicUrl: getAbsoluteUrl(request, `/public/:entity/:id`),
};
return routes;
}
export async function fillSystemProperties({
entity,
tenantId,
userId,
}: {
entity: EntityWithDetails;
tenantId: string | null | undefined;
userId: string | undefined;
}) {
// const userProp = entity.properties.find((f) => f.name === "user");
// if (userProp) {
// const users = await adminGetAllUsersNames();
// userProp.options = users.map((f) => ({
// value: f.email,
// name: f.email,
// })) as PropertyOption[];
// }
}
}
function isPathOrChild(pathname: string, prefix: string) {
return pathname === prefix || pathname.startsWith(`${prefix}/`);
}
@@ -1,19 +0,0 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "EntityViewsApi.ts"), "utf8");
describe("EntityViewsApi tenant scope", () => {
test("validates entity views against the current tenant/user scope", () => {
expect(source).toContain("validateEntityView({ entityId: entity.id, isDefault, name, title, order: null, tenantId, userId })");
expect(source).toContain("tenantId: item.tenantId, userId: item.userId");
expect(source).toContain("const views = await getEntityViews(entityId, { tenantId, userId })");
});
test("loads entity views by id through the current entity and tenant scope", () => {
expect(source).toContain("getEntityView(id, { entityId: entity.id, tenantId })");
});
});
@@ -1,358 +0,0 @@
import { EntityView } from "@toolctrl/db/prisma-browser";
import { EntityWithDetails, getEntityByName } from "../../db/entities/entities.db.server";
import {
createEntityView,
EntityViewWithDetails,
getEntityView,
getEntityViewByName,
getEntityViewDefault,
getEntityViews,
updateEntityViewFilters,
updateEntityViewProperties,
updateEntityViewSort,
updateScopedEntityView,
updateScopedEntityViewFilters,
updateScopedEntityViewProperties,
updateScopedEntityViewSort,
} from "../../db/entities/entityViews.db.server";
import { RowsApi } from "./RowsApi";
import { getUser } from "../../db/users.db.server";
import { getTenant } from "../../db/tenants.db.server";
import { PropertyType } from "~/application/enums/entities/PropertyType";
export namespace EntityViewsApi {
export type GetEntityViewsWithRows = {
view: EntityViewWithDetails | undefined;
rowsData: RowsApi.GetRowsData;
rowsCount: number;
};
export async function getAll({
entityName,
tenantId,
withDefault = true,
withRows = true,
}: {
entityName: string;
tenantId: string | null;
withDefault: boolean;
withRows: boolean;
}): Promise<GetEntityViewsWithRows[]> {
const entity = await getEntityByName({ tenantId, name: entityName });
const views = await getEntityViews(entity.id, { tenantId });
let allViews: (EntityViewWithDetails | undefined)[] = views;
if (withDefault) {
allViews = [undefined, ...views];
}
return await Promise.all(
allViews.map(async (entityView) => {
let rowsData = await RowsApi.getAll({
entity,
tenantId,
entityView,
urlSearchParams: new URLSearchParams(),
pageSize: 10000,
});
const rowsCount = rowsData.items.length;
if (!withRows) {
rowsData = { ...rowsData, items: [] };
}
const data: GetEntityViewsWithRows = {
view: entityView,
rowsData,
rowsCount,
};
return data;
})
);
}
export async function get(
id: string | undefined,
{ entityName, tenantId, pageSize }: { entityName: string; tenantId: string | null; pageSize?: number }
): Promise<GetEntityViewsWithRows | null> {
const entity = await getEntityByName({ tenantId, name: entityName });
if (!entity) {
return null;
}
let view: EntityViewWithDetails | null = null;
if (id) {
view = await getEntityView(id, { entityId: entity.id, tenantId });
if (!view) {
return null;
}
}
const rowsData = await RowsApi.getAll({
entity,
tenantId,
entityView: view ?? undefined,
urlSearchParams: new URLSearchParams(),
pageSize,
});
const data: GetEntityViewsWithRows = {
view: view ?? undefined,
rowsData,
rowsCount: rowsData.items.length,
};
return data;
}
export async function createFromForm({ entity, form, createdByUserId }: { form: FormData; entity: EntityWithDetails; createdByUserId: string }) {
const layout = form.get("layout")?.toString() ?? "";
const name = form.get("name")?.toString().toLowerCase() ?? "";
const title = form.get("title")?.toString() ?? "";
const pageSize = Number(form.get("pageSize"));
const isDefault = Boolean(form.get("isDefault"));
// Board
const groupBy = form.get("groupBy")?.toString() ?? undefined;
const groupByPropertyId = form.get("groupByPropertyId")?.toString() ?? undefined;
// Grid
const gridColumns = Number(form.get("gridColumns") ?? 0);
const gridColumnsSm = Number(form.get("gridColumnsSm") ?? 0);
const gridColumnsMd = Number(form.get("gridColumnsMd") ?? 0);
const gridColumnsLg = Number(form.get("gridColumnsLg") ?? 0);
const gridColumnsXl = Number(form.get("gridColumnsXl") ?? 0);
const gridColumns2xl = Number(form.get("gridColumns2xl") ?? 0);
const gridGap = form.get("gridGap")?.toString() ?? "sm";
const isSystem = form.get("isSystem") === "true";
let tenantId: string | null = form.get("tenantId")?.toString() ?? null;
let userId: string | null = form.get("userId")?.toString() ?? null;
if (!tenantId?.toString().trim()) {
tenantId = null;
}
if (!userId?.toString().trim()) {
userId = null;
}
const errors = [
...(await validateEntityView({ entityId: entity.id, isDefault, name, title, order: null, tenantId, userId })),
...(await validateGroupBy(entity, layout, groupBy, groupByPropertyId)),
];
if (errors.length > 0) {
throw Error(errors.join(", "));
}
const properties: { propertyId: string; name: string; order: number }[] = form.getAll("properties[]").map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
if (properties.length === 0) {
throw Error("Add at least one property to display");
}
const filters: { name: string; condition: string; value: string; match: string }[] = form.getAll("filters[]").map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
const sort: { name: string; asc: boolean; order: number }[] = form.getAll("sort[]").map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
if (tenantId) {
const tenant = await getTenant(tenantId);
if (!tenant) {
// eslint-disable-next-line no-console
console.log("Invalid account", { tenantId });
throw Error("Invalid account");
}
}
if (userId) {
const user = await getUser(userId);
if (!user) {
// eslint-disable-next-line no-console
console.log("Invalid user", { userId });
throw Error("Invalid user");
}
}
try {
const entityView = await createEntityView({
entityId: entity.id,
tenantId: tenantId,
userId: userId,
createdByUserId,
layout,
name,
title,
isDefault,
pageSize,
groupByPropertyId: groupBy === "byProperty" ? groupByPropertyId ?? null : null,
gridColumns,
gridColumnsSm,
gridColumnsMd,
gridColumnsLg,
gridColumnsXl,
gridColumns2xl,
gridGap,
isSystem,
});
await updateEntityViewProperties(entityView.id, properties);
await updateEntityViewFilters(entityView.id, filters);
await updateEntityViewSort(entityView.id, sort);
return entityView;
} catch (e: any) {
throw Error(e.message);
}
}
export async function updateFromForm({ item, entity, form }: { item: EntityView; form: FormData; entity: EntityWithDetails }) {
const layout = form.get("layout")?.toString() ?? "";
const name = form.get("name")?.toString() ?? "";
const title = form.get("title")?.toString() ?? "";
const pageSize = Number(form.get("pageSize"));
const order = Number(form.get("order"));
const isDefault = Boolean(form.get("isDefault"));
// Board
const groupBy = form.get("groupBy")?.toString() ?? undefined;
const groupByPropertyId = form.get("groupByPropertyId")?.toString() ?? undefined;
// Grid
const gridColumns = Number(form.get("gridColumns") ?? 0);
const gridColumnsSm = Number(form.get("gridColumnsSm") ?? 0);
const gridColumnsMd = Number(form.get("gridColumnsMd") ?? 0);
const gridColumnsLg = Number(form.get("gridColumnsLg") ?? 0);
const gridColumnsXl = Number(form.get("gridColumnsXl") ?? 0);
const gridColumns2xl = Number(form.get("gridColumns2xl") ?? 0);
const gridGap = form.get("gridGap")?.toString() ?? "sm";
const errors = [
...(await validateEntityView({ entityId: entity.id, isDefault, name, title, order, entityView: item, tenantId: item.tenantId, userId: item.userId })),
...(await validateGroupBy(entity, layout, groupBy, groupByPropertyId)),
];
if (errors.length > 0) {
throw Error(errors.join(", "));
}
const properties: { propertyId: string; name: string; order: number }[] = form.getAll("properties[]").map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
if (properties.length === 0) {
throw Error("Add at least one property to display");
}
const filters: { name: string; condition: string; value: string; match: string }[] = form.getAll("filters[]").map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
const sort: { name: string; asc: boolean; order: number }[] = form.getAll("sort[]").map((f: FormDataEntryValue) => {
return JSON.parse(f.toString());
});
try {
const viewScope = {
id: item.id,
entityId: entity.id,
tenantId: item.tenantId,
userId: item.userId,
};
const view = await updateScopedEntityView(viewScope, {
order,
layout,
name,
title,
isDefault,
pageSize,
groupByPropertyId: groupBy === "byProperty" ? groupByPropertyId ?? null : null,
gridColumns,
gridColumnsSm,
gridColumnsMd,
gridColumnsLg,
gridColumnsXl,
gridColumns2xl,
gridGap,
});
await updateScopedEntityViewProperties(viewScope, properties);
await updateScopedEntityViewFilters(viewScope, filters);
await updateScopedEntityViewSort(viewScope, sort);
return view;
} catch (e: any) {
throw Error(e.message);
}
}
export const getCurrentEntityView = async (
entityId: string,
urlParams: URLSearchParams,
{ tenantId, userId }: { tenantId?: string | null; userId?: string | null } = {}
) => {
const name = urlParams.get("v");
if (name) {
return await getEntityViewByName({ entityId, name, isSystem: false, tenantId, userId });
} else {
return await getEntityViewDefault({ entityId, isSystem: false, tenantId, userId });
}
};
const validateEntityView = async ({
entityId,
isDefault,
name,
title,
order,
entityView,
tenantId,
userId,
}: {
entityId: string;
isDefault: boolean;
name: string;
title: string;
order: number | null;
entityView?: EntityView;
tenantId: string | null;
userId: string | null;
}) => {
const errors: string[] = [];
const views = await getEntityViews(entityId, { tenantId, userId });
if (isDefault && userId) {
const defaultView = views.find((f) => f.id !== entityView?.id && f.isDefault && f.userId === userId);
if (defaultView) {
errors.push(`Existing default entity view with title: ${defaultView.title}`);
}
}
if (!entityView || entityView?.name !== name) {
const existingName = views.find((f) => f.id !== entityView?.id && f.name.toLowerCase() === name.toLowerCase());
if (existingName) {
errors.push(`Existing entity view with name: ${existingName.name}`);
}
}
if (!entityView || entityView?.title !== title) {
const existingTitle = views.find((f) => f.id !== entityView?.id && f.title.toLowerCase() === title.toLowerCase());
if (existingTitle) {
errors.push(`Existing entity view with title: ${existingTitle.title}`);
}
}
// if (order) {
// if (!entityView || entityView?.order !== order) {
// const existingOrder = await getEntityViewByOrder(entityId, order);
// if (existingOrder) {
// errors.push(`Existing entity view with order '${order}': ${existingOrder.title}`);
// }
// }
// }
return errors;
};
const validateGroupBy = async (entity: EntityWithDetails, layout: string, groupBy: string | undefined, groupByPropertyId: string | undefined) => {
if (layout !== "board") {
return [];
}
const errors: string[] = [];
if (groupBy === "byProperty") {
const property = entity.properties.find((p) => p.id === groupByPropertyId);
if (!property || property.type !== PropertyType.SELECT) {
errors.push(`Cannot save a Board view without a SELECT property`);
}
}
return errors;
};
}
@@ -1,128 +0,0 @@
import { createProperty, updatePropertyAttributes, updatePropertyOptions } from "../../db/entities/properties.db.server";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { Colors } from "~/application/enums/shared/Colors";
import { EntityWithDetails } from "../../db/entities/entities.db.server";
export namespace PropertiesApi {
export async function create({
entityId,
name,
title,
type,
subtype,
order,
isDefault,
isRequired,
isHidden,
isDisplay,
isReadOnly,
canUpdate,
showInCreate,
formulaId,
options,
attributes,
tenantId,
}: {
entityId: string;
name: string;
title: string;
type: PropertyType;
subtype?: string | null;
order?: number;
isDefault?: boolean;
isRequired?: boolean;
isHidden?: boolean;
isDisplay?: boolean;
isReadOnly?: boolean;
canUpdate?: boolean;
showInCreate?: boolean;
formulaId?: string | null;
options?: { order: number; value: string; name?: string | null; color?: Colors }[];
attributes?: { name: string; value: string }[];
tenantId: string | null;
}) {
if (!order) {
order = 0;
}
const property = await createProperty({
entityId,
name,
title,
type,
subtype: subtype ?? null,
order,
isDefault: isDefault ?? false,
isRequired: isRequired ?? false,
isHidden: isHidden ?? false,
isDisplay: isDisplay ?? false,
isReadOnly: isReadOnly ?? false,
canUpdate: canUpdate ?? true,
showInCreate: showInCreate ?? true,
formulaId: formulaId ?? null,
tenantId,
});
if (options !== undefined) {
await updatePropertyOptions(property.id, options);
}
if (attributes !== undefined) {
await updatePropertyAttributes(property.id, attributes);
}
return property;
}
export async function duplicate({ entity, propertyId }: { entity: EntityWithDetails; propertyId: string }) {
const existingProperty = entity.properties.find((p) => p.id === propertyId);
if (!existingProperty) {
throw Error("Property not found");
}
let number = 2;
let name = "";
const findExistingProperty = (name: string) => {
return entity.properties.find((p) => p.name === name);
};
do {
name = `${existingProperty.name}${number}`;
const existingPropertyWithNewName = findExistingProperty(name);
if (!existingPropertyWithNewName) {
break;
}
if (number > 10) {
throw Error("Too many duplicates");
}
number++;
} while (true);
let maxOrder = 0;
if (entity.properties.length > 0) {
maxOrder = Math.max(...entity.properties.map((p) => p.order));
}
return await create({
entityId: entity.id,
name,
title: existingProperty.title + " " + number,
type: existingProperty.type,
subtype: existingProperty.subtype,
order: maxOrder + 1,
isDefault: existingProperty.isDefault,
isRequired: existingProperty.isRequired,
isHidden: existingProperty.isHidden,
isDisplay: existingProperty.isDisplay,
isReadOnly: existingProperty.isReadOnly,
showInCreate: existingProperty.showInCreate,
formulaId: existingProperty.formulaId,
options: existingProperty.options.map((o) => ({
order: o.order,
value: o.value,
name: o.name,
color: o.color,
})),
attributes: existingProperty.attributes.map((a) => ({
name: a.name,
value: a.value,
})),
tenantId: existingProperty.tenantId,
});
}
}
@@ -1,40 +0,0 @@
import { getEntityByIdOrName } from "~/utils/db/entities/entities.db.server";
import { getRowById } from "~/utils/db/entities/rows.db.server";
import { createManualRowLog } from "../../db/logs.db.server";
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
import { createRowComment } from "../../db/entities/rowComments.db.server";
export namespace RowCommentsApi {
export async function create(
id: string,
{
comment,
tenantId,
userId,
}: {
comment: string;
tenantId: string | null;
userId: string;
}
) {
const item = await getRowById(id, { tenantId });
const entity = await getEntityByIdOrName({ tenantId, id: item?.entityId });
if (!item || !entity) {
throw new Error("Row not found");
}
const created = await createRowComment({
createdByUserId: userId,
rowId: id,
value: comment,
});
await createManualRowLog({
tenantId: item.tenantId,
createdByUserId: userId,
action: DefaultLogActions.Commented,
entity,
item,
commentId: created.id,
});
return created;
}
}
@@ -1,74 +0,0 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { RowPermissionsApi } from "./RowPermissionsApi";
import { getGroup } from "~/utils/db/permissions/groups.db.server";
import { getRole } from "~/utils/db/permissions/roles.db.server";
import { getTenant, getTenantUserByIds } from "~/utils/db/tenants.db.server";
vi.mock("~/utils/db/permissions/rowPermissions.db.server", () => ({
createRowPermission: vi.fn(),
deleteRowPermissionByIdForRow: vi.fn(),
getRowPermissions: vi.fn(async () => []),
updateRowPermissionForRow: vi.fn(),
}));
vi.mock("~/utils/db/permissions/groups.db.server", () => ({
getGroup: vi.fn(),
}));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({
getRole: vi.fn(),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
getTenant: vi.fn(),
getTenantUserByIds: vi.fn(),
}));
describe("RowPermissionsApi.validateShareTarget", () => {
beforeEach(() => {
vi.mocked(getGroup).mockReset();
vi.mocked(getRole).mockReset();
vi.mocked(getTenant).mockReset();
vi.mocked(getTenantUserByIds).mockReset();
});
test("rejects tenant share targets outside the current tenant", async () => {
await expect(
RowPermissionsApi.validateShareTarget({ type: "tenant", id: "tenant_b", access: "view" }, { currentTenantId: "tenant_a" })
).rejects.toThrow("Invalid permission target");
});
test("rejects invalid access values", async () => {
await expect(
RowPermissionsApi.validateShareTarget({ type: "public", access: "owner" as never })
).rejects.toThrow("Invalid permission access");
});
test("rejects user share targets that are not members of the current tenant", async () => {
vi.mocked(getTenantUserByIds).mockResolvedValue(null);
await expect(
RowPermissionsApi.validateShareTarget({ type: "user", id: "user_b", access: "view" }, { currentTenantId: "tenant_a" })
).rejects.toThrow("Invalid permission target");
expect(getTenantUserByIds).toHaveBeenCalledWith("tenant_a", "user_b");
});
test("rejects group share targets outside the current tenant", async () => {
vi.mocked(getGroup).mockResolvedValue(null);
await expect(
RowPermissionsApi.validateShareTarget({ type: "group", id: "group_b", access: "view" }, { currentTenantId: "tenant_a" })
).rejects.toThrow("Invalid permission target");
expect(getGroup).toHaveBeenCalledWith("group_b", "tenant_a");
});
test("rejects admin roles as tenant share targets", async () => {
vi.mocked(getRole).mockResolvedValue({ id: "role_admin", type: "admin" } as Awaited<ReturnType<typeof getRole>>);
await expect(
RowPermissionsApi.validateShareTarget({ type: "role", id: "role_admin", access: "view" }, { currentTenantId: "tenant_a" })
).rejects.toThrow("Invalid permission target");
});
});
@@ -1,158 +0,0 @@
import { RowAccess, RowAccessTypes } from "~/application/enums/entities/RowAccess";
import {
createRowPermission,
deleteRowPermissionByIdForRow,
getRowPermissions,
updateRowPermissionForRow,
} from "../../db/permissions/rowPermissions.db.server";
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
import { Row } from "@toolctrl/db/prisma-browser";
import { getGroup } from "~/utils/db/permissions/groups.db.server";
import { getRole } from "~/utils/db/permissions/roles.db.server";
import { getTenant, getTenantUserByIds } from "~/utils/db/tenants.db.server";
export namespace RowPermissionsApi {
type ShareData = { type: "tenant" | "user" | "role" | "group" | "public"; id?: string; access: RowAccess };
type ShareScope = { currentTenantId?: string | null };
export async function shareWithDefault(row: Row, defaultVisibility: DefaultVisibility) {
if (defaultVisibility === "tenant" && row.tenantId) {
await shareWithTenant(row, row.tenantId, "edit");
}
if (defaultVisibility === "public") {
return await shareWithPublic(row, "view");
}
}
export async function share(row: Row, data: ShareData, scope: ShareScope = {}) {
await validateShareTarget(data, scope);
const permission = {
tenantId: data.type === "tenant" ? data.id : null,
roleId: data.type === "role" ? data.id : null,
groupId: data.type === "group" ? data.id : null,
userId: data.type === "user" ? data.id : null,
public: data.type === "public",
access: data.access,
};
if (data.type !== "public" && !permission.tenantId && !permission.roleId && !permission.groupId && !permission.userId) {
throw Error("Invalid permission");
}
const permissions = await getRowPermissions(row.id);
const existing = permissions.find(
(f) =>
f.tenantId === permission.tenantId &&
f.roleId === permission.roleId &&
f.groupId === permission.groupId &&
f.userId === permission.userId &&
f.public === permission.public
);
if (data.type === "user" && data.id === row?.createdByUserId) {
return;
} else if (existing) {
return existing;
}
const create = await createRowPermission({
rowId: row.id,
...permission,
});
return create;
}
export async function validateShareTarget(data: ShareData, scope: ShareScope = {}) {
validateAccess(data.access);
if (data.type !== "tenant" && data.type !== "user" && data.type !== "role" && data.type !== "group" && data.type !== "public") {
throw Error("Invalid permission target");
}
if (data.type !== "public" && data.id === "public") {
throw Error("Invalid permission target");
}
if (data.type === "public" && data.id) {
throw Error("Invalid permission target");
}
if (data.type === "public") {
return;
}
if (!data.id) {
throw Error("Invalid permission target");
}
const { currentTenantId } = scope;
if (data.type === "tenant") {
if (currentTenantId && data.id !== currentTenantId) {
throw Error("Invalid permission target");
}
if (currentTenantId === null && !(await getTenant(data.id))) {
throw Error("Invalid permission target");
}
return;
}
if (data.type === "user") {
if (currentTenantId && !(await getTenantUserByIds(currentTenantId, data.id))) {
throw Error("Invalid permission target");
}
return;
}
if (data.type === "group") {
if (!(await getGroup(data.id, currentTenantId))) {
throw Error("Invalid permission target");
}
return;
}
const role = await getRole(data.id);
if (!role || (currentTenantId && role.type !== "app")) {
throw Error("Invalid permission target");
}
}
export function validateAccess(access: RowAccess) {
if (!RowAccessTypes.includes(access)) {
throw Error("Invalid permission access");
}
}
export async function shareWithTenant(row: Row, tenantId: string, access: RowAccess) {
return await share(row, {
type: "tenant",
id: tenantId,
access,
}, { currentTenantId: tenantId });
}
export async function shareWithUser(row: Row, userId: string, access: RowAccess) {
return await share(row, {
type: "user",
id: userId,
access,
});
}
export async function shareWithRole(row: Row, roleId: string, access: RowAccess) {
return await share(row, {
type: "role",
id: roleId,
access,
});
}
export async function shareWithGroup(row: Row, groupId: string, access: RowAccess) {
return await share(row, {
type: "group",
id: groupId,
access,
});
}
export async function shareWithPublic(row: Row, access: RowAccess) {
return await share(row, {
type: "public",
access,
});
}
export async function setAccessForRow(rowId: string, id: string, access: RowAccess) {
validateAccess(access);
const updated = await updateRowPermissionForRow(rowId, id, { access });
if (updated.count !== 1) {
throw Error("Permission not found");
}
return updated;
}
export async function delForRow(rowId: string, id: string) {
const deleted = await deleteRowPermissionByIdForRow(rowId, id);
if (deleted.count !== 1) {
throw Error("Permission not found");
}
return deleted;
}
}
@@ -1,231 +0,0 @@
import {
createLegacyRowRelationship,
deleteLegacyRowRelationship,
deleteLegacyRowRelationshipById,
findLegacyEntityRelationship,
findLegacyRowRelationshipById,
} from "@toolctrl/db/relationships.server";
import { TimeFunction, timeFake } from "~/modules/metrics/services/.server/MetricTracker";
import { RowsApi } from "./RowsApi";
import { EntityWithDetails, EntityWithDetailsAndRelationships, getEntityById, getEntityByName } from "../../db/entities/entities.db.server";
export namespace RowRelationshipsApi {
export async function getRelationship(
id: string,
{
tenantId,
userId,
time,
}: {
userId: string | undefined;
tenantId: string | null;
time?: TimeFunction;
}
) {
if (!time) {
time = timeFake;
}
const relationship = await time(findLegacyRowRelationshipById(id, tenantId), "RowRelationshipsApi.getRelationship");
if (!relationship) {
return null;
}
const parent = await RowsApi.get(relationship.parentId, {
entity: {
id: relationship.relationship.parentId,
},
tenantId,
userId,
});
const child = await RowsApi.get(relationship.childId, {
entity: {
id: relationship.relationship.childId,
},
tenantId,
userId,
});
return {
...relationship,
parent,
child,
};
}
export async function createRelationship({
parent,
child,
time,
allEntities,
metadata,
tenantId,
}: {
parent: { id: string; entityId: string } | { id: string; entityName: string };
child: { id: string; entityId: string } | { id: string; entityName: string };
tenantId?: string | null;
metadata?: string | null;
time?: TimeFunction;
allEntities?: EntityWithDetails[];
}) {
if (!time) {
time = timeFake;
}
const { relationship } = await getParentChildEntities({ parent, child, allEntities });
return await time(
createLegacyRowRelationship({
relationshipId: relationship.id,
parentId: parent.id,
childId: child.id,
tenantId,
metadata: metadata || null,
}),
"RowRelationshipsApi.createRelationship.createRowRelationship"
);
}
export async function createRelationshipWithIds({
parentEntityId,
childEntityId,
parentId,
childId,
metadata,
tenantId,
time,
allEntities,
}: {
parentEntityId: string;
childEntityId: string;
parentId: string;
childId: string;
tenantId?: string | null;
metadata: string | null;
time?: TimeFunction;
allEntities?: EntityWithDetails[];
}) {
if (!time) {
time = timeFake;
}
const { relationship } = await getParentChildEntities({
parent: { id: parentId, entityId: parentEntityId },
child: { id: childId, entityId: childEntityId },
allEntities,
});
return await time(
createLegacyRowRelationship({
relationshipId: relationship.id,
parentId,
childId,
tenantId,
metadata,
}),
"RowRelationshipsApi.createRelationship.createRowRelationship"
);
}
export async function deleteRelationship({
parent,
child,
time,
allEntities,
tenantId,
}: {
parent: { id: string; entityId: string } | { id: string; entityName: string };
child: { id: string; entityId: string } | { id: string; entityName: string };
tenantId?: string | null;
time?: TimeFunction;
allEntities?: EntityWithDetails[];
}) {
if (!time) {
time = timeFake;
}
const { parentEntity, childEntity } = await getParentChildEntities({ parent, child, allEntities });
const relationship = await time(
findLegacyEntityRelationship({
parentId: parentEntity.id,
childId: childEntity.id,
}),
"RowRelationshipsApi.deleteRelationship.getEntitiesRelationship"
);
if (!relationship) {
throw Error(`No relationship found between ${parentEntity.name} and ${childEntity.name}`);
}
return await time(
deleteLegacyRowRelationship({
relationshipId: relationship.id,
parentId: parent.id,
childId: child.id,
tenantId,
}),
"RowRelationshipsApi.deleteRelationship.deleteRowRelationship"
);
}
async function getParentChildEntities({
parent,
child,
allEntities,
}: {
parent: { id: string; entityId: string } | { id: string; entityName: string };
child: { id: string; entityId: string } | { id: string; entityName: string };
allEntities?: EntityWithDetails[];
}) {
let parentEntity: EntityWithDetailsAndRelationships | null = null;
let childEntity: EntityWithDetailsAndRelationships | null = null;
if ("entityName" in parent) {
parentEntity = allEntities
? allEntities.find((e) => e.name === parent.entityName) || null
: await getEntityByName({ tenantId: undefined, name: parent.entityName });
} else {
parentEntity = allEntities
? allEntities.find((e) => e.id === parent.entityId) || null
: await getEntityById({ tenantId: undefined, id: parent.entityId });
}
if ("entityName" in child) {
childEntity = allEntities
? allEntities.find((e) => e.name === child.entityName) || null
: await getEntityByName({ tenantId: undefined, name: child.entityName });
} else {
childEntity = allEntities ? allEntities.find((e) => e.id === child.entityId) || null : await getEntityById({ tenantId: undefined, id: child.entityId });
}
if (!parentEntity) {
throw Error(`Invalid parent entity ${JSON.stringify(parent)}`);
}
if (!childEntity) {
throw Error(`Invalid child entity ${JSON.stringify(child)}`);
}
const relationship = parentEntity.childEntities.find((e) => e.childId === childEntity!.id);
if (!relationship) {
throw Error(`No relationship found between ${parentEntity?.name} and ${childEntity?.name}`);
}
return {
parentEntity,
childEntity,
relationship,
};
}
export async function deleteRelationshipById(
id: string,
{
tenantId,
userId,
time,
}: {
tenantId: string | null;
userId: string | undefined;
time?: TimeFunction;
}
) {
if (!time) {
time = timeFake;
}
const relationship = await getRelationship(id, { tenantId, userId, time });
if (!relationship) {
throw Error(`No relationship found with id ${id}`);
}
return await time(
deleteLegacyRowRelationshipById({
id: relationship.id,
relationshipId: relationship.relationshipId,
parentId: relationship.parentId,
childId: relationship.childId,
tenantId,
}),
"RowRelationshipsApi.deleteRelationship.deleteRowRelationship",
);
}
}
File diff suppressed because it is too large. Load diff
@@ -1,380 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => {
const tx = {
event: {
create: vi.fn(),
},
};
return {
tx,
db: {
$transaction: vi.fn(async (runner: (tx: unknown) => Promise<unknown>) => runner(tx)),
},
rows: {
buildLegacyRowPropertyFiltersWhere: vi.fn(() => ({})),
buildLegacyRowQueryWhere: vi.fn(() => ({})),
changeLegacyRowOrder: vi.fn(),
countLegacyRows: vi.fn(),
createRowWithValues: vi.fn(),
hardDeleteRowById: vi.fn(),
getLegacyRow: vi.fn(),
getLegacyRowById: vi.fn(),
listLegacyRows: vi.fn(),
updateRowWithValuesInTransaction: vi.fn(),
},
entities: {
getEntityByIdOrName: vi.fn(),
},
entityViews: {
getEntityViews: vi.fn(),
},
entityTags: {
createEntityTag: vi.fn(),
getEntityTag: vi.fn(),
getEntityTags: vi.fn(),
},
permissions: {
getEntityPermission: vi.fn((entity: { name: string }, name: string) => `${entity.name}.${name}`),
getRowPermissionsCondition: vi.fn(() => ({})),
getUserPermission: vi.fn(async () => ({ permission: { id: "permission_1" }, userPermission: { id: "user_permission_1" } })),
getUserRowPermission: vi.fn(async () => ({ canRead: true, canUpdate: true, canDelete: true })),
getRowPermissions: vi.fn(),
getUserRoleInTenant: vi.fn(),
},
pagination: {
getPaginationFromCurrentUrl: vi.fn(() => ({ page: 1, pageSize: 25, sortedBy: [] })),
getEntityFiltersFromCurrentUrl: vi.fn(() => ({ query: "" })),
},
rowFiltersHelper: {
getRowFiltersCondition: vi.fn(() => ({})),
},
logs: {
createManualRowLog: vi.fn(),
getRowLogs: vi.fn(),
},
rowComments: {
getRowComments: vi.fn(),
},
rowTasks: {
getAllRowTasks: vi.fn(),
getRowTasks: vi.fn(),
},
rowTags: {
createRowTag: vi.fn(),
deleteRowTags: vi.fn(),
getRowTagByIds: vi.fn(),
getRowTags: vi.fn(),
},
subscription: {
getPlanFeatureUsage: vi.fn(),
reportUsage: vi.fn(),
},
rowHelper: {
getTextDescription: vi.fn(() => "Contact row"),
getDiff: vi.fn(() => ({ firstName: { before: "Ada", after: "Grace" } })),
},
relationshipHelper: {
getInputType: vi.fn(),
},
media: {
storeRowMediaInStorageProvider: vi.fn(),
},
rowPermissionsApi: {
shareWithDefault: vi.fn(),
},
rowEventsHelper: {
getRowUserOrApiKey: vi.fn(async () => ({ user: null, apiKey: null })),
},
events: {
getDescription: vi.fn((event: string) => `${event} description`),
publishOutboxEvent: vi.fn(),
},
apiHelper: {
getApiFormat: vi.fn((entity: { name: string }, row: { id: string }) => ({ id: row.id, entity: entity.name })),
},
entityViewsApi: {
getCurrentEntityView: vi.fn(),
},
entitiesApi: {
fillSystemProperties: vi.fn(),
},
pluginHooks: {
emitPluginHookFireAndForget: vi.fn(),
},
rowSearchOutbox: {
emitRowSearchDelete: vi.fn(),
emitRowSearchUpsert: vi.fn(),
},
rowSearch: {
searchRows: vi.fn(),
},
crmContactSearch: {
searchCrmContacts: vi.fn(),
},
notifications: {
sendToRoles: vi.fn(),
},
eventWebhookAttempts: {
createEventWebhookAttempt: vi.fn(),
updateEventWebhookAttempt: vi.fn(),
},
logger: {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
},
};
});
vi.mock("@toolctrl/db/client.server", () => ({
getDbClient: () => mocks.db,
}));
vi.mock("~/utils/db.server", () => ({
db: mocks.db,
}));
vi.mock("@toolctrl/db/rows.server", () => mocks.rows);
vi.mock("~/utils/db/entities/entities.db.server", () => mocks.entities);
vi.mock("~/utils/db/entities/entityViews.db.server", () => mocks.entityViews);
vi.mock("../../db/entities/entityTags.db.server", () => mocks.entityTags);
vi.mock("../../helpers/PermissionsHelper", () => mocks.permissions);
vi.mock("../../helpers/.server/PermissionsService", () => mocks.permissions);
vi.mock("../../helpers/RowPaginationHelper", () => mocks.pagination);
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: mocks.rowFiltersHelper }));
vi.mock("~/application/Constants", () => ({ default: { DEFAULT_PAGE_SIZE: 25 } }));
vi.mock("../../db/logs.db.server", () => mocks.logs);
vi.mock("../../db/entities/rowComments.db.server", () => mocks.rowComments);
vi.mock("../../db/entities/rowTasks.db.server", () => mocks.rowTasks);
vi.mock("../../db/entities/rowTags.db.server", () => mocks.rowTags);
vi.mock("../../db/permissions/rowPermissions.db.server", () => mocks.permissions);
vi.mock("../../services/.server/subscriptionService", () => mocks.subscription);
vi.mock("i18next", () => ({ t: (key: string) => key }));
vi.mock("../../helpers/RowHelper", () => ({ default: mocks.rowHelper }));
vi.mock("../../helpers/RelationshipHelper", () => ({ default: mocks.relationshipHelper }));
vi.mock("~/utils/helpers/.server/MediaService", () => mocks.media);
vi.mock("./RowPermissionsApi", () => ({ RowPermissionsApi: mocks.rowPermissionsApi }));
vi.mock("../../helpers/RowEventsHelper", () => mocks.rowEventsHelper);
vi.mock("@toolctrl/db/outbox", () => ({ publishOutboxEvent: mocks.events.publishOutboxEvent }));
vi.mock("../../utils/EventUtils", () => ({ default: mocks.events }));
vi.mock("../../db/eventWebhookAttempts.db.server", () => mocks.eventWebhookAttempts);
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({ default: mocks.notifications }));
vi.mock("~/utils/url.server", () => ({
getAbsoluteApiUrl: vi.fn(() => "https://api.example.test/v1/events/webhooks/attempts/attempt_1"),
getBaseURL: vi.fn(() => "https://app.example.test"),
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
adminPath: vi.fn((path: string) => `/admin/${path}`),
appPath: vi.fn(({ path }: { path: string }) => `/app/${path}`),
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: vi.fn(() => mocks.logger),
}));
vi.mock("../../helpers/ApiHelper", () => ({ default: mocks.apiHelper }));
vi.mock("./EntityViewsApi", () => ({ EntityViewsApi: mocks.entityViewsApi }));
vi.mock("./EntitiesApi", () => ({ EntitiesApi: mocks.entitiesApi }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => mocks.permissions);
vi.mock("~/modules/plugins/services/.server/pluginHookPublisher", () => mocks.pluginHooks);
vi.mock("@toolctrl/plugin-runtime", () => ({
PLUGIN_HOOK_ENTITY_CREATED: "entity.created",
PLUGIN_HOOK_ENTITY_DELETED: "entity.deleted",
PLUGIN_HOOK_ENTITY_UPDATED: "entity.updated",
}));
vi.mock("~/modules/rows/services/rowSearchOutbox.server", () => mocks.rowSearchOutbox);
vi.mock("~/modules/rows/services/rowSearch.server", () => mocks.rowSearch);
vi.mock("~/modules/crm/services/crmContactSearch.server", () => mocks.crmContactSearch);
import { RowApiError, RowsApi } from "./RowsApi";
const entity = {
id: "entity_contact",
name: "contact",
slug: "contacts",
title: "Contact",
defaultVisibility: "private",
properties: [],
parentEntities: [],
childEntities: [],
};
function row(id: string, patch: Record<string, unknown> = {}) {
return {
id,
entityId: entity.id,
tenantId: "tenant_1",
createdByUserId: "user_1",
createdByApiKeyId: null,
values: [],
parentRows: [],
childRows: [],
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
...patch,
};
}
describe("RowsApi workflow row events", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.db.$transaction.mockImplementation(async (runner: (tx: unknown) => Promise<unknown>) => runner(mocks.tx));
mocks.tx.event.create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({
id: `event_${mocks.tx.event.create.mock.calls.length}`,
...data,
}));
mocks.entities.getEntityByIdOrName.mockResolvedValue(entity);
mocks.subscription.getPlanFeatureUsage.mockResolvedValue(null);
mocks.permissions.getUserPermission.mockResolvedValue({ permission: { id: "permission_1" }, userPermission: { id: "user_permission_1" } });
mocks.permissions.getUserRowPermission.mockResolvedValue({ canRead: true, canUpdate: true, canDelete: true });
mocks.entityViews.getEntityViews.mockResolvedValue([]);
mocks.entityViewsApi.getCurrentEntityView.mockResolvedValue(null);
mocks.entityTags.getEntityTags.mockResolvedValue([]);
mocks.rows.listLegacyRows.mockResolvedValue([]);
mocks.rows.countLegacyRows.mockResolvedValue(0);
});
it("publishes tenant-scoped workflow outbox events for row create, update, and delete", async () => {
const created = row("row_created");
const beforeUpdate = row("row_updated", { values: [{ id: "value_before" }] });
const afterUpdate = row("row_updated", { values: [{ id: "value_after" }] });
const deleted = row("row_deleted");
const rowsById = new Map([
[created.id, created],
[beforeUpdate.id, beforeUpdate],
[deleted.id, deleted],
]);
const request = new Request("https://app.example.test/app/acme/contacts");
mocks.rows.createRowWithValues.mockResolvedValue({ id: created.id });
mocks.rows.getLegacyRowById.mockImplementation(async (id: string) => rowsById.get(id) ?? null);
mocks.rows.updateRowWithValuesInTransaction.mockResolvedValue(afterUpdate);
mocks.rows.hardDeleteRowById.mockResolvedValue(deleted);
await RowsApi.create({ entity, tenantId: "tenant_1", userId: "user_1", request, rowValues: { dynamicProperties: [] } });
await RowsApi.update(beforeUpdate.id, { entity, tenantId: "tenant_1", userId: "user_1", request, rowValues: { dynamicProperties: [] } });
await RowsApi.del(deleted.id, { entity, tenantId: "tenant_1", userId: "user_1", request });
expect(mocks.events.publishOutboxEvent).toHaveBeenCalledTimes(3);
expect(mocks.events.publishOutboxEvent).toHaveBeenNthCalledWith(1, mocks.tx, {
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: expect.objectContaining({ event: "row.created", userId: "user_1" }),
dispatchKey: "workflow-trigger:event_1",
});
expect(mocks.events.publishOutboxEvent).toHaveBeenNthCalledWith(2, mocks.tx, {
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: expect.objectContaining({ event: "row.updated", userId: "user_1" }),
dispatchKey: "workflow-trigger:event_2",
});
expect(mocks.events.publishOutboxEvent).toHaveBeenNthCalledWith(3, mocks.tx, {
tenantId: "tenant_1",
type: "workflow.trigger.event",
payload: expect.objectContaining({ event: "row.deleted", userId: "user_1" }),
dispatchKey: "workflow-trigger:event_3",
});
expect(mocks.tx.event.create).toHaveBeenCalledTimes(3);
expect(mocks.tx.event.create).toHaveBeenNthCalledWith(1, expect.objectContaining({ data: expect.objectContaining({ name: "row.created", tenantId: "tenant_1", userId: "user_1" }) }));
expect(mocks.tx.event.create).toHaveBeenNthCalledWith(2, expect.objectContaining({ data: expect.objectContaining({ name: "row.updated", tenantId: "tenant_1", userId: "user_1" }) }));
expect(mocks.tx.event.create).toHaveBeenNthCalledWith(3, expect.objectContaining({ data: expect.objectContaining({ name: "row.deleted", tenantId: "tenant_1", userId: "user_1" }) }));
expect(mocks.notifications.sendToRoles).toHaveBeenCalledTimes(3);
});
it("does not publish duplicate workflow outbox events when row event creation is disabled", async () => {
const deleted = row("row_parent");
mocks.rows.getLegacyRowById.mockResolvedValue(deleted);
mocks.rows.hardDeleteRowById.mockResolvedValue(deleted);
await RowsApi.del(deleted.id, {
entity,
tenantId: "tenant_1",
userId: "user_1",
request: new Request("https://app.example.test/app/acme/contacts"),
options: { createEvent: false },
});
expect(mocks.tx.event.create).not.toHaveBeenCalled();
expect(mocks.events.publishOutboxEvent).not.toHaveBeenCalled();
expect(mocks.notifications.sendToRoles).not.toHaveBeenCalled();
expect(mocks.rowSearchOutbox.emitRowSearchDelete).toHaveBeenCalledWith({ tenantId: "tenant_1", entity: { name: "contact" }, rowId: deleted.id });
});
});
describe("RowsApi row error codes", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.entities.getEntityByIdOrName.mockResolvedValue(entity);
});
it("throws a stable code for denied row reads", async () => {
mocks.rows.getLegacyRow.mockResolvedValue(row("row_private"));
mocks.permissions.getUserRowPermission.mockResolvedValue({ canRead: false, canUpdate: false, canDelete: false });
try {
await RowsApi.get("row_private", { entity, tenantId: "tenant_1", userId: "user_2" });
throw new Error("Expected RowsApi.get to reject");
} catch (error) {
expect(error).toBeInstanceOf(RowApiError);
expect(error).toMatchObject({ code: "row-access-denied", status: 403 });
}
});
});
describe("RowsApi CRM contact list search", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.entities.getEntityByIdOrName.mockResolvedValue(entity);
mocks.permissions.getUserPermission.mockResolvedValue({ permission: { id: "permission_1" }, userPermission: { id: "user_permission_1" } });
mocks.entityViews.getEntityViews.mockResolvedValue([]);
mocks.entityViewsApi.getCurrentEntityView.mockResolvedValue(null);
mocks.pagination.getPaginationFromCurrentUrl.mockReturnValue({ page: 1, pageSize: 25, sortedBy: [] });
mocks.pagination.getEntityFiltersFromCurrentUrl.mockReturnValue({ query: "ada" });
mocks.permissions.getRowPermissionsCondition.mockResolvedValue({});
mocks.rowFiltersHelper.getRowFiltersCondition.mockReturnValue({});
mocks.rows.buildLegacyRowQueryWhere.mockReturnValue({ id: { in: ["contact_row_1"] } });
mocks.rows.listLegacyRows.mockResolvedValue([]);
mocks.rows.countLegacyRows.mockResolvedValue(0);
mocks.entityTags.getEntityTags.mockResolvedValue([]);
mocks.crmContactSearch.searchCrmContacts.mockResolvedValue({
hits: [{ id: "contact_row_1", firstName: "Ada", lastName: "Lovelace", email: "ada@example.test", company: "", jobTitle: "" }],
total: 1,
fellBack: false,
});
mocks.rowSearch.searchRows.mockResolvedValue({ hits: [{ id: "row_1", folio: 1, entityName: "company" }], total: 1, fellBack: false });
});
it("routes contact-list freetext through searchCrmContacts and keeps the legacy SQL hydration path", async () => {
await RowsApi.getAll({
entity,
tenantId: "tenant_1",
userId: "user_1",
urlSearchParams: new URLSearchParams("q=ada"),
});
expect(mocks.crmContactSearch.searchCrmContacts).toHaveBeenCalledWith({ tenantId: "tenant_1", query: "ada", limit: 1000 });
expect(mocks.rowSearch.searchRows).not.toHaveBeenCalled();
expect(mocks.rows.buildLegacyRowQueryWhere).toHaveBeenCalledWith(
expect.objectContaining({
rowWhere: { id: { in: ["contact_row_1"] } },
})
);
expect(mocks.rows.listLegacyRows).toHaveBeenCalled();
expect(mocks.rows.countLegacyRows).toHaveBeenCalled();
});
it("keeps non-contact freetext on the generic rows search helper", async () => {
const companyEntity = { ...entity, id: "entity_company", name: "company", slug: "companies", title: "Company" };
mocks.entities.getEntityByIdOrName.mockResolvedValue(companyEntity);
await RowsApi.getAll({
entity: companyEntity,
tenantId: "tenant_1",
userId: "user_1",
urlSearchParams: new URLSearchParams("q=ada"),
});
expect(mocks.rowSearch.searchRows).toHaveBeenCalledWith({ tenantId: "tenant_1", entityId: "entity_company", query: "ada", limit: 1000 });
expect(mocks.crmContactSearch.searchCrmContacts).not.toHaveBeenCalled();
});
});
@@ -1,46 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const rowsApiPath = path.resolve(process.cwd(), "apps/web/app/utils/api/.server/RowsApi.ts");
describe("RowsApi workflow outbox transaction boundary", () => {
it("creates rows, reloads rows, and records row.created workflow events inside the same transaction", () => {
const source = fs.readFileSync(rowsApiPath, "utf8");
const createSection = source.slice(source.indexOf("export async function create({"), source.indexOf("export async function createSimple({"));
expect(createSection).toContain("db.$transaction(async (tx) =>");
expect(createSection).toContain("const rowClient = tx as unknown as RowCreateClient");
expect(createSection).toContain("rowClient\n );");
expect(createSection).toContain("getLegacyRowById(item.id, rowClient, tenantId)");
expect(createSection).toContain("EventsService.createInTransaction(tx as Parameters<typeof EventsService.createInTransaction>[0]");
expect(createSection).toContain("EventsService.dispatchPostCommitSideEffects(rowCreatedEvent)");
expect(createSection).not.toContain('EventsService.create({\n request,\n event: "row.created"');
});
it("updates rows and records row.updated workflow events inside the same transaction", () => {
const source = fs.readFileSync(rowsApiPath, "utf8");
const updateSection = source.slice(source.indexOf("export async function update("), source.indexOf("export async function del("));
expect(updateSection).toContain("db.$transaction(async (tx) =>");
expect(updateSection).toContain("updateRowWithValuesInTransaction(");
expect(updateSection).toContain('event: "row.updated"');
expect(updateSection).toContain("EventsService.createInTransaction(tx as Parameters<typeof EventsService.createInTransaction>[0]");
expect(updateSection.indexOf("updateRowWithValuesInTransaction(")).toBeLessThan(updateSection.indexOf("EventsService.createInTransaction"));
expect(updateSection).toContain("EventsService.dispatchPostCommitSideEffects(rowUpdatedEvent)");
expect(updateSection).not.toContain('EventsService.create({\n request,\n event: "row.updated"');
});
it("deletes rows and records row.deleted workflow events inside the same transaction", () => {
const source = fs.readFileSync(rowsApiPath, "utf8");
const deleteSection = source.slice(source.indexOf("export async function del("), source.indexOf("export async function count({"));
expect(deleteSection).toContain("db.$transaction(async (tx) =>");
expect(deleteSection).toContain("hardDeleteRowById({ id, entityId: rowEntity.id, tenantId: row.tenantId ?? null }, tx as unknown as RowDeleteClient)");
expect(deleteSection).toContain('event: "row.deleted"');
expect(deleteSection).toContain("EventsService.createInTransaction(tx as Parameters<typeof EventsService.createInTransaction>[0]");
expect(deleteSection.indexOf("hardDeleteRowById(")).toBeLessThan(deleteSection.indexOf("EventsService.createInTransaction"));
expect(deleteSection).toContain("EventsService.dispatchPostCommitSideEffects(rowDeletedEvent)");
expect(deleteSection).not.toContain('EventsService.create({\n request,\n event: "row.deleted"');
});
});
@@ -1,10 +1,7 @@
import { getTranslations } from "~/locale/i18next.server";
import { findEntityByName } from "../../db/entities/entities.db.server";
import { createTenant } from "../../db/tenants.db.server";
import { getUser, updateUserDefaultTenantId } from "../../db/users.db.server";
import { getUserInfo } from "../../session.server";
import { createStripeCustomer } from "../../stripe.server";
import { RowsApi } from "./RowsApi";
import { TenantTypesApi } from "./TenantTypesApi";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { AccountCreatedDto } from "~/modules/events/dtos/AccountCreatedDto";
@@ -12,7 +9,7 @@ import { autosubscribeToTrialOrFreePlan } from "../../services/.server/pricingSe
import { appPath } from "../../app/CanonicalUrlUtils";
export namespace TenantsApi {
export async function create({ request, form, name, slug }: { request: Request; form: FormData; name: string; slug?: string }) {
export async function create({ request, name, slug }: { request: Request; name: string; slug?: string }) {
const { t } = await getTranslations(request);
let userInfo = await getUserInfo(request);
const user = await getUser(userInfo.userId);
@@ -23,15 +20,7 @@ export namespace TenantsApi {
throw new Error("Name is required");
}
let stripeCustomerId: string | undefined;
if (process.env.STRIPE_SK) {
const stripeCustomer = await createStripeCustomer(user?.email, name);
if (!stripeCustomer) {
throw new Error("Could not create Stripe customer");
}
stripeCustomerId = stripeCustomer.id;
}
const tenant = await createTenant({ name, subscriptionCustomerId: stripeCustomerId, slug });
const tenant = await createTenant({ name, slug });
await updateUserDefaultTenantId({ defaultTenantId: tenant.id }, user.id);
@@ -48,22 +37,6 @@ export namespace TenantsApi {
} satisfies AccountCreatedDto,
});
const tenantSettingsEntity = await findEntityByName({ tenantId: null, name: "tenantSettings" });
if (tenantSettingsEntity) {
try {
await RowsApi.createCustom({
request,
entity: tenantSettingsEntity,
tenantId: tenant.id,
t,
form,
row: undefined,
});
} catch (e: any) {
throw e;
}
}
await TenantTypesApi.setTenantTypes({ tenantId: tenant.id });
return {
@@ -1,68 +0,0 @@
import { describe, expect, it } from "vitest";
import { readRepoFile } from "~/utils/testing/repoPaths";
type BoundarySurface = {
path: string;
packageImports: string[];
forbiddenImports: string[];
};
const rowApiBoundarySurfaces: BoundarySurface[] = [
{
path: "apps/web/app/utils/api/.server/RowsApi.ts",
packageImports: [
"@toolctrl/db/rows.server",
"buildLegacyRowPropertyFiltersWhere",
"buildLegacyRowQueryWhere",
"changeLegacyRowOrder",
"countLegacyRows",
"createRowWithValues",
"hardDeleteRowById",
"getLegacyRow",
"getLegacyRowById",
"listLegacyRows",
"updateRowWithValues",
],
forbiddenImports: ["~/utils/db.server", "~/utils/db/entities/rows.db.server", "../../db/entities/rows.db.server"],
},
{
path: "apps/web/app/utils/api/.server/RowRelationshipsApi.ts",
packageImports: [
"@toolctrl/db/relationships.server",
"createLegacyRowRelationship",
"deleteLegacyRowRelationship",
"deleteLegacyRowRelationshipById",
"findLegacyEntityRelationship",
"findLegacyRowRelationshipById",
],
forbiddenImports: ["~/utils/db.server", "~/utils/db/entities/rowRelationships.db.server", "../../db/entities/rowRelationships.db.server"],
},
];
function readSource(relativePath: string) {
return readRepoFile(relativePath);
}
function importFrom(importPath: string) {
return [`from \"${importPath}\"`, `from '${importPath}'`];
}
describe("row API package boundary imports", () => {
it.each(rowApiBoundarySurfaces)("imports migrated row persistence helpers from package boundaries in $path", ({ path: relativePath, packageImports }) => {
const source = readSource(relativePath);
for (const packageImport of packageImports) {
expect(source, `${relativePath} should import ${packageImport}`).toContain(packageImport);
}
});
it.each(rowApiBoundarySurfaces)("does not reintroduce app-local row persistence imports in $path", ({ path: relativePath, forbiddenImports }) => {
const source = readSource(relativePath);
for (const forbiddenImport of forbiddenImports) {
for (const importStatement of importFrom(forbiddenImport)) {
expect(source, `${relativePath} should not import ${forbiddenImport}`).not.toContain(importStatement);
}
}
});
});
@@ -1,9 +1,9 @@
import { createHmac, timingSafeEqual } from "node:crypto";
import { loadWebConfig } from "@toolctrl/config";
import { loadWebConfig } from "@hivegrid/config";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export const internalWebApiProxyHeader = "x-toolctrl-internal-web-api-proxy";
export const internalWebApiProxySignatureHeader = "x-toolctrl-internal-web-api-proxy-signature";
export const internalWebApiProxyHeader = "x-hivegrid-internal-web-api-proxy";
export const internalWebApiProxySignatureHeader = "x-hivegrid-internal-web-api-proxy-signature";
export function requireInternalWebApiProxyRequest(request: Request) {
if (request.headers.get(internalWebApiProxyHeader) !== "1" || !isValidInternalWebApiProxySignature(request)) {
@@ -1,9 +1,9 @@
import { describe, expect, test } from "vitest";
import packageCanonicalUrlUtils, { adminPath as packageAdminPath, appPath as packageAppPath } from "@toolctrl/url";
import packageCanonicalUrlUtils, { adminPath as packageAdminPath, appPath as packageAppPath } from "@hivegrid/url";
import CanonicalUrlUtils, { adminPath, apiPath, appPath, appUrl, type AppPathOptions } from "./CanonicalUrlUtils";
describe("CanonicalUrlUtils compatibility shim", () => {
test("re-exports named helpers from @toolctrl/url", () => {
test("re-exports named helpers from @hivegrid/url", () => {
const appOptions: AppPathOptions = { tenantSlug: "acme/team", path: "/settings?tab=billing#plan", mode: "host-aware" };
expect(appPath(appOptions)).toBe(packageAppPath(appOptions));
@@ -6,7 +6,7 @@ export {
appPath,
appUrl,
default,
} from "@toolctrl/url";
} from "@hivegrid/url";
export type {
AbsoluteUrlOptions,
@@ -20,4 +20,4 @@ export type {
CanonicalPathOptions,
CanonicalUrlMode,
PathInput,
} from "@toolctrl/url";
} from "@hivegrid/url";
@@ -1,4 +1,4 @@
import type { DomainRoutingConfig } from "@toolctrl/config";
import type { DomainRoutingConfig } from "@hivegrid/config";
import { adminPath, appPath, type PathInput } from "./CanonicalUrlUtils";
export type PublicDomainRoutingConfig = Pick<DomainRoutingConfig, "protocol" | "webAppHost" | "adminAppHost" | "apiHost" | "appBaseDomain">;
@@ -6,7 +6,7 @@ import {
getHostRoutingContext,
getHostRoutingContextFromRequest,
} from "./HostRouting.server";
import type { DomainRoutingConfig } from "@toolctrl/config";
import type { DomainRoutingConfig } from "@hivegrid/config";
const config: DomainRoutingConfig = {
appBaseDomain: "localhost:3000",
@@ -1,4 +1,4 @@
import { getDomainRoutingConfig, hostMatches, normalizeHost, type DomainRoutingConfig, type DomainRoutingEnv } from "@toolctrl/config";
import { getDomainRoutingConfig, hostMatches, normalizeHost, type DomainRoutingConfig, type DomainRoutingEnv } from "@hivegrid/config";
import { adminPath, apiPath, appPath } from "./CanonicalUrlUtils";
import {
canonicalAdminRouteSlugs,
@@ -15,6 +15,7 @@ describe("public route segments", () => {
"/healthz",
"/readyz",
"/mfa-challenge",
"/signup",
"/unauthorized/foo",
"/401",
"/403",
@@ -52,7 +53,7 @@ describe("public route segments", () => {
});
test("exports reserved slugs for route collision checks", () => {
expect(reservedTenantRouteSlugs).toEqual(expect.arrayContaining(["accounts", "analytics", "api", "crm", "docs", "help", "healthcheck", "healthz", "readyz", "swagger", "mcp", "mfa-challenge"]));
expect(reservedTenantRouteSlugs).toEqual(expect.arrayContaining(["accounts", "analytics", "api", "crm", "docs", "help", "healthcheck", "healthz", "readyz", "swagger", "mcp", "mfa-challenge", "signup"]));
expect(reservedTenantChildRouteSlugs).toEqual(expect.arrayContaining(["settings", "crm", "email-marketing", "workflow-engine", "g", "chat", "internal", "widgets"]));
});
});
@@ -27,6 +27,7 @@ export const publicWebRoutePrefixes = [
"/register",
"/reset",
"/select-tenant",
"/signup",
"/sitemap.xml",
"/subscribe/",
"/terms-and-conditions",
@@ -41,6 +42,7 @@ export const canonicalAdminRouteSlugs = [
"accounts",
"analytics",
"api",
"audit",
"audit-trails",
"dashboard",
"email-sequences",
@@ -53,11 +55,10 @@ export const canonicalAdminRouteSlugs = [
"marketing-leads",
"metrics",
"mfa-challenge",
"navigation",
"notifications",
"onboarding",
"settings",
"setup",
"select-tenant",
] as const;
export const disabledPluginRouteSlugs = [
@@ -6,11 +6,12 @@ describe("subscription URL helpers", () => {
it("builds canonical public checkout routes", () => {
expect(subscriptionCheckoutPath("acme")).toBe("/subscribe/acme");
expect(subscriptionCheckoutPath("acme", "{CHECKOUT_SESSION_ID}/success")).toBe("/subscribe/acme/{CHECKOUT_SESSION_ID}/success");
expect(subscriptionRequiredCheckoutPath("acme")).toBe("/subscribe/acme?error=subscription_required");
expect(subscriptionRequiredCheckoutPath("acme")).toBe("/acme/settings/subscription?subscription_required=1");
});
it("encodes tenant slugs as one route segment", () => {
expect(subscriptionCheckoutPath(" Acme Team/West ")).toBe("/subscribe/Acme%20Team%2FWest");
expect(() => subscriptionCheckoutPath(" ")).toThrow("tenantSlug is required");
expect(() => subscriptionRequiredCheckoutPath(" ")).toThrow("tenantSlug is required");
});
});
@@ -1,3 +1,5 @@
import { appPath } from "~/utils/app/CanonicalUrlUtils";
export function subscriptionCheckoutPath(tenantSlug: string, path?: string) {
const tenantSegment = tenantSlug.trim();
if (!tenantSegment) {
@@ -19,5 +21,10 @@ export function subscriptionCheckoutPath(tenantSlug: string, path?: string) {
}
export function subscriptionRequiredCheckoutPath(tenantSlug: string) {
return subscriptionCheckoutPath(tenantSlug, "?error=subscription_required");
const tenantSegment = tenantSlug.trim();
if (!tenantSegment) {
throw new Error("tenantSlug is required");
}
return appPath({ tenantSlug: tenantSegment, path: "settings/subscription?subscription_required=1", mode: "host-aware" });
}
@@ -1,7 +1,7 @@
import { vi, describe, it, expect } from "vitest";
import SubscriptionUtils from "./SubscriptionUtils";
import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/SubscriptionBillingPeriod";
import { Prisma } from "@toolctrl/db/prisma-browser";
import { Prisma } from "@hivegrid/db/prisma-browser";
import DateUtils from "../shared/DateUtils";
describe("getProductTitle", () => {
@@ -1,4 +1,4 @@
import type { TenantUser } from "@toolctrl/db/prisma-browser";
import type { TenantUser } from "@hivegrid/db/prisma-browser";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
export const avatarText = (user: { firstName: string | null; lastName: string | null; email: string }): string => {
@@ -0,0 +1,133 @@
/**
* AK-P3 AP-2 — synchronous Audit-Export into the (private) object storage.
*
* Decision (ticket §1, Owner-confirmed): v1 is a synchronous export, NOT an
* async AuditExportJob (that is v2). The export builds a CSV/NDJSON artifact,
* uploads it to the files bucket under `audit-exports/...`, returns a short-lived
* signed download URL, and records an `audit.exported` event. A purpose
* (`Zweck`) is mandatory.
*
* Retention: the signed URL TTL is the fixed default retention window. Object
* cleanup of the `audit-exports/` prefix is a bucket lifecycle rule (infra) —
* there is no per-export tracking table in v1 (AuditExportJob = v2) and the
* storage adapter has no list operation, so an app-side enumerating cron is not
* possible here. Audit-LOG-row retention is handled by the existing worker job
* (`audit-retention`).
*/
import { getDbClient } from "@hivegrid/db/client.server";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { putBufferAsFile, resolveStorageBucket, hasStorageCredentials } from "~/utils/integrations/storageService";
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
import {
AUDIT_EXPORT_MAX_ROWS,
buildAuditExportWhere,
computeAuditIntegritySummary,
renderAuditExportCsv,
renderAuditExportNdjson,
type AuditExportFilters,
type AuditExportRow,
} from "~/routes/admin/audit-export.helpers.server";
/** Fixed default retention window for an export artifact (== signed-URL TTL). */
export const AUDIT_EXPORT_RETENTION_SECONDS = 7 * 24 * 60 * 60;
export type AuditExportFormat = "csv" | "ndjson";
export type AuditExportActor = {
id?: string | null;
email?: string | null;
type?: string | null;
ip?: string | null;
};
export type AuditExportToStorageInput = {
filters: AuditExportFilters;
format: AuditExportFormat;
/** Mandatory purpose-of-processing note (DoD: Zweck-Pflichtfeld). */
purpose: string;
actor: AuditExportActor;
/** Audit-chain scope: null = platform/admin export across all tenants. */
tenantId: string | null;
};
export type AuditExportToStorageResult = {
url: string;
key: string;
rowCount: number;
integrityOk: boolean;
expiresInSeconds: number;
};
/** Thrown when no purpose was supplied; the route maps this to an i18n message. */
export class AuditExportPurposeRequiredError extends Error {
constructor() {
super("audit_export_purpose_required");
this.name = "AuditExportPurposeRequiredError";
}
}
/** Thrown when no object storage is configured; the route maps this to i18n. */
export class AuditExportStorageUnavailableError extends Error {
constructor() {
super("audit_export_storage_unavailable");
this.name = "AuditExportStorageUnavailableError";
}
}
export function parseAuditExportFormat(raw: string | null | undefined): AuditExportFormat {
return raw === "ndjson" ? "ndjson" : "csv";
}
export async function runAuditExportToStorage(input: AuditExportToStorageInput): Promise<AuditExportToStorageResult> {
if (!input.purpose || input.purpose.trim().length === 0) {
throw new AuditExportPurposeRequiredError();
}
if (!hasStorageCredentials()) {
throw new AuditExportStorageUnavailableError();
}
const db = getDbClient();
const rows = (await db.auditEvent.findMany({
where: buildAuditExportWhere(input.filters),
orderBy: { createdAt: "asc" },
take: AUDIT_EXPORT_MAX_ROWS,
})) as unknown as AuditExportRow[];
const integrity = computeAuditIntegritySummary(rows);
const body = input.format === "ndjson" ? renderAuditExportNdjson(rows, integrity) : renderAuditExportCsv(rows, integrity);
const ext = input.format === "ndjson" ? "ndjson" : "csv";
const contentType = input.format === "ndjson" ? "application/x-ndjson; charset=utf-8" : "text/csv; charset=utf-8";
const scope = input.tenantId ?? "platform";
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
const rand = Math.random().toString(36).slice(2, 10);
const filename = `audit-export-${scope}-${stamp}.${ext}`;
const key = `audit-exports/${scope}/${stamp}-${rand}.${ext}`;
const bucket = resolveStorageBucket();
await putBufferAsFile({ bucket, key, body: new TextEncoder().encode(body), contentType });
const url = await createMediaDownloadUrl({ key, filename, ttlSeconds: AUDIT_EXPORT_RETENTION_SECONDS });
// Every export is itself audited (DoD: audit.exported), with the purpose recorded.
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.actor.id ?? null,
actorType: input.actor.type ?? "admin",
actorEmail: input.actor.email ?? null,
actorIp: input.actor.ip ?? null,
action: "audit.exported",
targetType: "AuditExport",
targetId: key,
sourceModule: "audit",
dataSensitivity: "confidential",
metadata: {
purpose: input.purpose.trim(),
format: input.format,
rowCount: rows.length,
integrityOk: integrity.ok,
key,
},
});
return { url, key, rowCount: rows.length, integrityOk: integrity.ok, expiresInSeconds: AUDIT_EXPORT_RETENTION_SECONDS };
}
@@ -2,7 +2,7 @@
* Phase 10 Task #67 — Inline PDF helper for the admin/tenant audit-export
* routes.
*
* Wraps `serializeAuditEventsToPdf` from `@toolctrl/exports/audit-pdf`
* Wraps `serializeAuditEventsToPdf` from `@hivegrid/exports/audit-pdf`
* with the same row + integrity shape the admin route already computes
* for the CSV path. Wired into the export route via `?format=pdf`
* (the default remains CSV).
@@ -18,7 +18,7 @@ import {
type AuditPdfIntegrity,
type AuditPdfLabelOverrides,
type AuditPdfReportInput,
} from "@toolctrl/exports/audit-pdf";
} from "@hivegrid/exports/audit-pdf";
import type { TFunction } from "i18next";
import type { AuditExportFilters, AuditExportRow, AuditIntegritySummary } from "~/routes/admin/audit-export.helpers.server";
@@ -27,7 +27,7 @@ export { AUDIT_PDF_CONTENT_TYPE, AUDIT_PDF_HARD_ROW_LIMIT };
/**
* Map an in-memory AuditExportRow (from the existing CSV pipeline) to
* the AuditPdfEvent shape consumed by @toolctrl/exports/audit-pdf.
* the AuditPdfEvent shape consumed by @hivegrid/exports/audit-pdf.
*
* `metadata` is opaque JSON in Prisma — we keep it as-is; the renderer
* never inlines metadata into the report body (privacy / page-density
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import type { WebConfig } from "@toolctrl/config";
import type { WebConfig } from "@hivegrid/config";
import { getPublicAuthProviders, getServerAuthProviders } from "./authProviders.server";
const baseWebConfig: WebConfig = {
@@ -13,7 +13,6 @@ const baseWebConfig: WebConfig = {
apiHost: "api.example.com",
protocol: "https",
},
stripe: {},
crisp: {},
captcha: {},
analytics: {},
@@ -1,4 +1,4 @@
import { loadRequiredWebConfig, type WebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig, type WebConfig } from "@hivegrid/config";
type AuthProviderRequestOptions = {
request?: Request;
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createSharedStore } from "@toolctrl/shared-store";
import { createSharedStore } from "@hivegrid/shared-store";
import {
checkMfaChallengeRateLimit,
@@ -20,31 +20,46 @@ afterEach(async () => {
__resetMfaChallengeRateLimitStoreForTests();
});
const toKey = (userId: string, ip: string) => ({ userId, perIp: `${userId}:${ip}` });
describe("MFA challenge rate limiter", () => {
it("keys attempts by user and client IP", () => {
it("keys attempts by user and a TRUSTED client IP, ignoring spoofable X-Forwarded-For", () => {
const request = new Request("https://admin.example.test/mfa-challenge", {
headers: { "x-forwarded-for": "203.0.113.5, 10.0.0.1" },
headers: {
// Attacker-forged forwarded header must be ignored...
"x-forwarded-for": "1.2.3.4, 10.0.0.1",
// ...in favour of the Cloudflare-set trusted header.
"cf-connecting-ip": "203.0.113.5",
},
});
expect(mfaChallengeRateLimitKey(request, "user_1")).toBe("user_1:203.0.113.5");
expect(mfaChallengeRateLimitKey(request, "user_1")).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.5" });
});
it("falls back from blank forwarded headers to real-ip and then unknown", () => {
it("falls back to x-real-ip and then unknown, never to x-forwarded-for", () => {
expect(
mfaChallengeRateLimitKey(
new Request("https://admin.example.test/mfa-challenge", {
headers: { "x-forwarded-for": " ", "x-real-ip": "198.51.100.7" },
headers: { "x-real-ip": "198.51.100.7" },
}),
"user_1",
),
).toBe("user_1:198.51.100.7");
expect(mfaChallengeRateLimitKey(new Request("https://admin.example.test/mfa-challenge"), "user_1")).toBe(
"user_1:unknown",
);
).toEqual({ userId: "user_1", perIp: "user_1:198.51.100.7" });
// Only a spoofable X-Forwarded-For present -> not trusted -> unknown.
expect(
mfaChallengeRateLimitKey(
new Request("https://admin.example.test/mfa-challenge", { headers: { "x-forwarded-for": "203.0.113.9" } }),
"user_1",
),
).toEqual({ userId: "user_1", perIp: "user_1:unknown" });
expect(mfaChallengeRateLimitKey(new Request("https://admin.example.test/mfa-challenge"), "user_1")).toEqual({
userId: "user_1",
perIp: "user_1:unknown",
});
});
it("blocks after repeated failed attempts and can be reset", async () => {
const key = "user_1:203.0.113.5";
const key = toKey("user_1", "203.0.113.5");
const now = new Date("2026-05-11T12:00:00.000Z");
for (let index = 0; index < 5; index += 1) {
@@ -62,12 +77,29 @@ describe("MFA challenge rate limiter", () => {
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
});
it("enforces the per-user cap even when the attacker rotates the client IP", async () => {
const now = new Date("2026-05-11T12:00:00.000Z");
// Attacker changes the trusted IP every attempt, so no per-IP bucket ever
// fills — but the per-user bucket (keyed on userId alone) still bounds them.
for (let index = 0; index < 15; index += 1) {
const key = toKey("victim", `203.0.113.${index}`);
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
await recordFailedMfaChallengeAttempt(key, now);
}
const blocked = await checkMfaChallengeRateLimit(toKey("victim", "203.0.113.99"), now);
expect(blocked.allowed).toBe(false);
if (!blocked.allowed) {
expect(blocked.retryAfterSeconds).toBe(900);
}
});
it("treats non-numeric stored counters as zero remaining attempts", async () => {
const store = createSharedStore({ namespace: "test-mfa-challenge-nan" });
__setMfaChallengeRateLimitStoreForTests(store);
const key = "user_1:203.0.113.5";
const key = toKey("user_1", "203.0.113.5");
const now = new Date("2026-05-11T12:00:00.000Z");
await store.set(`rl:fixed:mfa-challenge:${key}`, "NaN", { ttlSeconds: 300 });
await store.set(`rl:fixed:mfa-challenge:${key.perIp}`, "NaN", { ttlSeconds: 300 });
await expect(checkMfaChallengeRateLimit(key, now)).resolves.toEqual({
allowed: true,
@@ -77,7 +109,7 @@ describe("MFA challenge rate limiter", () => {
});
it("resetMfaChallengeRateLimiterForTests clears cached fixed-window keys", async () => {
const key = "user_1:203.0.113.5";
const key = toKey("user_1", "203.0.113.5");
const now = new Date("2026-05-11T12:00:00.000Z");
await recordFailedMfaChallengeAttempt(key, now);
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
@@ -90,6 +122,27 @@ describe("MFA challenge rate limiter", () => {
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
});
it("swallows scan failures while clearing cached rate-limit keys (best-effort cleanup)", async () => {
const store = createSharedStore({ namespace: "test-mfa-scan-throw" });
// Force the cleanup scan to reject so the best-effort catch path runs.
(store.adapter as unknown as { scan: () => AsyncIterable<string> }).scan = async function* () {
throw new Error("scan boom");
};
__setMfaChallengeRateLimitStoreForTests(store);
// Populate the cached limiter so the reset has a previous store to scan.
await checkMfaChallengeRateLimit(toKey("user_scan", "203.0.113.9"));
await expect(resetMfaChallengeRateLimiterForTests()).resolves.toBeUndefined();
});
it("falls back to the process shared store after the test override is reset", async () => {
// Drops the injected store and reverts storeFactory to the default web store.
__resetMfaChallengeRateLimitStoreForTests();
const result = await checkMfaChallengeRateLimit(toKey("default-factory-user", "9.9.9.9"));
expect(result.allowed).toBe(true);
});
it("uses the redis adapter when REDIS_URL is set", () => {
const originalRedisUrl = process.env.REDIS_URL;
try {
@@ -2,72 +2,103 @@ import {
createFixedWindowRateLimiter,
type FixedWindowRateLimiter,
type SharedStore,
} from "@toolctrl/shared-store";
} from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { getTrustedClientIp } from "~/utils/server/IpUtils";
// Per (user, IP) throttle. The IP is derived from a trusted, proxy-set header
// so it cannot be rotated by forging X-Forwarded-For.
const MFA_CHALLENGE_LIMIT = 5;
const MFA_CHALLENGE_WINDOW_SECONDS = 5 * 60;
// Authoritative per-user throttle, independent of IP. This is what actually
// bounds a brute-force attack: the victim's userId is fixed, so an attacker
// cannot escape it by changing IPs. Generous enough that a real user retrying
// their TOTP a few times never hits it, tight enough that guessing a 6-digit
// code stays astronomically unlikely.
const MFA_CHALLENGE_USER_LIMIT = 15;
const MFA_CHALLENGE_USER_WINDOW_SECONDS = 15 * 60;
export type MfaChallengeRateLimitKey = {
/** Per-user key, independent of IP — the authoritative brute-force bound. */
userId: string;
/** Per (user, trusted-IP) key for finer-grained throttling. */
perIp: string;
};
export type MfaChallengeRateLimitResult =
| { allowed: true; remaining: number; resetAt: Date }
| { allowed: false; retryAfterSeconds: number; resetAt: Date };
type Limiter = {
limiter: FixedWindowRateLimiter;
type Limiters = {
perIp: FixedWindowRateLimiter;
perUser: FixedWindowRateLimiter;
store: SharedStore;
};
let cached: Limiter | null = null;
let cached: Limiters | null = null;
let storeFactory: () => SharedStore = () => getSharedStore();
function getLimiter(): Limiter {
function getLimiters(): Limiters {
if (cached !== null) return cached;
const store = storeFactory();
cached = {
store,
limiter: createFixedWindowRateLimiter({
perIp: createFixedWindowRateLimiter({
store,
prefix: "mfa-challenge",
windowSeconds: MFA_CHALLENGE_WINDOW_SECONDS,
max: MFA_CHALLENGE_LIMIT,
}),
perUser: createFixedWindowRateLimiter({
store,
prefix: "mfa-challenge-user",
windowSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS,
max: MFA_CHALLENGE_USER_LIMIT,
}),
};
return cached;
}
export function mfaChallengeRateLimitKey(request: Request, userId: string) {
const forwardedFor = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
const ip = forwardedFor || request.headers.get("x-real-ip")?.trim() || "unknown";
return `${userId}:${ip}`;
export function mfaChallengeRateLimitKey(request: Request, userId: string): MfaChallengeRateLimitKey {
const ip = getTrustedClientIp(request);
return { userId, perIp: `${userId}:${ip}` };
}
export async function checkMfaChallengeRateLimit(key: string, now: Date = new Date()): Promise<MfaChallengeRateLimitResult> {
const { store } = getLimiter();
const suffix = `rl:fixed:mfa-challenge:${key}`;
const raw = await store.get(suffix);
const count = raw === null ? 0 : Number.parseInt(raw, 10) || 0;
if (count >= MFA_CHALLENGE_LIMIT) {
return {
allowed: false,
retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS,
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
};
export async function checkMfaChallengeRateLimit(key: MfaChallengeRateLimitKey, now: Date = new Date()): Promise<MfaChallengeRateLimitResult> {
const { store } = getLimiters();
const [perIpCount, perUserCount] = await Promise.all([
peekCount(store, `rl:fixed:mfa-challenge:${key.perIp}`),
peekCount(store, `rl:fixed:mfa-challenge-user:${key.userId}`),
]);
// Block as soon as either bound is reached. The per-user window is longer, so
// report its reset when it is the binding constraint.
if (perUserCount >= MFA_CHALLENGE_USER_LIMIT) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_USER_WINDOW_SECONDS * 1000) };
}
if (perIpCount >= MFA_CHALLENGE_LIMIT) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000) };
}
return {
allowed: true,
remaining: MFA_CHALLENGE_LIMIT - count,
remaining: Math.min(MFA_CHALLENGE_LIMIT - perIpCount, MFA_CHALLENGE_USER_LIMIT - perUserCount),
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
};
}
export async function recordFailedMfaChallengeAttempt(key: string, _now: Date = new Date()): Promise<void> {
const { limiter } = getLimiter();
await limiter.consume(key);
async function peekCount(store: SharedStore, suffix: string): Promise<number> {
const raw = await store.get(suffix);
return raw === null ? 0 : Number.parseInt(raw, 10) || 0;
}
export async function resetMfaChallengeRateLimit(key: string): Promise<void> {
const { limiter } = getLimiter();
await limiter.reset(key);
export async function recordFailedMfaChallengeAttempt(key: MfaChallengeRateLimitKey, _now: Date = new Date()): Promise<void> {
const { perIp, perUser } = getLimiters();
await Promise.all([perIp.consume(key.perIp), perUser.consume(key.userId)]);
}
export async function resetMfaChallengeRateLimit(key: MfaChallengeRateLimitKey): Promise<void> {
const { perIp, perUser } = getLimiters();
await Promise.all([perIp.reset(key.perIp), perUser.reset(key.userId)]);
}
export async function resetMfaChallengeRateLimiterForTests(): Promise<void> {
@@ -76,7 +107,9 @@ export async function resetMfaChallengeRateLimiterForTests(): Promise<void> {
if (previous) {
try {
for await (const fullKey of previous.store.adapter.scan(
`shared-store:${previous.store.namespace}:rl:fixed:mfa-challenge:*`,
// Matches both the per-IP (mfa-challenge:*) and per-user
// (mfa-challenge-user:*) buckets.
`shared-store:${previous.store.namespace}:rl:fixed:mfa-challenge*`,
)) {
const prefix = `shared-store:${previous.store.namespace}:`;
if (fullKey.startsWith(prefix)) {
@@ -0,0 +1,63 @@
// @vitest-environment node
//
// Fault-injection coverage for the hard-to-reach failure branches in
// recovery-codes.server: the HMAC-secret resolution (CRYPTO_SECRET vs the
// SESSION_SECRET fallback vs neither) and the "could not generate unique
// codes after retry" guard. Both need control over `@hivegrid/config` /
// `node:crypto`, so they live in a dedicated file with their own mocks
// instead of the env-driven happy-path suite.
import { describe, expect, test, vi } from "vitest";
const state = vi.hoisted(() => ({
secret: { cryptoSecret: "fault-crypto-secret", sessionSecret: "" } as { cryptoSecret?: string; sessionSecret?: string },
collapseEntropy: false,
}));
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => state.secret,
};
});
vi.mock("node:crypto", async () => {
const actual = await vi.importActual<typeof import("node:crypto")>("node:crypto");
return {
...actual,
// When collapsed, every random byte is 0 → every generated character is the
// first alphabet entry → all codes are identical → the uniqueness retry
// loop is exhausted. Real HMAC/equality stay intact via `actual`.
randomBytes: (size: number) =>
state.collapseEntropy ? Buffer.alloc(size, 0) : (actual.randomBytes as (n: number) => Buffer)(size),
};
});
import { generateRecoveryCodes, hashRecoveryCode } from "./recovery-codes.server";
describe("recovery-codes.server (fault injection)", () => {
test("falls back to SESSION_SECRET when CRYPTO_SECRET is unset", () => {
state.secret = { cryptoSecret: "", sessionSecret: "session-fallback-secret" };
const hash = hashRecoveryCode("2345-6789-ABCD");
expect(hash).toMatch(/^[a-f0-9]{64}$/);
});
test("throws a configuration error when neither CRYPTO_SECRET nor SESSION_SECRET is set", () => {
state.secret = { cryptoSecret: "", sessionSecret: "" };
expect(() => hashRecoveryCode("2345-6789-ABCD")).toThrow("CRYPTO_SECRET or SESSION_SECRET env variable not set");
});
test("throws when unique recovery codes cannot be generated after the retry budget is exhausted", () => {
state.secret = { cryptoSecret: "fault-crypto-secret", sessionSecret: "" };
state.collapseEntropy = true;
try {
expect(() => generateRecoveryCodes({ count: 2 })).toThrow(
"Failed to generate unique recovery codes after retry; suspected entropy source failure.",
);
} finally {
state.collapseEntropy = false;
}
});
});
@@ -155,4 +155,50 @@ describe("recovery-codes.server", () => {
expect(consumed.usedAt).toBeInstanceOf(Date);
expect(consumed.entries[0].usedAt).toBe(consumed.usedAt);
});
test("rejects non-positive and non-integer count, segment, and segment-length parameters", async () => {
const { generateRecoveryCode, generateRecoveryCodes, normalizeRecoveryCode } = await import("./recovery-codes.server");
// Integer-but-non-positive values reach the `value <= 0` guard branch...
expect(() => generateRecoveryCode({ segments: 0 })).toThrow("segments must be a positive integer");
expect(() => generateRecoveryCode({ segmentLength: -1 })).toThrow("segmentLength must be a positive integer");
expect(() => generateRecoveryCodes({ count: 0 })).toThrow("count must be a positive integer");
expect(() => normalizeRecoveryCode("2345-6789-ABCD", { segments: 0 })).toThrow("segments must be a positive integer");
expect(() => normalizeRecoveryCode("2345-6789-ABCD", { segmentLength: 0 })).toThrow("segmentLength must be a positive integer");
// ...while a fractional value trips the `!Number.isInteger(value)` guard first.
expect(() => generateRecoveryCode({ segments: 2.5 })).toThrow("segments must be a positive integer");
});
test("generateRecoveryCode honours explicit shapes and falls back to the default segment layout", async () => {
const { generateRecoveryCode } = await import("./recovery-codes.server");
// No options → both `??` defaults are exercised (3 segments × 4 chars).
expect(generateRecoveryCode()).toMatch(codePattern);
// Explicit options → the provided values win over the defaults.
expect(generateRecoveryCode({ segments: 2, segmentLength: 5 })).toMatch(
/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{5}-[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{5}$/,
);
});
test("status helper keeps the most recent usage timestamp and stays null-safe when the first entry lacks a creation date", async () => {
const { getRecoveryCodeStatus } = await import("./recovery-codes.server");
// Two used entries with the later one first forces the reduce to keep the
// running `latest` (the `entry > latest` comparison resolves to false), and
// an undefined `createdAt` on the first entry exercises the `?? null`
// fallback for `generatedAt`.
const entries = [
{ hash: "aa", usedAt: new Date("2026-05-08T10:00:00.000Z"), createdAt: undefined as unknown as Date },
{ hash: "bb", usedAt: new Date("2026-05-08T09:00:00.000Z"), createdAt: new Date("2026-05-08T08:00:00.000Z") },
];
expect(getRecoveryCodeStatus(entries)).toEqual({
configured: true,
totalCount: 2,
remainingCount: 0,
usedCount: 2,
generatedAt: null,
lastUsedAt: new Date("2026-05-08T10:00:00.000Z"),
});
});
});
@@ -1,5 +1,5 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig } from "@hivegrid/config";
export const DEFAULT_RECOVERY_CODE_COUNT = 10;
export const DEFAULT_RECOVERY_CODE_SEGMENTS = 3;
@@ -122,6 +122,23 @@ describe("step-up.server", () => {
}
});
test("falls back to the wall clock when no timestamp is supplied for set or check", async () => {
const session = await createSession();
// No `now` → setMfaStepUpState stamps the current time...
const state = setMfaStepUpState(session, { userId: "admin-1", method: "totp" });
expect(typeof state.verifiedAt).toBe("string");
expect(Number.isNaN(Date.parse(state.verifiedAt))).toBe(false);
// ...and checkMfaStepUpState with no options compares against the current time.
const result = checkMfaStepUpState(session, "admin-1");
expect(result.verified).toBe(true);
if (result.verified) {
expect(result.ageMs).toBeGreaterThanOrEqual(0);
expect(result.ageMs).toBeLessThan(MFA_STEP_UP_MAX_AGE_MS);
}
});
test("clears existing MFA step-up state", async () => {
const session = await createSession();
setMfaStepUpState(session, { userId: "admin-1", method: "totp", now: new Date("2026-05-08T14:00:00.000Z") });
@@ -4,8 +4,8 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@toolctrl/config", async () => {
const actual = await vi.importActual<typeof import("@toolctrl/config")>("@toolctrl/config");
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => ({ nodeEnv: "test", sessionSecret: "test-session-secret-please-change" }),
@@ -32,6 +32,7 @@ import {
clearTrustedDeviceCookie,
forgetCurrentTrustedDevice,
isTrustedDevice,
listTrustedDevices,
rememberDeviceForUser,
revokeAllTrustedDevices,
revokeTrustedDevice,
@@ -128,6 +129,25 @@ describe("trusted-device (DB-backed)", () => {
expect(findUnique).not.toHaveBeenCalled();
});
it("lists active trusted devices scoped to the owner, newest-used first", async () => {
const rows = [activeRow({ id: "td-1" }), activeRow({ id: "td-2" })];
vi.mocked(db.trustedDevice.findMany).mockResolvedValue(rows as never);
await expect(listTrustedDevices("user-1")).resolves.toEqual(rows);
expect(db.trustedDevice.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({ userId: "user-1", revokedAt: null }),
orderBy: { lastUsedAt: "desc" },
}),
);
});
it("treats a database failure during the trust lookup as not-trusted", async () => {
const request = await rememberAndGetRequest("user-1");
findUnique.mockRejectedValue(new Error("db unavailable"));
await expect(isTrustedDevice(request, "user-1")).resolves.toBe(false);
});
it("revokes a single device scoped to the owner", async () => {
updateMany.mockResolvedValue({ count: 1 } as never);
await expect(revokeTrustedDevice({ userId: "user-1", deviceId: "td-1" })).resolves.toBe(true);
@@ -1,20 +1,16 @@
import { createHash, randomBytes } from "node:crypto";
import { createCookie } from "react-router";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { db } from "~/utils/db.server";
import { buildSessionDeviceContext } from "~/services/auth/sessionLifecycle.server";
// D1 (Trust-Device) — "diesem Geraet vertrauen" beim 2FA-Login. Der Marker UEBERLEBT den Logout
// (deshalb NICHT die per-Session `UserSession.trustedAt`), ist aber WIDERRUFBAR: ein eigenes, langlebiges
// Cookie (`RJ_trusted_device`) traegt einen opaken Zufalls-Token, persistiert wird nur dessen SHA-256-Hash
// in der Tabelle `TrustedDevice`. Autoritaet ist die Tabelle (Revoke einzeln / "ueberall vergessen" ueber
// Settings > Sicherheit) -> erfuellt den DoD-Screen "Trust-Device-Revoke" (R-P2a). Das Cookie ist nur der
// Traeger; ohne passende, aktive Zeile gilt das Geraet als NICHT vertrauenswuerdig.
// The trust-device marker survives logout, stays revocable via TrustedDevice,
// and stores only the SHA-256 hash of the opaque cookie token in the database.
export const TRUSTED_DEVICE_COOKIE_NAME = "RJ_trusted_device";
export const TRUSTED_DEVICE_COOKIE_NAME = "hivegrid_trusted_device";
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 Tage
const TRUSTED_DEVICE_TOKEN_BYTES = 32;
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // lastUsedAt hoechstens alle 5min fortschreiben
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // throttle lastUsedAt updates to every 5 minutes
export type TrustedDeviceRow = Awaited<ReturnType<typeof db.trustedDevice.create>>;
@@ -17,8 +17,8 @@ describe("resolveAssetBase", () => {
});
it("returns origin with trailing slash for a valid https URL", () => {
expect(resolveAssetBase({ ASSET_CDN_URL: "https://cdn.boiler.saas-ctrl.com" }, "production")).toBe(
"https://cdn.boiler.saas-ctrl.com/"
expect(resolveAssetBase({ ASSET_CDN_URL: "https://cdn.hivegrid.de" }, "production")).toBe(
"https://cdn.hivegrid.de/"
);
});
@@ -38,7 +38,6 @@ const EMPTY_CHUNK_ALLOWLIST = new Set([
"dry-run",
"healthcheck",
"healthz",
"ip-address-log-labels",
"logout",
"null",
"onboarding._id",
@@ -24,7 +24,7 @@ describe("vite config integration wiring", () => {
it("keeps production source maps opt-in for Sentry release lanes", async () => {
const source = await readViteConfigSource();
expect(source).toContain('process.env.TOOLCTRL_BUILD_SOURCEMAPS === "1"');
expect(source).toContain('process.env.HIVEGRID_BUILD_SOURCEMAPS === "1"');
expect(source).toContain("process.env.SENTRY_AUTH_TOKEN && buildSourcemapsEnabled");
expect(source).toMatch(/sourcemap:\s*buildSourcemapsEnabled/);
});
@@ -13,6 +13,9 @@ const routePathCases: Array<{
}> = [
{ routeId: "index", expected: undefined, note: "root index" },
{ routeId: "admin/index", expected: "admin", note: "nested index" },
{ routeId: "_index", expected: undefined, note: "v2 flat root index" },
{ routeId: "app.$tenant/files._index", expected: "app/:tenant/files", note: "v2 flat module index strips trailing _index" },
{ routeId: "app.$tenant/files.$id", expected: "app/:tenant/files/:id", note: "v2 flat nested param sibling" },
{ routeId: "__auth/login", expected: "login", note: "pathless layout segment" },
{ routeId: "account/(settings)", expected: "account/settings?", note: "optional segment" },
{ routeId: "docs/[sitemap.xml]", expected: "docs/sitemap.xml", note: "escaped dot segment" },
@@ -151,6 +154,30 @@ describe("v1 route convention path creation", () => {
expect(Object.values(promotedTenantRoutes).every((entry) => typeof entry.file === "string")).toBe(true);
});
it("registers v2 flat _index module routes at the parent path, not /_index", () => {
tempAppDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "v1-route-convention-"));
writeRouteFixture("routes/_index.tsx");
writeRouteFixture("routes/app.$tenant.tsx");
writeRouteFixture("routes/app.$tenant/files._index.tsx");
writeRouteFixture("routes/app.$tenant/files.$id.tsx");
writeRouteFixture("routes/app.$tenant/contacts._index.tsx");
const manifest = createRoutesFromFolders(defineRouteManifest, {
appDirectory: tempAppDirectory,
});
const byId = Object.fromEntries(Object.values(manifest).map((entry) => [entry.id, { path: entry.path, index: entry.index }]));
// Root _index is the index of the layout tree (no path).
expect(byId["routes/_index"]).toEqual({ path: undefined, index: true });
// A flat module _index becomes the leaf route AT the module path (renders /:tenant/files),
// not a literal "/files/_index" segment, and is not itself an index route.
expect(byId["routes/app.$tenant/files._index"]).toEqual({ path: "files", index: undefined });
expect(byId["routes/app.$tenant/contacts._index"]).toEqual({ path: "contacts", index: undefined });
// Sibling param route keeps its nested path.
expect(byId["routes/app.$tenant/files.$id"]).toEqual({ path: "files/:id", index: undefined });
});
it("ignores server-only files when requested by the route config", () => {
tempAppDirectory = fs.mkdtempSync(path.join(os.tmpdir(), "v1-route-convention-"));
@@ -106,7 +106,11 @@ export function createRoutesFromFolders(defineRoutes: DefineRoutesFunction, opti
for (let routeId of childRouteIds) {
let routePath: string | undefined = createRoutePath(routeId.slice((parentId || routesDirectory).length + 1));
let isIndexRoute = routeId.endsWith("/index");
// Index when the parent-relative path resolves to nothing and the final
// segment is the index marker. Supports the v1 `index` filename and the
// v2 flat `_index` filename. A flat `foo._index` (relative path "foo") is
// NOT an index — it is the leaf route at `/foo`.
let isIndexRoute = routePath === undefined && /(?:^|[/.])_?index$/.test(routeId);
let fullPath = createRoutePath(routeId.slice(routesDirectory.length + 1));
fullPath = promoteTenantAppRoutePath(fullPath);
routePath = promoteTenantAppRoutePath(routePath);
@@ -196,7 +200,11 @@ export function createRoutesFromFolders(defineRoutes: DefineRoutesFunction, opti
for (let routeId of childRouteIds) {
const routePath = createAdminHostRoutePath(routeId, parentId);
let isIndexRoute = routeId.endsWith("/index");
// Index when the parent-relative path resolves to nothing and the final
// segment is the index marker. Supports the v1 `index` filename and the
// v2 flat `_index` filename. A flat `foo._index` (relative path "foo") is
// NOT an index — it is the leaf route at `/foo`.
let isIndexRoute = routePath === undefined && /(?:^|[/.])_?index$/.test(routeId);
if (isIndexRoute) {
defineRoute(routePath, files[routeId], { index: true, id: getAdminHostRouteId(routeId) });
@@ -297,8 +305,8 @@ export function createRoutePath(partialRouteId: string): string | undefined {
}
if (isSegmentSeparator(char)) {
if (rawSegmentBuffer === "index" && result.endsWith("index")) {
result = result.replace(/\/?index$/, "");
if ((rawSegmentBuffer === "index" || rawSegmentBuffer === "_index") && result.endsWith("index")) {
result = result.replace(/\/?_?index$/, "");
} else {
result += "/";
}
@@ -327,13 +335,13 @@ export function createRoutePath(partialRouteId: string): string | undefined {
result += char;
}
if (rawSegmentBuffer === "index" && result.endsWith("index")) {
result = result.replace(/\/?index$/, "");
if ((rawSegmentBuffer === "index" || rawSegmentBuffer === "_index") && result.endsWith("index")) {
result = result.replace(/\/?_?index$/, "");
} else {
result = result.replace(/\/$/, "");
}
if (rawSegmentBuffer === "index" && result.endsWith("index?")) {
if ((rawSegmentBuffer === "index" || rawSegmentBuffer === "_index") && result.endsWith("index?")) {
throw new Error(`Invalid route path: ${partialRouteId}. Make index route optional by using (index)`);
}
@@ -8,10 +8,7 @@ vi.mock("~/utils/cache.server", () => ({
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({
resolveTenantProductAccess: vi.fn(),
}));
vi.mock("~/utils/services/.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(async () => null),
resolveTenantEntitlementSubscription: vi.fn(async () => null),
}));
vi.mock("~/utils/services/.server/featureFlagEvaluator.server", () => ({
@@ -19,13 +16,12 @@ vi.mock("~/utils/services/.server/featureFlagEvaluator.server", () => ({
}));
import { clearCacheKeyPrefix } from "~/utils/cache.server";
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService";
import { resolveTenantEntitlementSubscription, resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { evaluateFlagForContext } from "~/utils/services/.server/featureFlagEvaluator.server";
import { invalidateTenantModuleAccessCache, tenantHasFlag, tenantHasModule } from "./tenantConnector.server";
const resolveMock = vi.mocked(resolveTenantProductAccess);
const subscriptionMock = vi.mocked(getActiveTenantSubscriptions);
const subscriptionMock = vi.mocked(resolveTenantEntitlementSubscription);
const flagMock = vi.mocked(evaluateFlagForContext);
const clearPrefixMock = vi.mocked(clearCacheKeyPrefix);
@@ -42,9 +38,7 @@ describe("tenantHasModule", () => {
expect(allowed).toBe(true);
expect(subscriptionMock).toHaveBeenCalledWith("t1");
expect(resolveMock).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "t1", userId: "u1", featureKey: "crm-basic" })
);
expect(resolveMock).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "t1", userId: "u1", featureKey: "crm-basic" }));
});
it("returns false when the product-access decision denies the module", async () => {
@@ -1,6 +1,5 @@
import { cachified, clearCacheKeyPrefix } from "~/utils/cache.server";
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { getActiveTenantSubscriptions } from "~/utils/services/.server/subscriptionService";
import { resolveTenantEntitlementSubscription, resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { evaluateFlagForContext } from "~/utils/services/.server/featureFlagEvaluator.server";
/**
@@ -10,10 +9,9 @@ import { evaluateFlagForContext } from "~/utils/services/.server/featureFlagEval
* Loader-Guard). Beide bauen auf bestehende Resolver auf, statt sie nachzubauen:
*
* - `tenantHasModule()` — "Darf dieser Tenant dieses Modul nutzen?" Brücke Billing↔Feature-Gate:
* prüft Abo/Entitlement (`SubscriptionFeature` über das aktive Tenant-Abo), Produkt-Blueprint,
* prüft lokalen Billing-State/Entitlements, Produkt-Blueprint,
* Tenant-Override und ggf. Tenant-Rollen-Permission via {@link resolveTenantProductAccess}.
* Die Modul-Entscheidung wird auf Connector-Ebene gecacht (`getActiveTenantSubscriptions` ist
* bereits gecacht; die zusätzlichen Konfigurations-/Override-/Permission-Queries nicht).
* Die Modul-Entscheidung wird auf Connector-Ebene gecacht.
*
* - `tenantHasFlag()` — "Ist dieses Feature-Flag für diesen Kontext aktiv?" Delegiert an den
* v2-Evaluator {@link evaluateFlagForContext}, der bereits eigenen Eval-Cache mitbringt.
@@ -51,7 +49,7 @@ export async function tenantHasModule(input: TenantModuleAccessInput): Promise<b
key: moduleCacheKey(input),
ttl: MODULE_CACHE_TTL_MS,
getFreshValue: async () => {
const subscription = await getActiveTenantSubscriptions(input.tenantId);
const subscription = await resolveTenantEntitlementSubscription(input.tenantId);
const decision = await resolveTenantProductAccess({
tenantId: input.tenantId,
userId: input.userId,
@@ -87,7 +85,7 @@ export async function tenantHasFlag(input: TenantFlagContext): Promise<boolean>
/**
* Verwirft alle gecachten Modul-Entscheidungen eines Tenants. Aufrufen nach Abo-/Override-/
* Rollen-Änderungen (z.B. Stripe-Webhook, Admin-Plan-Wechsel), damit das Gate sofort nachzieht.
* Rollen-Änderungen (z.B. Billing-Sync, Admin-Plan-Wechsel), damit das Gate sofort nachzieht.
*/
export function invalidateTenantModuleAccessCache(tenantId: string): void {
clearCacheKeyPrefix(`${MODULE_CACHE_PREFIX}${tenantId}:`);
@@ -6,15 +6,12 @@ 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 { getSetupSteps } from "~/utils/services/setupService";
import type { SetupItem } from "~/application/dtos/setup/SetupItem";
import type { Stat } from "~/application/dtos/stats/Stat";
import type { PaginationDto } from "~/application/dtos/data/PaginationDto";
export type AdminDashboardLoaderData = {
title: string;
stats: Stat[];
setupSteps: SetupItem[];
tenants: {
items: TenantWithUsage[];
pagination: PaginationDto;
@@ -29,13 +26,12 @@ export async function loadAdminDashboardRouteData({ request, params }: AdminDash
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const { t } = await time(getTranslations(request), "getTranslations");
const { stats, setupSteps, tenants } = await time(
const { stats, tenants } = await time(
promiseHash({
stats: time(
getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) }),
"admin.dashboard.details.getAdminDashboardStats"
),
setupSteps: time(getSetupSteps(), "admin.dashboard.details.getSetupSteps"),
tenants: time(adminGetAllTenantsWithUsage(undefined, currentPagination), "admin.dashboard.details.adminGetAllTenantsWithUsage"),
}),
"admin.dashboard.details"
@@ -44,7 +40,6 @@ export async function loadAdminDashboardRouteData({ request, params }: AdminDash
const data: AdminDashboardLoaderData = {
title: `${t("app.sidebar.dashboard")} | ${process.env.APP_NAME}`,
stats,
setupSteps,
tenants,
};
return { data, headers: getServerTimingHeader() };
@@ -3,12 +3,10 @@ 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 { getAllEntities } from "~/utils/db/entities/entities.db.server";
import { getAllEntityGroups } from "~/utils/db/entities/entityGroups.db.server";
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 "@toolctrl/db/auth-boundary.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";
@@ -16,7 +14,7 @@ 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 "@toolctrl/db/auth-boundary.server";
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
import { TFunction } from "i18next";
import { redirect } from "react-router";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
@@ -55,12 +53,10 @@ export async function loadAdminData({ request, t }: { request: Request; t: TFunc
const myTenants = await time(getMyTenants(user.id), "getMyTenants");
const { allPermissions, superAdminRole, entities, entityGroups, allRoles, myGroups, onboardingSession } = await time(
const { allPermissions, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
promiseHash({
allPermissions: getPermissionsByUser(userInfo.userId, null),
superAdminRole: getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin),
entities: getAllEntities({ tenantId: null }),
entityGroups: getAllEntityGroups(),
allRoles: getAllRolesWithoutPermissions("admin"),
myGroups: getMyGroups(user.id, null),
onboardingSession: OnboardingService.getUserActiveOnboarding({ userId: user.id, tenantId: null, request }),
@@ -71,8 +67,6 @@ export async function loadAdminData({ request, t }: { request: Request; t: TFunc
user,
myTenants,
currentTenant: null,
entities,
entityGroups,
// roles,
allRoles,
permissions: allPermissions.map((f) => f as DefaultPermission),
@@ -27,7 +27,7 @@ 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("@toolctrl/db/auth-boundary.server", () => ({
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
getAuthUserWithoutPasswordById: vi.fn(async () => ({ id: "user_1", admin: false, locale: "en" })),
getTenantsForUser: vi.fn(async () => [{ id: "tenant_1", slug: "acme", name: "Acme" }]),
}));
@@ -36,9 +36,7 @@ vi.mock("~/utils/db/tenants.db.server", () => ({
getTenantSimple: vi.fn(async () => ({ id: "tenant_1", slug: "acme", name: "Acme", deactivatedReason: null })),
getTenantUserType: vi.fn(() => mocks.postDetails.tenantUser.promise),
}));
vi.mock("@toolctrl/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: {} })) }));
vi.mock("~/utils/db/entities/entities.db.server", () => ({ getAllEntities: vi.fn(async () => []) }));
vi.mock("~/utils/db/entities/entityGroups.db.server", () => ({ getAllEntityGroups: vi.fn(async () => []) }));
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", () => ({
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";
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("@toolctrl/db/auth-boundary.server", () => ({
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
getAuthUserWithoutPasswordById: vi.fn(async () => ({ id: "user_1", admin: false, locale: "en" })),
getTenantsForUser: vi.fn(),
}));
@@ -10,9 +10,7 @@ vi.mock("~/utils/db/tenants.db.server", () => ({
getTenantSimple: vi.fn(async () => ({ id: "tenant_1", slug: "acme", name: "Acme", deactivatedReason: null })),
getTenantUserType: vi.fn(),
}));
vi.mock("@toolctrl/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: {} })) }));
vi.mock("~/utils/db/entities/entities.db.server", () => ({ getAllEntities: vi.fn() }));
vi.mock("~/utils/db/entities/entityGroups.db.server", () => ({ getAllEntityGroups: vi.fn() }));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: {} })) }));
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", () => ({
@@ -1,7 +1,6 @@
import { Params, redirect } from "react-router";
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { timeFake, TimeFunction } from "~/modules/metrics/services/.server/MetricTracker";
@@ -9,14 +8,12 @@ import OnboardingService from "~/modules/onboarding/services/OnboardingService";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import UrlUtils from "~/utils/app/UrlUtils";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { getAllEntities } from "~/utils/db/entities/entities.db.server";
import { getAllEntityGroups } from "~/utils/db/entities/entityGroups.db.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
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 { adminGetAllActiveTenantSimple, getTenantSimple, getTenantUserType } from "~/utils/db/tenants.db.server";
import { getAuthUserWithoutPasswordById as getUser, getTenantsForUser as getMyTenants } from "@toolctrl/db/auth-boundary.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";
@@ -27,13 +24,31 @@ import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatur
import { CreditTypes } from "~/modules/usage/dtos/CreditType";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { TFunction } from "i18next";
import { featureKeys, type FeatureKey } from "@toolctrl/entitlements";
import { featureKeys, type FeatureKey } from "@hivegrid/entitlements";
import { resolveTenantProductAccess } 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
// listed here — a key missing from this list resolves to no productAccess entry
// and silently hides the sidebar item for ALL tenants/plans (recurring footgun:
// files+tasks were re-added in 1017cf58b; dashboard/automation/leads/projects/
// hr/integrations/email-inbox/booking/forms re-added 2026-07-07 after the R-P5
// verification found "Integrationen" unreachable despite being plan-included).
const tenantNavigationFeatureKeys = [
featureKeys.dashboard,
featureKeys.crmBasic,
featureKeys.leads,
featureKeys.projects,
featureKeys.files,
featureKeys.tasks,
featureKeys.hr,
featureKeys.integrations,
featureKeys.booking,
featureKeys.forms,
featureKeys.search,
featureKeys.automation,
featureKeys.emailMarketing,
featureKeys.emailInbox,
featureKeys.api,
featureKeys.workflowEngine,
featureKeys.credits,
@@ -51,6 +66,7 @@ export async function loadAppData({
tenantId: preloadedTenantId,
userInfo: preloadedUserInfo,
user: preloadedUser,
isOperatorAdmin: preloadedIsOperatorAdmin,
}: {
request: Request;
params: Params;
@@ -59,6 +75,7 @@ export async function loadAppData({
tenantId?: string;
userInfo?: Awaited<ReturnType<typeof getUserInfo>>;
user?: Awaited<ReturnType<typeof getUser>>;
isOperatorAdmin?: boolean;
}) {
const { tenantId, userInfo } = await time(
promiseHash({
@@ -94,18 +111,14 @@ 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}`);
}
let { myTenants, mySubscription, allPermissions, superUserRole, superAdminRole, entities, entityGroups, allRoles, myGroups, onboardingSession } = await time(
const operatorAdmin = Boolean(user.admin) || Boolean(preloadedIsOperatorAdmin);
let { myTenants, mySubscription, allPermissions, superUserRole, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
promiseHash({
myTenants: time(user.admin ? adminGetAllActiveTenantSimple() : getMyTenants(user.id), "loadAppData.getDetails.getMyTenants"),
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"),
entities: time(
getAllEntities({ tenantId, active: true, types: [DefaultEntityTypes.All, DefaultEntityTypes.AppOnly] }),
"loadAppData.getDetails.getAllEntities"
),
entityGroups: time(getAllEntityGroups(), "loadAppData.getDetails.getAllEntityGroups()"),
allRoles: time(getAllRolesWithoutPermissions("app"), "loadAppData.getDetails.getAllRolesWithoutPermissions"),
myGroups: time(getMyGroups(user.id, currentTenant.id), "loadAppData.getDetails.getMyGroups"),
onboardingSession: time(
@@ -134,7 +147,7 @@ export async function loadAppData({
featureKey,
subscription: mySubscription,
tenantRolePermissionNames: allPermissions,
bypassTenantRolePermission: !!user.admin || !!superAdminRole,
bypassTenantRolePermission: operatorAdmin || !!superAdminRole,
}),
] as const)
),
@@ -143,7 +156,7 @@ export async function loadAppData({
}),
"loadAppData.postDetails"
);
const currentRole = user.admin ? TenantUserType.ADMIN : tenantUser?.type ?? TenantUserType.MEMBER;
const currentRole = operatorAdmin ? TenantUserType.ADMIN : tenantUser?.type ?? TenantUserType.MEMBER;
const data: AppLoaderData = {
// i18n: i18n.translations,
user,
@@ -151,8 +164,6 @@ export async function loadAppData({
currentTenant,
currentRole,
mySubscription,
entities,
entityGroups,
// roles,
allRoles,
permissions: allPermissions.map((f) => f as DefaultPermission),
@@ -26,10 +26,10 @@ function readLoader(relativePath: string) {
}
describe("auth boundary imports for shared data loaders", () => {
it.each(dataLoaderPaths)("imports migrated auth/user/tenant reads from @toolctrl/db in $path", ({ path: relativePath }) => {
it.each(dataLoaderPaths)("imports migrated auth/user/tenant reads from @hivegrid/db in $path", ({ path: relativePath }) => {
const source = readLoader(relativePath);
expect(source).toContain("@toolctrl/db/auth-boundary.server");
expect(source).toContain("@hivegrid/db/auth-boundary.server");
});
it.each(dataLoaderPaths)("does not import migrated app DB wrappers in $path", ({ path: relativePath, blockedImports }) => {
@@ -43,10 +43,10 @@ describe("auth boundary imports for shared data loaders", () => {
});
describe("auth boundary imports for tenant selection routes", () => {
it.each(tenantSelectionRoutePaths)("imports migrated auth/user/tenant reads from @toolctrl/db in %s", (relativePath) => {
it.each(tenantSelectionRoutePaths)("imports migrated auth/user/tenant reads from @hivegrid/db in %s", (relativePath) => {
const source = readLoader(relativePath);
expect(source).toContain("@toolctrl/db/auth-boundary.server");
expect(source).toContain("@hivegrid/db/auth-boundary.server");
});
it.each(tenantSelectionRoutePaths)("does not import migrated app DB wrappers in %s", (relativePath) => {
@@ -1,10 +1,11 @@
import { loadRequiredWebConfig } from "@toolctrl/config";
import { getAuthUserWithoutPasswordById as getUser, getTenantById as getTenant, getTenantByIdOrSlug } from "@toolctrl/db/auth-boundary.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getAuthUserWithoutPasswordById as getUser, getTenantById as getTenant, getTenantByIdOrSlug } from "@hivegrid/db/auth-boundary.server";
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 { resolveAnrede } from "~/locale/anrede.server";
import { getCurrentEnabledFlagNames } from "~/utils/services/.server/featureFlagsRequest.server";
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
import { getAnalyticsSession, generateAnalyticsUserId, commitAnalyticsSession, destroyAnalyticsSession } from "~/utils/analyticsCookie.server";
@@ -71,12 +72,18 @@ export async function loadRootData({ request, params }: { request: Request; para
}
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,
anrede,
theme: userInfo.theme || appConfiguration.app.theme,
serverUrl: getBaseURL(request),
publicBaseUrl: getAbsoluteUrl(request, "/"),
@@ -86,7 +93,6 @@ export async function loadRootData({ request, params }: { request: Request; para
userSession: userInfo,
authenticated: userInfo.userId?.length > 0,
debug: webConfig.nodeEnv === "development",
isStripeTest: webConfig.stripe.secretKey?.startsWith("sk_test_") ?? true,
chatWebsiteId: webConfig.crisp.chatWebsiteId,
appConfiguration,
csrf,
@@ -1,12 +1,10 @@
import { useMatches } from "react-router";
import { AppOrAdminData } from "./useAppOrAdminData";
import EntitiesSingleton from "~/modules/rows/repositories/EntitiesSingleton";
export type AdminLoaderData = AppOrAdminData;
export function useAdminData(): AdminLoaderData {
const paths: string[] = ["routes/admin", "routes/admin.__host"];
const adminData = (useMatches().find((f) => paths.includes(f.id.toLowerCase()))?.data ?? {}) as AdminLoaderData;
EntitiesSingleton.getInstance().setEntities(adminData.entities);
return adminData;
}
@@ -1,4 +1,4 @@
import { Tenant, TenantUser } from "@toolctrl/db/prisma-browser";
import { Tenant, TenantUser } from "@hivegrid/db/prisma-browser";
import { useMatches } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import { getTenantWithUsers } from "../db/tenants.db.server";
@@ -3,7 +3,6 @@ import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { TenantSimple } from "../db/tenants.db.server";
import { TenantSubscriptionWithDetails } from "../db/tenantSubscriptions.db.server";
import { AppOrAdminData } from "./useAppOrAdminData";
import EntitiesSingleton from "~/modules/rows/repositories/EntitiesSingleton";
export type AppLoaderData = AppOrAdminData & {
currentTenant: TenantSimple;
@@ -14,6 +13,5 @@ export type AppLoaderData = AppOrAdminData & {
export function useAppData(): AppLoaderData {
const paths: string[] = ["routes/app.$tenant", "routes/app"];
const appData = (useMatches().find((f) => paths.includes(f.id.toLowerCase()))?.data ?? {}) as AppLoaderData;
EntitiesSingleton.getInstance().setEntities(appData.entities);
return appData;
}
@@ -3,14 +3,12 @@ import { TenantSimple } from "../db/tenants.db.server";
import { UserWithoutPassword } from "../db/users.db.server";
import { AppLoaderData } from "./useAppData";
import { AdminLoaderData } from "./useAdminData";
import { EntityWithDetails } from "../db/entities/entities.db.server";
import { GroupWithDetails } from "../db/permissions/groups.db.server";
import { OnboardingSessionWithDetails } from "~/modules/onboarding/db/onboardingSessions.db.server";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { EntityGroupWithDetails } from "../db/entities/entityGroups.db.server";
import { TenantTypeWithDetails } from "../db/tenants/tenantTypes.db.server";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import type { ProductAccessDecision } from "@toolctrl/entitlements";
import type { ProductAccessDecision } from "@hivegrid/entitlements";
export type AppOrAdminData = {
// i18n: Record<string, Language>;
@@ -20,8 +18,6 @@ export type AppOrAdminData = {
allRoles: { id: string; name: string; description: string }[];
// roles: UserRoleWithPermission[];
permissions: DefaultPermission[];
entities: EntityWithDetails[];
entityGroups: EntityGroupWithDetails[];
isSuperUser: boolean;
isSuperAdmin: boolean;
myGroups: GroupWithDetails[];
@@ -7,6 +7,7 @@ import { AnalyticsInfoDto } from "~/application/dtos/marketing/AnalyticsInfoDto"
import { UserWithoutPassword } from "../db/users.db.server";
import { TenantSimple } from "../db/tenants.db.server";
import type { PublicDomainRoutingConfig } from "~/utils/app/CrossHostUrls";
import type { Anrede } from "@hivegrid/i18n";
export type AppRootData = {
metatags: MetaTagsDto;
@@ -14,6 +15,7 @@ export type AppRootData = {
currentTenant: TenantSimple | null;
theme: string;
locale: string;
anrede: Anrede;
serverUrl: string;
publicBaseUrl: string;
apiBaseUrl: string;
@@ -22,7 +24,6 @@ export type AppRootData = {
userSession: UserSession;
authenticated: boolean;
debug: boolean;
isStripeTest: boolean;
chatWebsiteId?: string;
appConfiguration: AppConfiguration;
csrf?: string;
@@ -1,4 +1,4 @@
import { getDbClient, getReadDbClient } from "@toolctrl/db/client.server";
import { getDbClient, getReadDbClient } from "@hivegrid/db/client.server";
const db = getDbClient();
@@ -0,0 +1,112 @@
// @vitest-environment node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
// R-P5 — APPS-ENGINE RLS GATE PROOF. Proves that once apps-engine-isolation.sql is
// applied, the restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is confined
// to its own tenant's DataConnection / AppSyncRun rows, sees nothing without a
// tenant context, and is blocked by WITH CHECK from writing cross-tenant. The
// global `App` catalog stays readable (no RLS).
//
// Runs ONLY when RLS_TEST_DATABASE_URL is set; otherwise skipped.
//
// Setup:
// docker run -d --name hg-rls-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16
// DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push
// RLS_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run rls-apps-engine
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const APP_ROLE = "hivegrid_app";
const APP_PASSWORD = "hivegrid_app_pw";
function appUrlFrom(adminUrl: string): string {
const url = new URL(adminUrl);
url.username = APP_ROLE;
url.password = APP_PASSWORD;
return url.toString();
}
const describeIfDb = ADMIN_URL ? describe : describe.skip;
describeIfDb("Apps-Engine RLS tenant isolation gate proof (DataConnection, AppSyncRun)", () => {
let admin: pg.Client;
let app: pg.Client;
beforeAll(async () => {
admin = new pg.Client({ connectionString: ADMIN_URL });
await admin.connect();
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8"));
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/apps-engine-isolation.sql"), "utf8"));
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
// Global App catalog (no tenant) + two tenants' connections + sync runs.
await admin.query(`INSERT INTO "App"(id,"updatedAt","key","title","category","connectionType") VALUES
('rls_app1',now(),'sample-data-sync','Sample','erp','rest_api') ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "DataConnection"(id,"updatedAt","tenantId","appId","label") VALUES
('rls_dcA',now(),'rls_tenantA','rls_app1','A'),
('rls_dcB',now(),'rls_tenantB','rls_app1','B') ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "AppSyncRun"(id,"updatedAt","tenantId","dataConnectionId") VALUES
('rls_runA',now(),'rls_tenantA','rls_dcA'),
('rls_runB',now(),'rls_tenantB','rls_dcB') ON CONFLICT (id) DO NOTHING`);
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
await app.connect();
});
afterAll(async () => {
await app?.end();
await admin?.end();
});
async function underTenant<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
await app.query("BEGIN");
try {
await app.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
const result = await run();
await app.query("COMMIT");
return result;
} catch (error) {
await app.query("ROLLBACK");
throw error;
}
}
it("confirms the app role is neither superuser nor BYPASSRLS", async () => {
const { rows } = await admin.query(`SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = $1`, [APP_ROLE]);
expect(rows[0]).toMatchObject({ rolsuper: false, rolbypassrls: false });
});
it("under tenant A, only tenant A connections are visible", async () => {
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "DataConnection" ORDER BY id`)).rows.map((r) => r.id));
expect(ids).toEqual(["rls_dcA"]);
});
it("sees no connections without a tenant context", async () => {
expect((await app.query(`SELECT count(*)::int AS c FROM "DataConnection"`)).rows[0].c).toBe(0);
});
it("WITH CHECK blocks inserting a connection for a foreign tenant", async () => {
await expect(
underTenant("rls_tenantA", async () =>
app.query(`INSERT INTO "DataConnection"(id,"updatedAt","tenantId","appId","label") VALUES ('rls_dcX',now(),'rls_tenantB','rls_app1','x')`),
),
).rejects.toThrow(/row-level security/i);
});
it("isolates AppSyncRun rows by tenant", async () => {
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "AppSyncRun" ORDER BY id`)).rows.map((r) => r.id));
expect(ids).toEqual(["rls_runA"]);
});
it("keeps the global App catalog readable under any tenant context", async () => {
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "App"`)).rows[0].c);
expect(count).toBeGreaterThanOrEqual(1);
});
});
@@ -0,0 +1,156 @@
// @vitest-environment node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
// Resolve the repo root from this file's location so the SQL artifacts load
// regardless of the cwd vitest runs under (root vs the @hivegrid/web package dir).
// This file lives at apps/web/app/utils/db/.server/ → six segments below root.
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
// VA-P23 — EMAIL-INBOX RLS GATE PROOF. Companion to rls-file-isolation: proves
// that once the email-inbox RLS block (prisma/rls/email-inbox-isolation.sql) is
// applied, the restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is
// confined to its own tenant's EmailIntegrationMailbox / -Message rows, sees
// nothing without a tenant context, and is blocked by WITH CHECK from writing
// cross-tenant rows. This makes the P5 activation a pure switch: the wrapped
// emailInbox db layer already runs inside withTenantRLS().
//
// Runs ONLY when RLS_TEST_DATABASE_URL is set (a SUPERUSER connection to a
// throwaway DB with the schema pushed). Without it the block is skipped so the
// normal unit suite stays green without a DB.
//
// Setup:
// docker run -d --name hg-rls-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16
// DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push
// RLS_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run rls-email-inbox-isolation
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const APP_ROLE = "hivegrid_app";
const APP_PASSWORD = "hivegrid_app_pw";
function appUrlFrom(adminUrl: string): string {
const url = new URL(adminUrl);
url.username = APP_ROLE;
url.password = APP_PASSWORD;
return url.toString();
}
const describeIfDb = ADMIN_URL ? describe : describe.skip;
describeIfDb("Email-inbox RLS tenant isolation gate proof (EmailIntegrationMailbox, EmailIntegrationMessage)", () => {
let admin: pg.Client;
let app: pg.Client;
beforeAll(async () => {
admin = new pg.Client({ connectionString: ADMIN_URL });
await admin.connect();
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
await admin.query(baseSql);
// 2) Email-inbox RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs
// on the four VA-P23 tables (the deferred P5 activation artifact).
const emailInboxRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/email-inbox-isolation.sql"), "utf8");
await admin.query(emailInboxRlsSql);
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
// 3) Seed two tenants' mailboxes + messages as superuser (bypasses RLS).
// Mailbox has no FK on tenantId/ownerUserId, so no User/Tenant rows needed.
await admin.query(`INSERT INTO "EmailIntegrationMailbox"(id,"updatedAt","tenantId","ownerUserId",provider,"emailAddress","externalAccountId") VALUES
('rls_mboxA',now(),'rls_tenantA','rls_userA','gmail','a@example.com','extA'),
('rls_mboxB',now(),'rls_tenantB','rls_userB','microsoft','b@example.com','extB')
ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt") VALUES
('rls_msgA',now(),'rls_tenantA','rls_mboxA','pmA','inbound','x@example.com',now()),
('rls_msgB',now(),'rls_tenantB','rls_mboxB','pmB','inbound','y@example.com',now())
ON CONFLICT (id) DO NOTHING`);
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
await app.connect();
});
afterAll(async () => {
await app?.end();
await admin?.end();
});
async function underTenant<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
await app.query("BEGIN");
try {
await app.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
const result = await run();
await app.query("COMMIT");
return result;
} catch (error) {
await app.query("ROLLBACK");
throw error;
}
}
it("confirms the app role is neither superuser nor BYPASSRLS", async () => {
const { rows } = await admin.query(`SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = $1`, [APP_ROLE]);
expect(rows[0]).toMatchObject({ rolsuper: false, rolbypassrls: false });
});
it("under tenant A context, only tenant A mailboxes are visible", async () => {
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationMailbox" ORDER BY id`)).rows.map((r) => r.id));
expect(ids).toEqual(["rls_mboxA"]);
});
it("cannot read another tenant's messages even with an explicit WHERE filter", async () => {
const count = await underTenant(
"rls_tenantA",
async () => (await app.query(`SELECT count(*)::int AS c FROM "EmailIntegrationMessage" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c,
);
expect(count).toBe(0);
});
it("sees no mailboxes at all when no tenant context is set", async () => {
const count = (await app.query(`SELECT count(*)::int AS c FROM "EmailIntegrationMailbox"`)).rows[0].c;
expect(count).toBe(0);
});
it("WITH CHECK blocks inserting a message for a foreign tenant", async () => {
await expect(
underTenant("rls_tenantA", async () =>
app.query(
`INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt")
VALUES ('rls_msgX',now(),'rls_tenantB','rls_mboxB','pmX','inbound','z@example.com',now())`,
),
),
).rejects.toThrow(/row-level security/i);
});
it("allows inserting and reading a message for the active tenant", async () => {
await underTenant("rls_tenantA", async () => {
await app.query(
`INSERT INTO "EmailIntegrationMessage"(id,"updatedAt","tenantId","mailboxId","providerMessageId",direction,"fromAddress","sentAt")
VALUES ('rls_msgA2',now(),'rls_tenantA','rls_mboxA','pmA2','outbound','a@example.com',now())
ON CONFLICT (id) DO NOTHING`,
);
const ids = (await app.query(`SELECT id FROM "EmailIntegrationMessage" ORDER BY id`)).rows.map((r) => r.id);
expect(ids).toContain("rls_msgA2");
expect(ids).not.toContain("rls_msgB");
});
});
it("isolates sync cursors and webhook events by tenant as well", async () => {
await admin.query(`INSERT INTO "EmailIntegrationSyncCursor"(id,"updatedAt","tenantId","mailboxId","externalFolderId") VALUES
('rls_curA',now(),'rls_tenantA','rls_mboxA','*'),
('rls_curB',now(),'rls_tenantB','rls_mboxB','inbox')
ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "EmailIntegrationWebhookEvent"(id,"tenantId","mailboxId",provider,"notificationPayload") VALUES
('rls_whA','rls_tenantA','rls_mboxA','gmail','{}'),
('rls_whB','rls_tenantB','rls_mboxB','microsoft','{}')
ON CONFLICT (id) DO NOTHING`);
const cursorIds = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationSyncCursor" ORDER BY id`)).rows.map((r) => r.id));
expect(cursorIds).toEqual(["rls_curA"]);
const eventIds = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmailIntegrationWebhookEvent" ORDER BY id`)).rows.map((r) => r.id));
expect(eventIds).toEqual(["rls_whA"]);
});
});
@@ -7,7 +7,7 @@ import pg from "pg";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
// Resolve the repo root from this file's location so the SQL artifacts load
// regardless of the cwd vitest runs under (root vs the @toolctrl/web package dir).
// regardless of the cwd vitest runs under (root vs the @hivegrid/web package dir).
// This file lives at apps/web/app/utils/db/.server/ → six segments below root.
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
@@ -0,0 +1,134 @@
// @vitest-environment node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
// Resolve the repo root from this file's location so the SQL artifacts load
// regardless of the cwd vitest runs under. This file lives at
// apps/web/app/utils/db/.server/ → six segments below root.
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
// AK-P17a — HR RLS GATE PROOF. Companion to the task/file/tenant isolation tests:
// proves that once the HR RLS block (prisma/rls/hr-isolation.sql) is applied, the
// restricted hivegrid_app role (NOSUPERUSER, NOBYPASSRLS) is confined to its own
// tenant's HR rows (here: HrEmployeeProfile + EmployeePasswordSafeEntry), sees
// nothing without a tenant context, and is blocked by WITH CHECK from writing
// cross-tenant rows. This is what makes the P5 activation a pure switch: the
// wrapped hr*Service helpers already set the GUC, so flipping RLS on cannot break
// the module.
//
// Runs ONLY when RLS_TEST_DATABASE_URL is set (a SUPERUSER connection to a
// throwaway DB with the schema pushed). Without it the block is skipped so the
// normal unit suite stays green without a DB.
//
// Setup:
// docker run -d --name hg-rls-pg -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=hivegrid -p 5433:5432 pgvector/pgvector:pg16
// DIRECT_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm exec prisma db push
// RLS_TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5433/hivegrid pnpm vitest run rls-hr-isolation
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const APP_ROLE = "hivegrid_app";
const APP_PASSWORD = "hivegrid_app_pw";
function appUrlFrom(adminUrl: string): string {
const url = new URL(adminUrl);
url.username = APP_ROLE;
url.password = APP_PASSWORD;
return url.toString();
}
const describeIfDb = ADMIN_URL ? describe : describe.skip;
describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePasswordSafeEntry)", () => {
let admin: pg.Client;
let app: pg.Client;
beforeAll(async () => {
admin = new pg.Client({ connectionString: ADMIN_URL });
await admin.connect();
// 1) Base RLS mechanic + restricted role (creates hivegrid_app, NOBYPASSRLS).
const baseSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8");
await admin.query(baseSql);
// 2) HR RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the HR
// tables (the deferred P5 activation artifact, applied here).
const hrRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/hr-isolation.sql"), "utf8");
await admin.query(hrRlsSql);
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
// 3) Seed two tenants' HR rows as superuser (bypasses RLS). The HR models use
// bare scalars (AD-21), so no User/Tenant rows are required. The vault is
// seeded for the FK from the entry.
await admin.query(`INSERT INTO "HrEmployeeProfile"(id,"updatedAt","tenantId","userId","position") VALUES
('rls_hrpA',now(),'rls_tenantA','rls_userA','Engineer'),
('rls_hrpB',now(),'rls_tenantB','rls_userB','Engineer')
ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "EmployeePasswordSafeVault"(id,"updatedAt","tenantId","name","createdByUserId") VALUES
('rls_vaultA',now(),'rls_tenantA','Vault A','rls_userA'),
('rls_vaultB',now(),'rls_tenantB','Vault B','rls_userB')
ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "EmployeePasswordSafeEntry"(id,"updatedAt","tenantId","vaultId","title") VALUES
('rls_entryA',now(),'rls_tenantA','rls_vaultA','Entry A'),
('rls_entryB',now(),'rls_tenantB','rls_vaultB','Entry B')
ON CONFLICT (id) DO NOTHING`);
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
await app.connect();
});
afterAll(async () => {
await app?.end();
await admin?.end();
});
async function underTenant<T>(tenantId: string, run: () => Promise<T>): Promise<T> {
await app.query("BEGIN");
try {
await app.query("SELECT set_config('app.tenant_id', $1, true)", [tenantId]);
const result = await run();
await app.query("COMMIT");
return result;
} catch (error) {
await app.query("ROLLBACK");
throw error;
}
}
it("confirms the app role is neither superuser nor BYPASSRLS", async () => {
const { rows } = await admin.query(`SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = $1`, [APP_ROLE]);
expect(rows[0]).toMatchObject({ rolsuper: false, rolbypassrls: false });
});
it("under tenant A context, only tenant A employee profiles are visible", async () => {
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "HrEmployeeProfile" ORDER BY id`)).rows.map((r) => r.id));
expect(ids).toEqual(["rls_hrpA"]);
});
it("cannot read another tenant's profile even with an explicit WHERE filter", async () => {
const count = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "HrEmployeeProfile" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
expect(count).toBe(0);
});
it("sees no HR rows at all when no tenant context is set", async () => {
const count = (await app.query(`SELECT count(*)::int AS c FROM "HrEmployeeProfile"`)).rows[0].c;
expect(count).toBe(0);
});
it("WITH CHECK blocks inserting a profile for a foreign tenant", async () => {
await expect(
underTenant("rls_tenantA", async () =>
app.query(`INSERT INTO "HrEmployeeProfile"(id,"updatedAt","tenantId","userId") VALUES ('rls_hrpX',now(),'rls_tenantB','rls_userB')`),
),
).rejects.toThrow(/row-level security/i);
});
it("isolates password-safe entries by tenant as well", async () => {
const ids = await underTenant("rls_tenantA", async () => (await app.query(`SELECT id FROM "EmployeePasswordSafeEntry" ORDER BY id`)).rows.map((r) => r.id));
expect(ids).toEqual(["rls_entryA"]);
const crossCount = await underTenant("rls_tenantA", async () => (await app.query(`SELECT count(*)::int AS c FROM "EmployeePasswordSafeEntry" WHERE "tenantId" = 'rls_tenantB'`)).rows[0].c);
expect(crossCount).toBe(0);
});
});
@@ -7,7 +7,7 @@ import pg from "pg";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
// Resolve the repo root from this file's location so the SQL artifacts load
// regardless of the cwd vitest runs under (root vs the @toolctrl/web package dir).
// regardless of the cwd vitest runs under (root vs the @hivegrid/web package dir).
// This file lives at apps/web/app/utils/db/.server/ → six segments below root.
const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../../..");
@@ -1,4 +1,4 @@
import type { Prisma } from "@toolctrl/db/prisma-browser";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { db } from "~/utils/db.server";
@@ -16,14 +16,14 @@ import {
type LegacyApiKeySimple,
type LegacyApiKeyWithDetails,
updateLegacyApiKey,
} from "@toolctrl/db/api-keys.server";
} from "@hivegrid/db/api-keys.server";
import { db } from "../db.server";
import { getClientIPAddress } from "~/utils/server/IpUtils";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import RowFiltersHelper from "../helpers/RowFiltersHelper";
import { cachified, clearCacheKey } from "../cache.server";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
export type ApiKeyWithDetails = LegacyApiKeyWithDetails;
@@ -177,23 +177,14 @@ export async function getFirstApiKey(tenantId: string | null) {
return findFirstLegacyActiveApiKey(tenantId);
}
export async function createApiKey(
data: {
tenantId: string;
createdByUserId: string;
alias: string;
expires: Date | null;
active: boolean;
},
entities: {
entityId: string;
create: boolean;
read: boolean;
update: boolean;
delete: boolean;
}[]
) {
return createLegacyApiKey(data, entities, undefined, getApiKeyHashSecret());
export async function createApiKey(data: {
tenantId: string;
createdByUserId: string;
alias: string;
expires: Date | null;
active: boolean;
}) {
return createLegacyApiKey(data, undefined, getApiKeyHashSecret());
}
export async function createApiKeyLog(
@@ -229,16 +220,9 @@ export async function updateApiKey(
alias: string;
expires: Date | null;
active: boolean;
},
entities: {
entityId: string;
create: boolean;
read: boolean;
update: boolean;
delete: boolean;
}[]
}
) {
const apiKey = await updateLegacyApiKey(id, data, entities);
const apiKey = await updateLegacyApiKey(id, data);
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
return apiKey;
}
@@ -7,7 +7,7 @@ const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url
describe("appConfiguration web config adoption", () => {
test("uses loadRequiredWebConfig instead of direct web env reads for public config fields", () => {
expect(source).toContain('import { loadRequiredWebConfig } from "@toolctrl/config"');
expect(source).toContain('import { loadRequiredWebConfig } from "@hivegrid/config"');
expect(source).toContain("const webConfig = loadRequiredWebConfig()");
expect(source).toContain("instanceUrl: webConfig.captcha.instanceUrl ?? \"\"");
expect(source).toContain("const authProviders = getPublicAuthProviders({ request, webConfig })");
@@ -1,6 +1,6 @@
import { defaultBrandTokens } from "@toolctrl/brand";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { Prisma } from "@toolctrl/db/prisma-browser";
import { defaultBrandTokens } from "@hivegrid/brand";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { Prisma } from "@hivegrid/db/prisma-browser";
import { getTranslations } from "~/locale/i18next.server";
import { getPublicAuthProviders } from "../auth/authProviders.server";
import { cachified, clearCacheKey } from "../cache.server";
@@ -41,6 +41,7 @@ export type AppConfiguration = {
slug: { require: boolean; type: "tenant" | "username" } | null;
captcha: {
enabled: boolean;
provider: "mcaptcha" | "cap";
instanceUrl: string;
loginSiteKey: string;
};
@@ -139,6 +140,7 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
slug: { require: false, type: "username" },
captcha: {
enabled: Boolean(webConfig.captcha.instanceUrl && webConfig.captcha.loginSiteKey),
provider: webConfig.captcha.provider,
instanceUrl: webConfig.captcha.instanceUrl ?? "",
loginSiteKey: webConfig.captcha.loginSiteKey ?? "",
},
@@ -220,7 +222,7 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
conf.auth.requireEmailVerification = appConfiguration?.authRequireEmailVerification;
conf.auth.requireOrganization = appConfiguration?.authRequireOrganization;
conf.auth.requireName = appConfiguration?.authRequireName;
// Captcha (mCaptcha) is env-driven (MCAPTCHA_*), not stored per-tenant in the DB.
// Captcha is env-driven, not stored per-tenant in the DB.
// `conf.auth.captcha` is already populated from webConfig in the default builder.
conf.analytics.enabled = appConfiguration?.analyticsEnabled;
@@ -1,7 +1,7 @@
import { JsonPropertyDto } from "~/modules/jsonProperties/dtos/JsonPropertyTypeDto";
import { TFunction } from "i18next";
import { JsonPropertiesValuesDto } from "~/modules/jsonProperties/dtos/JsonPropertiesValuesDto";
import { Portal } from "@toolctrl/db/prisma-browser";
import { Portal } from "@hivegrid/db/prisma-browser";
export type PortalConfiguration = {
enabled: boolean;
@@ -98,8 +98,8 @@ export function getAppPortalConfiguration({ t }: { t: TFunction }): PortalConfig
properties: [titleProperty, descriptionProperty, ...seoProperties],
errors: (params) => {
let errors: string[] = [];
if (!params.portal.stripeAccountId) {
errors.push(t("models.portal.pages.errors.stripeAccountMissing"));
if (!params.portal.paymentProviderAccountId) {
errors.push(t("models.portal.pages.errors.paymentAccountMissing"));
}
return errors;
},
@@ -1,4 +1,4 @@
import { Blacklist } from "@toolctrl/db/prisma-browser";
import { Blacklist } from "@hivegrid/db/prisma-browser";
import Constants from "~/application/Constants";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
@@ -1,800 +0,0 @@
import { Entity, EntityRelationship, EntityTag, EntityTemplate, Prisma, Property, PropertyAttribute, PropertyOption } from "@toolctrl/db/prisma-browser";
import Constants from "~/application/Constants";
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility";
import { defaultProperties } from "~/utils/helpers/PropertyHelper";
import { db } from "../../db.server";
import { EntityRelationshipWithDetails } from "./entityRelationships.db.server";
import { EntityViewWithDetails } from "./entityViews.db.server";
import { createProperties, CreatePropertyDto } from "./properties.db.server";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
import EntitiesSingleton from "~/modules/rows/repositories/EntitiesSingleton";
export type EntitySimple = {
id: string;
order: number;
name: string;
title: string;
titlePlural: string;
active: boolean;
slug: string;
type: string;
hasApi: boolean;
showInSidebar: boolean;
icon: string;
onEdit: string | null;
};
export type RowsUsage = { entityId: string; _count: number };
export type EntityWithProperties = Entity & {
properties: PropertyWithDetails[];
};
export type EntityWithDetails = Entity & {
properties: PropertyWithDetails[];
views: EntityViewWithDetails[];
tags: EntityTag[];
parentEntities: EntityRelationshipWithDetails[];
childEntities: EntityRelationshipWithDetails[];
templates: EntityTemplate[];
};
export type EntityWithDetailsAndRelationships = EntityWithDetails & {
parentEntities: (EntityRelationship & { parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null } })[];
childEntities: (EntityRelationship & { parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null } })[];
};
export type EntityWithCount = EntityWithDetails & {
_count: { rows: number };
};
export type PropertyWithDetails = Property & {
// entity: EntityWithDetails;
attributes: PropertyAttribute[];
options: PropertyOption[];
parent?: PropertyWithDetails;
formula: { name: string; resultAs: string; calculationTrigger: string } | null;
};
// const includeEntityWithDetails = {
// properties: {
// include: {
// options: true,
// },
// },
// };
export async function getEntitiesInIds(ids: string[]) {
return await db.entity.findMany({
where: { id: { in: ids } },
});
}
export async function getAllEntities({
tenantId,
active,
types,
}: {
tenantId: string | null | undefined;
active?: boolean;
types?: string[];
}): Promise<EntityWithDetails[]> {
let where: Prisma.EntityWhereInput = {};
if (active) {
where = { active };
}
if (types) {
where = { ...where, type: { in: types } };
}
const allEntities = await db.entity.findMany({
where,
orderBy: [
{ type: "asc" },
{
order: "asc",
},
],
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
EntitiesSingleton.getInstance().setEntities(allEntities);
return allEntities;
}
export async function getAllEntitiesSimple({ active, types }: { active?: boolean; types?: string[] } = {}): Promise<EntitySimple[]> {
let where: Prisma.EntityWhereInput = {};
if (active) {
where = { active };
}
if (types) {
where = { ...where, type: { in: types } };
}
return await db.entity.findMany({
where,
orderBy: [
{ type: "asc" },
{
order: "asc",
},
],
select: EntityModelHelper.selectSimpleProperties,
});
}
export async function getEntitySimple({ id, name }: { id?: string; name?: string }): Promise<EntitySimple | null> {
if (!id && !name) {
return null;
} else if (id) {
return await db.entity.findUnique({
where: {
id,
},
select: EntityModelHelper.selectSimpleProperties,
});
} else {
return await db.entity.findUnique({
where: {
name,
},
select: EntityModelHelper.selectSimpleProperties,
});
}
}
export async function getEntitiesByName(name: string[]) {
return await db.entity.findMany({
where: {
name: {
in: name,
},
},
});
}
export async function getAllEntitiesWithRowCount({ tenantId }: { tenantId: string | null }): Promise<EntityWithCount[]> {
return await db.entity.findMany({
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
templates: {
where: { ...filterTenantId(tenantId) },
},
_count: {
select: {
rows: true,
},
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
},
orderBy: [
{ type: "asc" },
{
order: "asc",
},
],
});
}
export async function getAllRowsUsage(tenantId: string): Promise<RowsUsage[]> {
const countEntities = await db.row.groupBy({
by: ["entityId"],
_count: true,
where: {
OR: [
{
tenantId,
},
],
},
});
return countEntities;
}
export async function getEntityById({ id, tenantId }: { id: string; tenantId: string | null | undefined }): Promise<EntityWithDetailsAndRelationships | null> {
return await db.entity.findUnique({
where: {
id,
},
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
}
export async function getEntityBySlug({
tenantId,
slug,
activeOnly,
}: {
tenantId: string | null;
slug: string;
activeOnly?: boolean;
}): Promise<EntityWithDetails> {
const entity = await db.entity.findUnique({
where: {
slug,
},
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
attributes: true,
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
if (!entity) {
throw new Error(`Entity '${slug}' not found`);
}
if (activeOnly && !entity.active) {
throw new Error(`Entity '${slug}' is not active`);
}
return entity;
}
export async function getSimpleEntityBySlug(slug: string): Promise<EntitySimple | null> {
return await db.entity.findUnique({
where: {
slug,
},
select: EntityModelHelper.selectSimpleProperties,
});
}
export async function findEntityBySlug(slug: string): Promise<Entity | null> {
return await db.entity.findUnique({
where: { slug },
});
}
export async function getEntityByName({ tenantId, name }: { tenantId: string | null | undefined; name: string }): Promise<EntityWithDetails> {
const entity = await db.entity.findUnique({
where: {
name,
},
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
if (!entity) {
throw new Error(`Entity with name ${name} not found`);
}
return entity;
}
export async function getEntityByIdOrName({
tenantId,
id,
name,
}: {
tenantId: string | null | undefined;
id?: string;
name?: string;
}): Promise<EntityWithDetails> {
let entity: EntityWithDetails | null = null;
if (id) {
entity = await getEntityById({ tenantId, id });
} else if (name) {
entity = await getEntityByName({ tenantId, name });
}
if (!entity) {
throw new Error(`Entity with id ${id} or name ${name} not found`);
}
return entity;
}
export async function getEntityByIdNameOrSlug({ tenantId, idNameOrSlug }: { tenantId: string | null; idNameOrSlug: string }): Promise<EntityWithDetails> {
return getEntityWithWhere({
tenantId,
where: {
OR: [{ id: idNameOrSlug }, { name: idNameOrSlug }, { slug: idNameOrSlug }],
},
});
}
async function getEntityWithWhere({ tenantId, where }: { tenantId: string | null; where: Prisma.EntityWhereInput }) {
const entity = await db.entity.findFirst({
where,
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
if (!entity) {
throw new Error(`Entity not found`);
}
return entity;
}
export async function findEntityByName({ tenantId, name }: { tenantId: string | null; name: string }): Promise<EntityWithDetails | null> {
return await db.entity.findUnique({
where: { name },
include: {
views: { where: { ...filterTenantId(tenantId) }, include: { properties: true, filters: true, sort: true, groupByProperty: true } },
tags: true,
parentEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
childEntities: {
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
parentEntityView: { where: { ...filterTenantId(tenantId) }, include: EntityViewModelHelper.includeDetails },
},
orderBy: { order: "asc" },
},
properties: {
where: { ...filterTenantId(tenantId) },
orderBy: { order: "asc" },
include: {
// entity: {
// include: {
// ...includePropertiesWithDetails,
// },
// },
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: { select: { name: true, resultAs: true, calculationTrigger: true } },
},
},
templates: {
where: { ...filterTenantId(tenantId) },
},
},
});
}
export async function findSimpleEntityByName(name: string): Promise<{ id: string; title: string; titlePlural: string; slug: string } | null> {
if (EntitiesSingleton.getInstance().isSet()) {
return (
EntitiesSingleton.getInstance()
.getEntities()
.find((f) => f.name === name) ?? null
);
}
return await db.entity.findUnique({
where: { name },
select: { id: true, title: true, titlePlural: true, slug: true },
});
}
export async function getEntityByPrefix(prefix: string): Promise<Entity | null> {
return await db.entity.findUnique({
where: {
prefix,
},
});
}
export async function createEntity(
data: {
name: string;
slug: string;
prefix: string;
title: string;
titlePlural: string;
isAutogenerated: boolean;
type: string;
hasApi: boolean;
icon: string;
active: boolean;
showInSidebar: boolean;
hasTags: boolean;
hasComments: boolean;
hasTasks: boolean;
hasActivity: boolean;
hasBulkDelete: boolean;
hasViews: boolean;
defaultVisibility: string;
onCreated: string | null;
onEdit: string | null;
},
order?: number | null
) {
if (!order) {
order = (await getMaxEntityOrder()) + 1;
}
const entity = await db.entity.create({
data: {
...data,
order,
},
});
const webhooks = [
{
action: DefaultLogActions.Created,
method: "POST",
endpoint: "",
},
{
action: DefaultLogActions.Updated,
method: "POST",
endpoint: "",
},
{
action: DefaultLogActions.Created,
method: "POST",
endpoint: "",
},
];
await Promise.all(
webhooks.map(async (webhook) => {
return await db.entityWebhook.create({
data: {
entityId: entity.id,
action: webhook.action,
method: webhook.method,
endpoint: webhook.endpoint,
},
});
})
);
await Promise.all(
defaultProperties.map(async (property) => {
return await db.property.create({
data: {
entityId: entity.id,
...property,
},
});
})
);
return entity;
}
export async function createCoreEntity(
data: {
name: string;
slug: string;
title: string;
titlePlural: string;
prefix: string;
type: string;
isAutogenerated?: boolean;
hasApi?: boolean;
icon?: string;
active?: boolean;
showInSidebar?: boolean;
hasTags?: boolean;
hasComments?: boolean;
hasTasks?: boolean;
hasActivity?: boolean;
hasBulkDelete?: boolean;
hasViews?: boolean;
defaultVisibility?: DefaultVisibility;
onCreated?: string | null;
onEdit?: string | null;
},
properties?: CreatePropertyDto[]
) {
const entity = await createEntity({
name: data.name,
slug: data.slug,
prefix: data.prefix,
title: data.title,
titlePlural: data.titlePlural,
type: data.type,
isAutogenerated: data.isAutogenerated !== undefined ? data.isAutogenerated : true,
hasApi: data.hasApi !== undefined ? data.hasApi : true,
icon: data.icon !== undefined ? data.icon : "",
active: data.active !== undefined ? data.active : true,
showInSidebar: data.showInSidebar !== undefined ? data.showInSidebar : true,
hasTags: data.hasTags !== undefined ? data.hasTags : true,
hasComments: data.hasComments !== undefined ? data.hasComments : true,
hasTasks: data.hasTasks !== undefined ? data.hasTasks : false,
hasActivity: data.hasActivity !== undefined ? data.hasActivity : true,
hasBulkDelete: data.hasBulkDelete !== undefined ? data.hasBulkDelete : false,
hasViews: data.hasViews !== undefined ? data.hasViews : true,
defaultVisibility: data.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY,
onCreated: data.onCreated ?? "redirectToOverview",
onEdit: data.onEdit ?? "editRoute",
});
if (properties) {
await createProperties(entity.id, properties);
}
return entity;
}
export async function updateEntity(
id: string,
data: {
name?: string;
slug?: string;
order?: number;
prefix?: string;
title?: string;
titlePlural?: string;
isAutogenerated?: boolean;
type?: string;
hasApi?: boolean;
icon?: string;
active?: boolean;
showInSidebar?: boolean;
hasTags?: boolean;
hasComments?: boolean;
hasTasks?: boolean;
hasActivity?: boolean;
hasBulkDelete?: boolean;
hasViews?: boolean;
defaultVisibility?: string;
onCreated?: string | null;
onEdit?: string | null;
}
) {
return await db.entity.update({
where: {
id,
},
data,
});
}
export async function deleteEntity(id: string) {
return await db.entity.delete({
where: {
id,
},
});
}
export default async function getMaxEntityOrder(): Promise<number> {
return (
(
await db.entity.aggregate({
_max: {
order: true,
},
})
)._max?.order ?? 0
);
}
export async function getDefaultEntityVisibility(id: string): Promise<DefaultVisibility> {
return ((
await db.entity.findUnique({
where: { id },
select: {
defaultVisibility: true,
},
})
)?.defaultVisibility ?? Constants.DEFAULT_ROW_VISIBILITY) as DefaultVisibility;
}
function filterTenantId(tenantId: string | null | undefined) {
const filter: { tenantId?: string | null; OR?: { tenantId?: string | null }[] } = {};
if (tenantId === undefined) {
return filter;
} else if (tenantId === null) {
filter.tenantId = null;
} else {
filter.OR = [{ tenantId: null }, { tenantId }];
}
return filter;
}
@@ -1,137 +0,0 @@
import { EntityGroup, EntityGroupEntity, Prisma } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { EntitySimple } from "./entities.db.server";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
import { EntityViewWithDetails } from "./entityViews.db.server";
export type EntityGroupWithDetails = EntityGroup & {
entities: EntityGroupEntityWithDetails[];
};
export type EntityGroupEntityWithDetails = EntityGroupEntity & {
entity: EntitySimple;
allView: EntityViewWithDetails | null;
};
export async function getAllEntityGroups(): Promise<EntityGroupWithDetails[]> {
return db.entityGroup.findMany({
include: {
entities: {
include: {
entity: { select: EntityModelHelper.selectSimpleProperties },
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
},
orderBy: { entity: { order: "asc" } },
},
},
orderBy: { order: "asc" },
});
}
export async function getEntityGroup(id: string): Promise<EntityGroupWithDetails | null> {
return db.entityGroup.findUnique({
where: { id },
include: {
entities: {
include: {
entity: { select: EntityModelHelper.selectSimpleProperties },
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
},
orderBy: { entity: { order: "asc" } },
},
},
});
}
export async function getEntityGroupBySlug(slug: string): Promise<EntityGroupWithDetails | null> {
return db.entityGroup.findUnique({
where: { slug },
include: {
entities: {
include: {
entity: { select: EntityModelHelper.selectSimpleProperties },
allView: { include: { properties: true, filters: true, sort: true, groupByProperty: true } },
},
orderBy: { entity: { order: "asc" } },
},
},
});
}
export async function createEntityGroup(data: {
order: number;
slug: string;
title: string;
icon: string;
collapsible: boolean;
section: string | null;
entities: {
entityId: string;
allViewId: string | null;
}[];
}): Promise<EntityGroup> {
return db.entityGroup.create({
data: {
order: data.order,
slug: data.slug,
title: data.title,
icon: data.icon,
collapsible: data.collapsible,
section: data.section,
entities: {
create: data.entities.map((f) => {
return {
entityId: f.entityId,
allViewId: f.allViewId,
};
}),
},
},
});
}
export async function updateEntityGroup(
id: string,
data: {
order?: number;
slug?: string;
title?: string;
icon?: string;
collapsible?: boolean;
section?: string | null;
entities?: {
entityId: string;
allViewId: string | null;
}[];
}
): Promise<EntityGroup> {
let update: Prisma.EntityGroupUpdateInput = {
order: data.order,
slug: data.slug,
title: data.title,
icon: data.icon,
collapsible: data.collapsible,
section: data.section,
};
if (data.entities) {
update.entities = {
deleteMany: {},
create: data.entities.map((f) => {
return {
entityId: f.entityId,
allViewId: f.allViewId,
};
}),
};
}
return db.entityGroup.update({
where: { id },
data: update,
});
}
export async function deleteEntityGroup(id: string): Promise<EntityGroup> {
return db.entityGroup.delete({
where: { id },
});
}
@@ -1,258 +0,0 @@
import { EntityRelationship } from "@toolctrl/db/prisma-browser";
import { db } from "../../db.server";
import { EntityViewWithDetails } from "./entityViews.db.server";
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
export type EntityRelationshipWithDetails = EntityRelationship & {
parent: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
child: { id: string; name: string; title: string; titlePlural: string; slug: string; onEdit: string | null };
childEntityView: EntityViewWithDetails | null;
parentEntityView: EntityViewWithDetails | null;
};
export type EntityRelationshipWithCount = EntityRelationshipWithDetails & {
_count: { rows: number };
};
export async function getAllEntityRelationships(): Promise<EntityRelationshipWithDetails[]> {
return await db.entityRelationship.findMany({
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
},
});
}
export async function findEntityRelationship({
parentId,
childId,
title,
notIn,
}: {
parentId: string;
childId: string;
title: string | null;
notIn?: string[];
}): Promise<EntityRelationshipWithCount | null> {
return await db.entityRelationship.findFirst({
where: {
OR: [
{ parentId, childId },
{ parentId: childId, childId: parentId },
],
title,
id: {
notIn,
},
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
});
}
export async function getEntityRelationships(entityId: string): Promise<EntityRelationshipWithDetails[]> {
return await db.entityRelationship.findMany({
where: {
OR: [
{
parentId: entityId,
},
{
childId: entityId,
},
],
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
},
orderBy: [{ order: "asc" }],
});
}
export async function getEntityRelationshipsWithCount(entityId: string): Promise<EntityRelationshipWithCount[]> {
return await db.entityRelationship.findMany({
where: {
OR: [{ parentId: entityId }, { childId: entityId }],
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
orderBy: [{ order: "asc" }],
});
}
export async function getEntitiesRelationship({
parentEntityId,
childEntityId,
}: {
parentEntityId: string;
childEntityId: string;
}): Promise<EntityRelationshipWithDetails | null> {
return await db.entityRelationship.findFirst({
where: {
parentId: parentEntityId,
childId: childEntityId,
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
},
orderBy: [{ order: "asc" }],
});
}
export async function getEntityRelationship(id: string): Promise<EntityRelationshipWithCount | null> {
return await db.entityRelationship.findUnique({
where: {
id,
},
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
});
}
type EntityRelationshipScope = {
id: string;
entityId: string;
};
function relationshipScopeWhere(scope: EntityRelationshipScope) {
return {
id: scope.id,
OR: [{ parentId: scope.entityId }, { childId: scope.entityId }],
};
}
export async function getScopedEntityRelationship(scope: EntityRelationshipScope): Promise<EntityRelationshipWithCount | null> {
return await db.entityRelationship.findFirst({
where: relationshipScopeWhere(scope),
include: {
parent: { select: EntityModelHelper.selectEntityWithoutIcon },
child: { select: EntityModelHelper.selectEntityWithoutIcon },
childEntityView: { include: EntityViewModelHelper.includeDetails },
parentEntityView: { include: EntityViewModelHelper.includeDetails },
_count: true,
},
});
}
export async function createEntityRelationship({
parentId,
childId,
order,
title,
type,
required,
cascade,
readOnly,
hiddenIfEmpty,
childEntityViewId,
parentEntityViewId,
}: {
parentId: string;
childId: string;
order: number;
title: string | null;
type: string;
required: boolean;
cascade: boolean;
readOnly: boolean;
hiddenIfEmpty: boolean;
childEntityViewId: string | null;
parentEntityViewId: string | null;
}) {
return await db.entityRelationship.create({
data: {
parentId,
childId,
order,
title,
type,
required,
cascade,
readOnly,
hiddenIfEmpty,
childEntityViewId,
parentEntityViewId,
},
});
}
export async function updateEntityRelationship(
id: string,
data: {
parentId?: string;
childId?: string;
order?: number;
title?: string | null;
type?: string;
required?: boolean;
cascade?: boolean;
readOnly?: boolean;
hiddenIfEmpty?: boolean;
childEntityViewId?: string | null;
parentEntityViewId?: string | null;
}
) {
return await db.entityRelationship.update({
where: {
id,
},
data: {
...data,
},
});
}
type UpdateEntityRelationshipData = Parameters<typeof updateEntityRelationship>[1];
export async function updateScopedEntityRelationship(scope: EntityRelationshipScope, data: UpdateEntityRelationshipData) {
const result = await db.entityRelationship.updateMany({
where: relationshipScopeWhere(scope),
data: {
...data,
},
});
if (result.count !== 1) {
throw Error("Relationship not found");
}
return await getScopedEntityRelationship(scope);
}
export async function deleteEntityRelationship(id: string) {
return await db.entityRelationship.delete({
where: {
id,
},
});
}
export async function deleteScopedEntityRelationship(scope: EntityRelationshipScope) {
const result = await db.entityRelationship.deleteMany({
where: relationshipScopeWhere(scope),
});
if (result.count !== 1) {
throw Error("Relationship not found");
}
}
@@ -1,47 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db.server", () => ({
db: {
entityTag: {
findFirst: vi.fn(),
findUnique: vi.fn(),
updateMany: vi.fn(),
deleteMany: vi.fn(),
},
},
}));
import { db } from "~/utils/db.server";
import { deleteEntityTag, getEntityTagById, updateEntityTag } from "./entityTags.db.server";
const entityTagMock = vi.mocked(db.entityTag, true);
describe("entity tag tenant boundary helpers", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("can resolve tags by id within an entity scope", async () => {
const tag = { id: "tag_1", entityId: "entity_1", value: "Warm", color: 3, createdAt: new Date("2026-01-01T00:00:00.000Z") };
entityTagMock.findFirst.mockResolvedValueOnce(tag);
await expect(getEntityTagById("tag_1", "entity_1")).resolves.toEqual(tag);
expect(entityTagMock.findFirst).toHaveBeenCalledWith({ where: { id: "tag_1", entityId: "entity_1" } });
expect(entityTagMock.findUnique).not.toHaveBeenCalled();
});
it("updates and deletes tags with id and entity scope", async () => {
entityTagMock.updateMany.mockResolvedValueOnce({ count: 1 });
entityTagMock.deleteMany.mockResolvedValueOnce({ count: 1 });
await updateEntityTag({ id: "tag_1", entityId: "entity_1" }, { value: "Warm", color: 3 });
await deleteEntityTag({ id: "tag_1", entityId: "entity_1" });
expect(entityTagMock.updateMany).toHaveBeenCalledWith({
where: { id: "tag_1", entityId: "entity_1" },
data: { value: "Warm", color: 3 },
});
expect(entityTagMock.deleteMany).toHaveBeenCalledWith({ where: { id: "tag_1", entityId: "entity_1" } });
});
});
@@ -1,65 +0,0 @@
import { EntityTag } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
export async function getEntityTags(entityId: string): Promise<EntityTag[]> {
return await db.entityTag.findMany({
where: {
entityId,
},
});
}
export async function getEntityTagById(id: string, entityId?: string): Promise<EntityTag | null> {
if (entityId) {
return await db.entityTag.findFirst({
where: {
id,
entityId,
},
});
}
return await db.entityTag.findUnique({ where: { id } });
}
export async function getEntityTag(entityId: string, value: string): Promise<EntityTag | null> {
return await db.entityTag.findFirst({
where: {
entityId,
value,
},
});
}
export async function getEntityTagByEntityName(entityName: string, value: string): Promise<EntityTag | null> {
return await db.entityTag.findFirst({
where: {
entity: { name: entityName },
value,
},
});
}
export async function createEntityTag(data: { entityId: string; color: number; value: string }) {
return await db.entityTag.create({
data,
});
}
export async function updateEntityTag({ id, entityId }: { id: string; entityId: string }, data: { color?: number; value?: string }) {
return await db.entityTag.updateMany({
where: {
id,
entityId,
},
data,
});
}
export async function deleteEntityTag({ id, entityId }: { id: string; entityId: string }) {
return await db.entityTag.deleteMany({
where: {
id,
entityId,
},
});
}
@@ -1,70 +0,0 @@
import { db } from "~/utils/db.server";
export async function getEntityTemplates(entityId: string, { tenantId }: { tenantId: string | null }) {
return await db.entityTemplate.findMany({
where: { entityId, tenantId },
orderBy: { entity: { order: "asc" } },
});
}
type EntityTemplateScope = {
id: string;
tenantId: string | null;
entityId: string;
};
export async function getEntityTemplate(id: string, { tenantId, entityId }: { tenantId: string | null; entityId?: string }) {
return await db.entityTemplate
.findFirstOrThrow({
where: { id, tenantId, ...(entityId ? { entityId } : {}) },
})
.catch(() => {
return null;
});
}
export async function createEntityTemplate(data: { tenantId: string | null; entityId: string; title: string; config: string }) {
return await db.entityTemplate.create({
data: {
tenantId: data.tenantId,
entityId: data.entityId,
title: data.title,
config: data.config,
},
});
}
export async function updateEntityTemplate(id: string, data: { title: string; config: string }) {
return await db.entityTemplate.update({
where: {
id,
},
data,
});
}
export async function updateScopedEntityTemplate(scope: EntityTemplateScope, data: { title: string; config: string }) {
const result = await db.entityTemplate.updateMany({
where: scope,
data,
});
if (result.count !== 1) {
throw Error("Entity template not found");
}
return await getEntityTemplate(scope.id, { tenantId: scope.tenantId, entityId: scope.entityId });
}
export async function deleteEntityTemplate(id: string) {
return await db.entityTemplate.delete({
where: { id },
});
}
export async function deleteScopedEntityTemplate(scope: EntityTemplateScope) {
const result = await db.entityTemplate.deleteMany({
where: scope,
});
if (result.count !== 1) {
throw Error("Entity template not found");
}
}
@@ -1,19 +0,0 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "entityViews.db.server.ts"), "utf8");
describe("entity views db wrapper", () => {
test("does not include tenant user-private views unless a user id is explicit", () => {
expect(source).toContain("const userId = options.userId ?? null");
expect(source).toContain("if (userId) {\n scope.unshift({ tenantId: options.tenantId, userId });\n }");
});
test("supports scoped entity-view lookup by id", () => {
expect(source).toContain("entityId: options?.entityId");
expect(source).toContain("...buildEntityViewScopeWhere({ tenantId: options?.tenantId, userId: options?.userId })");
});
});
@@ -1,422 +0,0 @@
import { EntityView, EntityViewFilter, EntityViewProperty, EntityViewSort, Prisma, Property } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
import TenantModelHelper from "~/utils/helpers/models/TenantModelHelper";
import { TenantSimple } from "../tenants.db.server";
import EntityModelHelper from "~/utils/helpers/models/EntityModelHelper";
import { EntitySimple } from "./entities.db.server";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import EntityViewModelHelper from "~/utils/helpers/models/EntityViewModelHelper";
export type EntityViewWithDetails = EntityView & {
properties: EntityViewProperty[];
filters: EntityViewFilter[];
sort: EntityViewSort[];
groupByProperty: Property | null;
};
export type EntityViewWithTenantAndUser = EntityViewWithDetails & {
entity: EntitySimple;
createdByUser: UserSimple | null;
tenant: TenantSimple | null;
user: UserSimple | null;
};
export async function getAllEntityViews({
type,
entityId,
pagination,
filters,
}: {
type?: string;
entityId?: string;
pagination?: { pageSize: number; page: number };
filters?: FiltersDto;
}): Promise<{ items: EntityViewWithTenantAndUser[]; total: number }> {
let where: Prisma.EntityViewWhereInput = {
entityId,
};
if (type === "default") {
where = { tenantId: null, userId: null, isSystem: false };
} else if (type === "tenant") {
where = { tenantId: { not: null }, userId: null, isSystem: false };
} else if (type === "user") {
where = { userId: { not: null }, isSystem: false };
} else if (type === "system") {
where = { isSystem: true };
}
const filterEntityId = filters?.properties.find((filter) => filter.name === "entityId")?.value;
const filterTenantId = filters?.properties.find((filter) => filter.name === "tenantId")?.value;
const filterUserId = filters?.properties.find((filter) => filter.name === "userId")?.value;
if (filterEntityId) {
where = { ...where, entityId: filterEntityId };
}
if (filterTenantId) {
where = { ...where, tenantId: filterTenantId };
}
if (filterUserId) {
where = { ...where, userId: filterUserId };
}
const items = await db.entityView.findMany({
take: pagination?.pageSize,
skip: pagination ? pagination.pageSize * (pagination.page - 1) : undefined,
where,
include: {
...EntityViewModelHelper.includeDetails,
entity: { select: EntityModelHelper.selectSimpleProperties },
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
user: { select: UserModelHelper.selectSimpleUserProperties },
},
orderBy: [{ tenantId: "asc" }, { userId: "asc" }, { order: "asc" }],
});
const total = await db.entityView.count({ where });
return {
items,
total,
};
}
export async function getEntityViews(
entityId: string,
options?: {
tenantId?: string | null;
userId?: string | null;
}
): Promise<EntityViewWithDetails[]> {
let where: Prisma.EntityViewWhereInput = {
entityId,
isSystem: false,
};
if (options?.tenantId !== undefined) {
const userId = options.userId ?? null;
const scope: Prisma.EntityViewWhereInput[] = [{ tenantId: options.tenantId, userId: null }, { tenantId: null, userId: null }];
if (userId) {
scope.unshift({ tenantId: options.tenantId, userId });
}
where = {
...where,
OR: scope,
};
}
return await db.entityView.findMany({
where,
include: EntityViewModelHelper.includeDetails,
orderBy: {
order: "asc",
},
});
}
function buildEntityViewScopeWhere({
tenantId,
userId,
}: {
tenantId?: string | null;
userId?: string | null;
}): Prisma.EntityViewWhereInput {
if (tenantId === undefined) {
return {};
}
return {
OR: [
{ tenantId, userId },
{ tenantId, userId: null },
{ tenantId: null, userId: null },
],
};
}
export async function getEntityView(
id: string,
options?: {
entityId?: string;
tenantId?: string | null;
userId?: string | null;
}
): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
id,
entityId: options?.entityId,
...buildEntityViewScopeWhere({ tenantId: options?.tenantId, userId: options?.userId }),
},
include: EntityViewModelHelper.includeDetails,
});
}
export async function getEntityViewWithTenantAndUser(id: string): Promise<EntityViewWithTenantAndUser | null> {
return await db.entityView.findUnique({
where: {
id,
},
include: {
...EntityViewModelHelper.includeDetails,
entity: { select: EntityModelHelper.selectSimpleProperties },
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
tenant: { select: TenantModelHelper.selectSimpleTenantProperties },
user: { select: UserModelHelper.selectSimpleUserProperties },
},
});
}
export async function getEntityViewByName({
entityId,
name,
isSystem,
tenantId,
userId,
}: {
entityId: string;
name: string;
isSystem?: boolean;
tenantId?: string | null;
userId?: string | null;
}): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
entityId,
name,
isSystem,
...buildEntityViewScopeWhere({ tenantId, userId }),
},
include: EntityViewModelHelper.includeDetails,
});
}
export async function getEntityViewDefault({
entityId,
isSystem,
tenantId,
userId,
}: {
entityId: string;
isSystem?: boolean;
tenantId?: string | null;
userId?: string | null;
}): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
entityId,
isSystem,
isDefault: true,
...buildEntityViewScopeWhere({ tenantId, userId }),
},
include: EntityViewModelHelper.includeDetails,
});
}
export async function getEntityViewByOrder(entityId: string, order: number): Promise<EntityViewWithDetails | null> {
return await db.entityView.findFirst({
where: {
entityId,
order,
},
include: EntityViewModelHelper.includeDetails,
});
}
export default async function getMaxEntityViewOrder(entityId: string): Promise<number> {
return (
(
await db.entityView.aggregate({
where: { entityId },
_max: {
order: true,
},
})
)._max?.order ?? 0
);
}
export async function createEntityView(data: {
entityId: string;
tenantId: string | null;
userId: string | null;
createdByUserId: string;
layout: string;
name: string;
title: string;
isDefault: boolean;
isSystem: boolean;
pageSize: number;
groupByPropertyId?: string | null;
gridColumns?: number;
gridColumnsSm?: number;
gridColumnsMd?: number;
gridColumnsLg?: number;
gridColumnsXl?: number;
gridColumns2xl?: number;
gridGap?: string;
order?: number;
}) {
if (!data.order) {
data.order = (await getMaxEntityViewOrder(data.entityId)) + 1;
}
return await db.entityView.create({
data: {
entityId: data.entityId,
tenantId: data.tenantId,
userId: data.userId,
createdByUserId: data.createdByUserId,
layout: data.layout,
order: data.order,
name: data.name,
title: data.title,
isDefault: data.isDefault,
isSystem: data.isSystem,
pageSize: data.pageSize,
groupByPropertyId: data.groupByPropertyId,
gridColumns: data.gridColumns ?? 5,
gridColumnsSm: data.gridColumnsSm ?? 2,
gridColumnsMd: data.gridColumnsMd ?? 3,
gridColumnsLg: data.gridColumnsLg ?? 4,
gridColumnsXl: data.gridColumnsXl ?? 5,
gridColumns2xl: data.gridColumns2xl ?? 6,
gridGap: data.gridGap ?? "sm",
},
});
}
export async function updateEntityViewProperties(id: string, items: { propertyId: string | null; name: string; order: number }[]) {
await db.entityViewProperty.deleteMany({
where: { entityViewId: id },
});
return await Promise.all(
items.map(async (item) => {
return await db.entityViewProperty.create({
data: {
entityViewId: id,
propertyId: item.propertyId,
name: item.name,
order: item.order,
},
});
})
);
}
type EntityViewScope = {
id: string;
entityId: string;
tenantId: string | null;
userId: string | null;
};
async function assertScopedEntityView(scope: EntityViewScope) {
const view = await getEntityView(scope.id, { entityId: scope.entityId, tenantId: scope.tenantId, userId: scope.userId });
if (!view || view.tenantId !== scope.tenantId || view.userId !== scope.userId) {
throw Error("Entity view not found");
}
return view;
}
export async function updateScopedEntityViewProperties(scope: EntityViewScope, items: { propertyId: string | null; name: string; order: number }[]) {
await assertScopedEntityView(scope);
return await updateEntityViewProperties(scope.id, items);
}
export async function updateEntityViewFilters(id: string, items: { name: string; condition: string; value: string; match: string }[]) {
await db.entityViewFilter.deleteMany({
where: { entityViewId: id },
});
return await Promise.all(
items.map(async (item) => {
return await db.entityViewFilter.create({
data: {
entityViewId: id,
name: item.name,
condition: item.condition,
value: item.value,
match: item.match,
},
});
})
);
}
export async function updateScopedEntityViewFilters(scope: EntityViewScope, items: { name: string; condition: string; value: string; match: string }[]) {
await assertScopedEntityView(scope);
return await updateEntityViewFilters(scope.id, items);
}
export async function updateEntityViewSort(id: string, items: { name: string; asc: boolean; order: number }[]) {
await db.entityViewSort.deleteMany({
where: { entityViewId: id },
});
return await Promise.all(
items.map(async (item) => {
return await db.entityViewSort.create({
data: {
entityViewId: id,
name: item.name,
asc: item.asc,
order: item.order,
},
});
})
);
}
export async function updateScopedEntityViewSort(scope: EntityViewScope, items: { name: string; asc: boolean; order: number }[]) {
await assertScopedEntityView(scope);
return await updateEntityViewSort(scope.id, items);
}
export async function updateEntityView(
id: string,
data: {
layout?: string;
isDefault?: boolean;
isSystem?: boolean;
pageSize?: number;
name?: string;
title?: string;
order?: number;
groupByPropertyId?: string | null;
gridColumns?: number;
gridColumnsSm?: number;
gridColumnsMd?: number;
gridColumnsLg?: number;
gridColumnsXl?: number;
gridColumns2xl?: number;
gridGap?: string;
}
) {
return await db.entityView.update({
where: { id },
data,
});
}
type UpdateEntityViewData = Parameters<typeof updateEntityView>[1];
export async function updateScopedEntityView(scope: EntityViewScope, data: UpdateEntityViewData) {
const result = await db.entityView.updateMany({
where: scope,
data,
});
if (result.count !== 1) {
throw Error("Entity view not found");
}
return await assertScopedEntityView(scope);
}
export async function deleteEntityView(id: string) {
return await db.entityView.delete({
where: { id },
});
}
export async function deleteScopedEntityView(scope: EntityViewScope) {
const result = await db.entityView.deleteMany({
where: scope,
});
if (result.count !== 1) {
throw Error("Entity view not found");
}
}
@@ -1,202 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db.server", () => ({
db: {
entityWebhook: {
deleteMany: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
updateMany: vi.fn(),
},
entityWebhookLog: {
create: vi.fn(async (args) => args.data),
},
},
}));
vi.mock("~/utils/url.server", () => ({
getBaseURL: vi.fn((request: Request) => new URL(request.url).origin),
}));
// The shared outbound client resolves DNS and rejects hosts that resolve to
// internal addresses. Stub the resolver so public test hosts resolve to a
// public IP, while a chosen host simulates DNS rebinding to a metadata address.
vi.mock("node:dns/promises", () => ({
lookup: vi.fn(async (hostname: string) => {
if (hostname === "rebind.attacker.test") {
return [{ address: "169.254.169.254", family: 4 }];
}
return [{ address: "93.184.216.34", family: 4 }];
}),
}));
import { db } from "~/utils/db.server";
import { callEntityWebhooks, deleteEntityWebhook, getEntityWebhook, updateEntityWebhook } from "./entityWebhooks.db.server";
const entityWebhookMock = vi.mocked(db.entityWebhook, true);
const entityWebhookLogMock = vi.mocked(db.entityWebhookLog, true);
describe("entity webhook delivery", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 204 })));
});
it("delivers allowed absolute webhook URLs", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_absolute", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenCalledWith("https://hooks.example.com/rows", expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal) }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_absolute", logId: "log_1", status: 204 } });
});
it("delivers webhooks at request-relative endpoints resolved against the base URL", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_relative", entityId: "entity_1", action: "created", method: "POST", endpoint: "/webhooks/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenCalledWith("https://tenant.example.com/webhooks/rows", expect.objectContaining({ redirect: "manual", signal: expect.any(AbortSignal) }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_relative", logId: "log_1", status: 204 } });
});
it("follows safe redirects after validating the redirect target", async () => {
vi.stubGlobal(
"fetch",
vi
.fn()
.mockResolvedValueOnce(new Response(null, { status: 307, headers: { location: "https://hooks.example.com/rows-next" } }))
.mockResolvedValueOnce(new Response(null, { status: 204 }))
);
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_redirect", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenNthCalledWith(1, "https://hooks.example.com/rows", expect.objectContaining({ method: "POST", redirect: "manual" }));
expect(fetch).toHaveBeenNthCalledWith(2, "https://hooks.example.com/rows-next", expect.objectContaining({ method: "POST", redirect: "manual" }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_redirect", logId: "log_1", status: 204 } });
});
it("blocks unsafe redirect targets without following them", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 302, headers: { location: "http://127.0.0.1/webhook" } })));
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_redirect_blocked", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith("https://hooks.example.com/rows", expect.objectContaining({ redirect: "manual" }));
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_redirect_blocked", logId: "log_1", status: 0 } });
});
it("blocks unsafe webhook URLs and records failed delivery status without fetching", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_private", entityId: "entity_1", action: "created", method: "POST", endpoint: "http://10.0.0.1/webhook" },
{ id: "webhook_internal", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://worker.internal/webhook" },
{ id: "webhook_relative_localhost", entityId: "entity_1", action: "created", method: "POST", endpoint: "/webhooks/rows" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://localhost/api/rows"),
});
expect(fetch).not.toHaveBeenCalled();
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_private", logId: "log_1", status: 0 } });
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_internal", logId: "log_1", status: 0 } });
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_relative_localhost", logId: "log_1", status: 0 } });
});
it("blocks public hostnames that resolve to internal addresses (DNS rebinding) without fetching", async () => {
entityWebhookMock.findMany.mockResolvedValueOnce([
{ id: "webhook_rebind", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://rebind.attacker.test/webhook" },
]);
await callEntityWebhooks({
logId: "log_1",
entityId: "entity_1",
action: "created",
body: "payload",
request: new Request("https://tenant.example.com/api/rows"),
});
expect(fetch).not.toHaveBeenCalled();
expect(entityWebhookLogMock.create).toHaveBeenCalledWith({ data: { webhookId: "webhook_rebind", logId: "log_1", status: 0 } });
});
});
describe("entity webhook admin boundaries", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("reads a webhook only inside the current entity scope", async () => {
const webhook = { id: "webhook_1", entityId: "entity_1", action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" };
entityWebhookMock.findFirst.mockResolvedValueOnce(webhook);
await expect(getEntityWebhook({ id: "webhook_1", entityId: "entity_1" })).resolves.toEqual(webhook);
expect(entityWebhookMock.findFirst).toHaveBeenCalledWith({ where: { id: "webhook_1", entityId: "entity_1" } });
});
it("updates and deletes only webhooks inside the current entity scope", async () => {
entityWebhookMock.updateMany.mockResolvedValueOnce({ count: 1 });
entityWebhookMock.deleteMany.mockResolvedValueOnce({ count: 1 });
await updateEntityWebhook(
{ id: "webhook_1", entityId: "entity_1" },
{ action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" }
);
await deleteEntityWebhook({ id: "webhook_1", entityId: "entity_1" });
expect(entityWebhookMock.updateMany).toHaveBeenCalledWith({
where: { id: "webhook_1", entityId: "entity_1" },
data: { action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" },
});
expect(entityWebhookMock.deleteMany).toHaveBeenCalledWith({ where: { id: "webhook_1", entityId: "entity_1" } });
});
it("rejects scoped update and delete misses", async () => {
entityWebhookMock.updateMany.mockResolvedValueOnce({ count: 0 });
entityWebhookMock.deleteMany.mockResolvedValueOnce({ count: 0 });
await expect(
updateEntityWebhook({ id: "webhook_foreign", entityId: "entity_1" }, { action: "created", method: "POST", endpoint: "https://hooks.example.com/rows" })
).rejects.toThrow("Entity webhook not found.");
await expect(deleteEntityWebhook({ id: "webhook_foreign", entityId: "entity_1" })).rejects.toThrow("Entity webhook not found.");
});
});
@@ -1,133 +0,0 @@
import { EntityWebhook } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { getBaseURL } from "~/utils/url.server";
import { fetchOutboundHttpWithRedirects } from "~/utils/outboundHttp.server";
const BLOCKED_WEBHOOK_STATUS = 0;
export type EntityWebhookWithDetails = EntityWebhook & { _count: { logs: number } };
export async function getEntityWebhooks(entityId: string) {
return await db.entityWebhook.findMany({
where: {
entityId,
},
include: {
_count: {
select: {
logs: true,
},
},
},
});
}
export async function getEntityWebhook(input: { id: string; entityId: string }) {
return await db.entityWebhook.findFirst({
where: {
id: input.id,
entityId: input.entityId,
},
});
}
export async function getEntityWebhooksByAction(entityId: string, action: string) {
return await db.entityWebhook.findMany({
where: {
entityId,
action,
},
});
}
export async function createEntityWebhook(data: { entityId: string; action: string; method: string; endpoint: string }) {
return await db.entityWebhook.create({
data,
});
}
export async function updateEntityWebhook(
input: { id: string; entityId: string },
data: {
action: string;
method: string;
endpoint: string;
}
) {
const result = await db.entityWebhook.updateMany({
where: {
id: input.id,
entityId: input.entityId,
},
data,
});
if (result.count !== 1) {
throw new Error("Entity webhook not found.");
}
return result;
}
export async function deleteEntityWebhook(input: { id: string; entityId: string }) {
const result = await db.entityWebhook.deleteMany({
where: {
id: input.id,
entityId: input.entityId,
},
});
if (result.count !== 1) {
throw new Error("Entity webhook not found.");
}
return result;
}
export async function callEntityWebhooks({
logId,
entityId,
action,
body,
request,
}: {
logId: string;
entityId: string;
action: string;
body: string;
request?: Request;
}) {
const webhooks = await getEntityWebhooksByAction(entityId, action);
return await Promise.all(
webhooks.map(async (webhook) => {
if (webhook.endpoint) {
const status = await fetchLegacyWebhookStatus(webhook.endpoint, request, {
method: webhook.method,
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
});
return db.entityWebhookLog.create({
data: {
webhookId: webhook.id,
logId,
status,
},
});
}
})
);
}
function resolveWebhookEndpoint(endpoint: string, request?: Request): string {
return endpoint.startsWith("/") && request ? getBaseURL(request) + endpoint : endpoint;
}
// Delivery goes through the shared SSRF-safe outbound client, which validates
// the scheme, blocks literal private/loopback/link-local/metadata hosts, AND
// resolves DNS to reject public hostnames that resolve to internal addresses
// (DNS rebinding) — the gap in the previous forked, hostname-string-only guard.
// Redirect hops are re-validated and resolved the same way. Any rejection or
// transport error is recorded as a blocked-delivery status.
async function fetchLegacyWebhookStatus(endpoint: string, request: Request | undefined, init: RequestInit): Promise<number> {
try {
const response = await fetchOutboundHttpWithRedirects(resolveWebhookEndpoint(endpoint, request), init);
return response.status;
} catch {
return BLOCKED_WEBHOOK_STATUS;
}
}
@@ -1,273 +0,0 @@
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { Colors } from "~/application/enums/shared/Colors";
import { defaultProperties } from "~/utils/helpers/PropertyHelper";
import { db } from "../../db.server";
export async function getProperty(id: string) {
return await db.property.findUnique({
where: {
id,
},
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
formula: true,
},
});
}
export async function getEntityPropertyByName(entityId: string, name: string) {
return await db.property.findFirst({
where: {
entityId,
name,
},
include: {
attributes: true,
options: {
orderBy: {
order: "asc",
},
},
},
});
}
export async function createProperty(data: {
entityId: string;
name: string;
title: string;
type: PropertyType;
subtype: string | null;
order: number;
isDefault: boolean;
isRequired: boolean;
isHidden: boolean;
isDisplay: boolean;
isReadOnly: boolean;
canUpdate: boolean;
showInCreate: boolean;
formulaId: string | null;
tenantId: string | null;
}) {
if (data.name.includes(" ")) {
throw Error("Property names cannot contain spaces: " + data.name);
}
if (data.name.includes("-")) {
throw Error("Property names cannot contain '-': " + data.name);
}
return await db.property.create({
data,
});
}
export type CreatePropertyDto = {
name: string;
title: string;
type: PropertyType;
subtype: string | null;
isRequired?: boolean;
isDefault?: boolean;
isHidden?: boolean;
isDisplay?: boolean;
isReadOnly?: boolean;
canUpdate?: boolean;
showInCreate?: boolean;
formulaId?: string | null;
tenantId?: string | null;
options?: { order: number; value: string; name?: string; color?: Colors }[];
attributes?: {
name: string;
value: string;
}[];
};
export async function createProperties(entityId: string, fields: CreatePropertyDto[]) {
return await Promise.all(
fields.map(async (field, idx) => {
const property = await createProperty({
entityId,
order: defaultProperties.length + idx + 1,
name: field.name,
title: field.title,
type: field.type,
subtype: field.subtype ?? null,
isRequired: field.isRequired ?? true,
isDefault: field.isDefault ?? false,
isHidden: field.isHidden ?? false,
isDisplay: field.isDisplay ?? false,
isReadOnly: field.isReadOnly ?? false,
canUpdate: field.canUpdate ?? true,
showInCreate: field.showInCreate ?? true,
formulaId: field.formulaId ?? null,
tenantId: field.tenantId ?? null,
});
if (field.options) {
await updatePropertyOptions(
property.id,
field.options.map((option) => {
return {
order: option.order,
value: option.value,
name: option.name ?? null,
color: option.color,
};
})
);
}
if (field.attributes) {
await updatePropertyAttributes(property.id, field.attributes);
}
return property;
})
);
}
export async function updateProperty(
id: string,
data: {
name?: string;
title?: string;
type?: PropertyType;
subtype?: string | null;
order?: number;
isDefault?: boolean;
isRequired?: boolean;
isHidden?: boolean;
isDisplay?: boolean;
isReadOnly?: boolean;
canUpdate?: boolean;
showInCreate?: boolean;
formulaId?: string | null;
}
) {
const property = await db.property.update({
where: { id },
data,
});
return property;
}
type PropertyScope = {
id: string;
tenantId: string | null;
entityId: string;
};
type UpdatePropertyData = Parameters<typeof updateProperty>[1];
async function assertScopedProperty(scope: PropertyScope) {
const property = await getProperty(scope.id);
if (!property || property.tenantId !== scope.tenantId || property.entityId !== scope.entityId) {
throw Error("Property not found");
}
return property;
}
export async function getScopedProperty(scope: PropertyScope) {
const property = await getProperty(scope.id);
if (!property || property.tenantId !== scope.tenantId || property.entityId !== scope.entityId) {
return null;
}
return property;
}
export async function updateScopedProperty(scope: PropertyScope, data: UpdatePropertyData) {
const result = await db.property.updateMany({
where: scope,
data,
});
if (result.count !== 1) {
throw Error("Property not found");
}
return await assertScopedProperty(scope);
}
export async function updatePropertyOrder(id: string, order: number) {
return await db.property.update({
where: { id },
data: {
order,
},
});
}
export async function updateScopedPropertyOrder(scope: PropertyScope, order: number) {
const result = await db.property.updateMany({
where: scope,
data: {
order,
},
});
if (result.count !== 1) {
throw Error("Property not found");
}
}
export async function updatePropertyOptions(id: string, options: { order: number; value: string; name?: string | null; color?: Colors }[]) {
await db.propertyOption.deleteMany({
where: { propertyId: id },
});
await Promise.all(
options.map(async (option) => {
return await db.propertyOption.create({
data: {
propertyId: id,
order: option.order,
value: option.value,
name: option.name ?? null,
color: option.color,
},
});
})
);
}
export async function updateScopedPropertyOptions(scope: PropertyScope, options: { order: number; value: string; name?: string | null; color?: Colors }[]) {
await assertScopedProperty(scope);
await updatePropertyOptions(scope.id, options);
}
export async function updatePropertyAttributes(id: string, attributes: { name: string; value: string }[]) {
await db.propertyAttribute.deleteMany({
where: { propertyId: id },
});
await Promise.all(
attributes
.filter((f) => f.value !== undefined)
.map(async (attribute) => {
return await db.propertyAttribute.create({
data: {
propertyId: id,
name: attribute.name,
value: attribute.value,
},
});
})
);
}
export async function updateScopedPropertyAttributes(scope: PropertyScope, attributes: { name: string; value: string }[]) {
await assertScopedProperty(scope);
await updatePropertyAttributes(scope.id, attributes);
}
export async function deleteProperty(id: string) {
return await db.property.delete({
where: { id },
});
}
export async function deleteScopedProperty(scope: PropertyScope) {
const result = await db.property.deleteMany({
where: scope,
});
if (result.count !== 1) {
throw Error("Property not found");
}
}
@@ -1,29 +0,0 @@
import { RowCommentReaction } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
export type RowCommentReactionWithDetails = RowCommentReaction & {
createdByUser: UserSimple;
};
export async function setRowCommentReaction(data: { createdByUserId: string; rowCommentId: string; reaction: string }) {
const existing = await db.rowCommentReaction.findFirst({
where: {
createdByUserId: data.createdByUserId,
rowCommentId: data.rowCommentId,
reaction: data.reaction,
},
});
if (!existing) {
await db.rowCommentReaction.create({
data,
});
return true;
} else {
await db.rowCommentReaction.deleteMany({
where: {
...data,
},
});
return false;
}
}
@@ -1,91 +0,0 @@
import { RowComment } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
import { RowCommentReactionWithDetails } from "./rowCommentReaction.db.server";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
export type RowCommentWithDetails = RowComment & {
createdByUser: UserSimple;
reactions: RowCommentReactionWithDetails[];
// replies: (RowComment & { createdByUser: User })[];
};
export async function getRowComments(rowId: string): Promise<RowCommentWithDetails[]> {
return await db.rowComment.findMany({
where: {
rowId,
// parentCommentId: null,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
reactions: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
},
},
// replies: {
// include: {
// ...UserModelHelper.includeSimpleCreatedByUser,
// },
// },
},
});
}
export async function getRowComment(id: string): Promise<RowCommentWithDetails | null> {
return await db.rowComment.findUnique({
where: {
id,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
reactions: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
},
},
// replies: {
// include: {
// ...UserModelHelper.includeSimpleCreatedByUser,
// },
// },
},
});
}
export async function getRowCommentInRow({ id, rowId }: { id: string; rowId: string }): Promise<RowCommentWithDetails | null> {
return await db.rowComment.findFirst({
where: {
id,
rowId,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
reactions: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
},
},
},
});
}
export async function createRowComment(data: { createdByUserId: string; rowId: string; value: string }) {
return await db.rowComment.create({
data,
});
}
export async function updateRowCommentInRow({ id, rowId }: { id: string; rowId: string }, data: { value?: string; isDeleted?: boolean }) {
const updated = await db.rowComment.updateMany({
where: {
id,
rowId,
},
data,
});
if (updated.count !== 1) {
throw new Error("Row comment not found");
}
return updated;
}
@@ -1,91 +0,0 @@
import { db } from "~/utils/db.server";
import { createScopedLogger } from "~/utils/logger.server";
const rowRelationshipsLogger = createScopedLogger("db.entities.rowRelationships");
type RowRelationshipTenantScope = {
tenantId: string | null;
};
function scopedRowRelationshipWhere(scope: RowRelationshipTenantScope) {
return {
parent: { deletedAt: null, tenantId: scope.tenantId },
child: { deletedAt: null, tenantId: scope.tenantId },
};
}
export async function getRowRelationship(id: string, scope: RowRelationshipTenantScope) {
return await db.rowRelationship.findFirst({
where: { id, ...scopedRowRelationshipWhere(scope) },
include: {
relationship: true,
},
});
}
export async function getRowsRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
return await db.rowRelationship.findFirst({
where: { parentId, childId, ...scopedRowRelationshipWhere({ tenantId }) },
});
}
export async function createRowRelationship({
parentId,
childId,
relationshipId,
metadata,
tenantId,
}: {
parentId: string;
childId: string;
relationshipId: string;
metadata: string | null;
tenantId: string | null;
}) {
const [parent, child] = await Promise.all([
db.row.findFirst({ where: { id: parentId, deletedAt: null, tenantId }, select: { id: true } }),
db.row.findFirst({ where: { id: childId, deletedAt: null, tenantId }, select: { id: true } }),
]);
if (!parent || !child) {
return undefined;
}
return await db.rowRelationship
.create({
data: {
parentId,
childId,
relationshipId,
metadata,
},
})
.catch((e) => {
rowRelationshipsLogger.error({ err: e }, "Error creating row relationship");
});
}
export async function deleteRowRelationship({ parentId, childId, tenantId }: { parentId: string; childId: string; tenantId: string | null }) {
return await db.rowRelationship.deleteMany({
where: {
parentId,
childId,
...scopedRowRelationshipWhere({ tenantId }),
},
});
}
export async function deleteRowRelationshipById(id: string, scope: RowRelationshipTenantScope) {
const item = await db.rowRelationship.findFirst({
where: { id, ...scopedRowRelationshipWhere(scope) },
select: { id: true },
});
if (!item) {
return null;
}
return await db.rowRelationship.delete({
where: {
id: item.id,
},
});
}
@@ -1,69 +0,0 @@
import { EntityTag, RowTag } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
export type RowTagWithDetails = RowTag & {
tag: EntityTag;
};
export async function getRowTags(rowId: string): Promise<RowTagWithDetails[]> {
return await db.rowTag.findMany({
where: {
rowId,
},
include: {
tag: true,
},
});
}
export async function getRowTagById(id: string): Promise<RowTagWithDetails | null> {
return await db.rowTag.findUnique({
where: {
id,
},
include: {
tag: true,
},
});
}
export async function getRowTag(rowId: string, value: string): Promise<RowTagWithDetails | null> {
return await db.rowTag.findFirst({
where: {
rowId,
tag: {
value,
},
},
include: {
tag: true,
},
});
}
export async function getRowTagByIds(rowId: string, tagId: string): Promise<RowTagWithDetails | null> {
return await db.rowTag.findFirst({
where: {
rowId,
tagId,
},
include: {
tag: true,
},
});
}
export async function createRowTag(data: { rowId: string; tagId: string }) {
return await db.rowTag.create({
data,
});
}
export async function deleteRowTags(rowId: string, tagId: string) {
return await db.rowTag.deleteMany({
where: {
rowId,
tagId,
},
});
}
@@ -1,46 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
type RowTaskDbMocks = {
findMany: ReturnType<typeof vi.fn>;
};
function getMocks(): RowTaskDbMocks {
const store = globalThis as typeof globalThis & { __rowTaskDbMocks__?: RowTaskDbMocks };
store.__rowTaskDbMocks__ ??= {
findMany: vi.fn(),
};
return store.__rowTaskDbMocks__;
}
vi.mock("~/utils/db.server", () => ({
db: {
rowTask: {
findMany: getMocks().findMany,
},
},
}));
import { getAllRowTasks } from "./rowTasks.db.server";
const mocks = getMocks();
describe("row task db helpers", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.findMany.mockResolvedValue([]);
});
it("filters task lists through row tenant scope when provided", async () => {
await getAllRowTasks({ tenantId: "tenant_1", assignedOrCreatedUserId: "user_1", completed: false });
expect(mocks.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
completed: false,
row: { tenantId: "tenant_1" },
OR: [{ createdByUserId: "user_1" }, { assignedToUserId: "user_1" }],
}),
})
);
});
});
@@ -1,188 +0,0 @@
import { Prisma, RowTask } from "@toolctrl/db/prisma-browser";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
import { RowWithValues } from "./rows.db.server";
export type RowTaskWithDetails = RowTask & {
createdByUser: UserSimple;
assignedToUser: UserSimple | null;
row: RowWithValues;
};
export async function getRowTasks(rowId: string): Promise<RowTaskWithDetails[]> {
return await db.rowTask.findMany({
where: {
rowId,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
orderBy: [
{
completed: "asc",
},
{
createdAt: "asc",
},
],
});
}
export async function getRowTask(id: string): Promise<RowTaskWithDetails | null> {
return await db.rowTask.findUnique({
where: {
id,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
});
}
export async function getRowTaskInRow({ id, rowId }: { id: string; rowId: string }): Promise<RowTaskWithDetails | null> {
return await db.rowTask.findFirst({
where: {
id,
rowId,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
});
}
export async function createRowTask(data: {
createdByUserId: string;
rowId: string;
title: string;
description?: string;
completed?: boolean;
completedAt?: Date | null;
completedByUserId?: string | null;
assignedToUserId?: string | null;
deadline?: Date | null;
}) {
return await db.rowTask.create({
data: {
createdByUserId: data.createdByUserId,
rowId: data.rowId,
title: data.title,
description: data.description ?? "",
completed: data.completed ?? false,
completedAt: data.completedAt ?? null,
completedByUserId: data.completedByUserId ?? null,
assignedToUserId: data.assignedToUserId ?? null,
deadline: data.deadline ?? null,
},
});
}
export async function updateRowTaskInRow(
scope: { id: string; rowId: string },
data: {
createdByUserId?: string;
rowId?: string;
title?: string;
description?: string;
completed?: boolean;
completedAt?: Date | null;
completedByUserId?: string | null;
assignedToUserId?: string | null;
deadline?: Date | null;
}
) {
const updated = await db.rowTask.updateMany({
where: {
id: scope.id,
rowId: scope.rowId,
},
data,
});
if (updated.count !== 1) {
throw new Error("Row task not found");
}
return updated;
}
export async function deleteRowTaskInRow(scope: { id: string; rowId: string }) {
const deleted = await db.rowTask.deleteMany({
where: {
id: scope.id,
rowId: scope.rowId,
},
});
if (deleted.count !== 1) {
throw new Error("Row task not found");
}
return deleted;
}
export async function getAllRowTasks({
completed,
assignedOrCreatedUserId,
tenantId,
}: {
completed?: boolean;
assignedOrCreatedUserId?: string;
tenantId?: string | null;
}): Promise<RowTaskWithDetails[]> {
const userWhere: Prisma.RowTaskWhereInput = {};
if (assignedOrCreatedUserId) {
userWhere.OR = [
{
createdByUserId: assignedOrCreatedUserId,
},
{
assignedToUserId: assignedOrCreatedUserId,
},
];
}
return await db.rowTask.findMany({
where: {
completed,
...(tenantId !== undefined ? { row: { tenantId } } : {}),
...userWhere,
},
include: {
...UserModelHelper.includeSimpleCreatedByUser,
assignedToUser: true,
row: {
include: {
createdByUser: { select: UserModelHelper.selectSimpleUserProperties },
createdByApiKey: true,
values: { include: { media: true, multiple: true, range: true } },
},
},
},
orderBy: [
{
createdAt: "desc",
},
],
});
}
@@ -1,26 +0,0 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
const rootPath = (...segments: string[]) => resolve(process.cwd(), ...segments);
const readProjectFile = (path: string) => readFileSync(rootPath(path), "utf8");
describe("row tenant-scope guard", () => {
it("requires explicit tenant and entity scope for row reloads", () => {
const source = readProjectFile("apps/web/app/utils/db/entities/rows.db.server.ts");
expect(source).toContain("getRowById(id: string, scope: { entityId?: string; tenantId: string | null })");
expect(source).not.toContain("getRowById(id: string, scope?:");
expect(source).not.toContain("RowModelHelper.includeRowDetailsNested");
});
it("keeps legacy row relationship helpers tenant-scoped", () => {
const source = readProjectFile("apps/web/app/utils/db/entities/rowRelationships.db.server.ts");
expect(source).toContain("type RowRelationshipTenantScope");
expect(source).toContain("parent: { deletedAt: null, tenantId: scope.tenantId }");
expect(source).toContain("child: { deletedAt: null, tenantId: scope.tenantId }");
expect(source).not.toContain("findUnique({");
expect(source).not.toContain("where: { id },");
});
});
@@ -1,505 +0,0 @@
import {
hardDeleteRowById,
updateRowWithValues,
type LegacyRowWithDetails,
type RowMutationData,
type RowMutationValueInput,
type RowMutationRelationshipChildInput,
type RowMutationRelationshipParentInput,
} from "@toolctrl/db/rows.server";
import {
Prisma,
Row,
Tenant,
RowValue,
ApiKey,
RowMedia,
RowRelationship,
SampleCustomEntity,
RowPermission,
RowValueMultiple,
RowValueRange,
} from "@toolctrl/db/prisma-browser";
import { RowFiltersDto } from "~/application/dtos/data/RowFiltersDto";
import { MediaDto } from "~/application/dtos/entities/MediaDto";
import { deleteRowMediaFromStorageProvider, storeRowMediaInStorageProvider } from "~/utils/helpers/.server/MediaService";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import TenantHelper from "~/utils/helpers/TenantHelper";
import { db } from "../../db.server";
import { UserSimple } from "../users.db.server";
import { EntityWithDetails, getEntityById } from "./entities.db.server";
import { RowTagWithDetails } from "./rowTags.db.server";
import { getRowPermissionsCondition } from "~/utils/helpers/.server/PermissionsService";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";
import RowModelHelper from "~/utils/helpers/models/RowModelHelper";
export type RowValueWithDetails = RowValue & {
media: RowMedia[];
multiple: RowValueMultiple[];
range: RowValueRange | null;
};
export type RowWithValues = Row & {
createdByUser: UserSimple | null;
createdByApiKey: ApiKey | null;
values: RowValueWithDetails[];
};
export type RowWithCreatedBy = Row & {
createdByUser: UserSimple | null;
createdByApiKey: ApiKey | null;
};
export type RowWithDetails = Row & {
createdByUser: UserSimple | null;
createdByApiKey: ApiKey | null;
tenant: Tenant | null;
values: RowValueWithDetails[];
tags: RowTagWithDetails[];
parentRows:
| (RowRelationship & { parent: RowWithValues })[]
| (RowRelationship & {
parent: RowWithValues & {
parentRows: (RowRelationship & {
parent: { values: RowValueWithDetails[] };
})[];
childRows: (RowRelationship & {
child: { values: RowValueWithDetails[] };
})[];
};
})[];
childRows: (RowRelationship & {
child: RowWithValues & {
parentRows: (RowRelationship & {
parent: { values: RowValueWithDetails[] };
})[];
childRows: (RowRelationship & {
child: { values: RowValueWithDetails[] };
})[];
};
})[];
permissions: RowPermission[];
sampleCustomEntity: SampleCustomEntity | null;
};
export type RowMutationScope = { id: string; entityId: string; tenantId: string | null };
export async function getAllRows(entityId: string): Promise<RowWithDetails[]> {
return await db.row.findMany({
where: {
deletedAt: null,
entityId,
},
include: RowModelHelper.includeRowDetails,
});
}
export async function getRows({
entityId,
entityName,
tenantId,
userId,
take,
skip,
orderBy,
filters,
ids,
rowWhere,
includePublic,
}: {
entityId?: string;
entityName?: string;
tenantId?: string | null;
userId?: string;
take?: number;
skip?: number;
orderBy?: Prisma.RowOrderByWithRelationInput[];
filters?: RowFiltersDto;
ids?: string[];
rowWhere?: Prisma.RowWhereInput;
includePublic?: boolean;
}): Promise<RowWithDetails[]> {
const whereFilters = RowFiltersHelper.getRowFiltersCondition(filters);
let filterEntity: Prisma.RowWhereInput | undefined = undefined;
if (entityId) {
filterEntity = { entityId };
} else if (entityName) {
filterEntity = { entity: { name: entityName } };
}
const accessFilters = await getAccessFilters({ tenantId });
const where: Prisma.RowWhereInput = {
AND: [
{ deletedAt: null },
{ ...rowWhere },
whereFilters,
{ id: { in: ids } },
{ ...filterEntity },
{ ...accessFilters },
// ...getSearchCondition(filters?.query),
],
};
return await db.row.findMany({
take,
skip,
where,
include: RowModelHelper.createScopedIncludeRowDetails(tenantId ?? null),
orderBy,
});
}
export async function getRowsBetween(name: string, tenantId: string | null, startDate: Date, endDate: Date): Promise<RowWithDetails[]> {
return await db.row.findMany({
where: {
AND: [
{ deletedAt: null },
{
entity: { name },
...TenantHelper.tenantCondition({ tenantId }),
},
{
createdAt: {
lte: endDate,
gte: startDate,
},
},
],
},
include: RowModelHelper.createScopedIncludeRowDetails(tenantId),
orderBy: { createdAt: "asc" },
});
}
export async function getRowsInIds(ids: string[], tenantId?: string | null): Promise<RowWithDetails[]> {
return await db.row.findMany({
where: {
deletedAt: null,
id: {
in: ids,
},
tenantId,
},
include: tenantId === undefined ? RowModelHelper.includeRowDetails : RowModelHelper.createScopedIncludeRowDetails(tenantId),
});
}
export async function countRows({
entityId,
entityName,
tenantId,
userId,
filters,
rowWhere,
includePublic,
}: {
entityId?: string;
entityName?: string;
tenantId?: string | null;
userId?: string | undefined;
filters?: RowFiltersDto;
rowWhere?: Prisma.RowWhereInput;
includePublic?: boolean;
}): Promise<number> {
const whereFilters = RowFiltersHelper.getRowFiltersCondition(filters);
let filterEntity: { entityId: string } | { entity: { name: string } } | undefined = undefined;
if (entityId) {
filterEntity = { entityId };
} else if (entityName) {
filterEntity = { entity: { name: entityName } };
}
const accessFilters = await getAccessFilters({ tenantId });
const where: Prisma.RowWhereInput = {
AND: [
{ deletedAt: null },
{ ...rowWhere },
whereFilters,
// { id: { in: ids } },
{ ...filterEntity },
{ ...accessFilters },
// ...getSearchCondition(filters?.query),
],
};
return await db.row.count({
where,
});
}
export async function getRow({ entityId, id, tenantId }: { entityId: string; id: string; tenantId?: string | null }): Promise<RowWithDetails | null> {
const accessFilters = await getAccessFilters({ tenantId });
return await db.row.findFirst({
where: {
deletedAt: null,
id,
entityId,
...accessFilters,
},
include: {
...RowModelHelper.createScopedIncludeRowDetails(tenantId ?? null),
},
});
}
export async function getRowById(id: string, scope: { entityId?: string; tenantId: string | null }): Promise<RowWithDetails | null> {
return await db.row.findFirst({
where: {
deletedAt: null,
id,
...(scope.entityId ? { entityId: scope.entityId } : {}),
tenantId: scope.tenantId,
},
include: {
...RowModelHelper.createScopedIncludeRowDetails(scope.tenantId),
},
});
}
export async function getMaxRowFolio({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
let where: any = { tenantId, entityId };
return await db.row.aggregate({
where,
_max: {
folio: true,
},
});
}
export async function getNextRowFolio({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
const maxFolio = await getMaxRowFolio({ tenantId, entityId });
let next = 1;
if (maxFolio && maxFolio._max.folio !== null) {
next = maxFolio._max.folio + 1;
}
return next;
}
export async function getMaxRowOrder({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
let where: any = { tenantId, entityId };
return await db.row.aggregate({
where,
_max: {
order: true,
},
});
}
export async function getNextRowOrder({ tenantId, entityId }: { tenantId: string | null; entityId: string }) {
const maxOrder = await getMaxRowOrder({ tenantId, entityId });
let next = 1;
if (maxOrder && maxOrder._max.order !== null) {
next = maxOrder._max.order + 1;
}
return next;
}
export async function createRow({
entity,
data,
nextFolio,
nextOrder,
}: {
entity: EntityWithDetails;
data: {
tenantId: string | null;
createdByUserId?: string | null;
createdByApiKeyId?: string | null;
properties: any;
dynamicProperties?: {
propertyId: string;
id?: string | null;
textValue?: string | null;
numberValue?: number | string | null;
dateValue?: Date | string | null;
booleanValue?: boolean | null;
media?: MediaDto[];
multiple?: RowValueMultipleDto[];
range?: RowValueRangeDto;
}[];
parentRows?: { relationshipId: string; parentId: string }[];
childRows?: { relationshipId: string; childId: string }[];
rowCreateInput?: Partial<Prisma.RowCreateInput>;
};
nextFolio?: number | undefined;
nextOrder?: number | undefined;
}) {
let folio = nextFolio ?? 1;
if (!nextFolio) {
const maxFolio = await getMaxRowFolio({ tenantId: data.tenantId, entityId: entity.id });
if (maxFolio && maxFolio._max.folio !== null) {
folio = maxFolio._max.folio + 1;
}
}
let order = nextOrder ?? 1;
if (!nextOrder) {
const maxOrder = await getMaxRowOrder({ tenantId: data.tenantId, entityId: entity.id });
if (maxOrder && maxOrder._max.order !== null) {
order = maxOrder._max.order + 1;
}
}
const createInput: Prisma.XOR<Prisma.RowCreateInput, Prisma.RowUncheckedCreateInput> = {
folio,
order,
entityId: entity.id,
tenantId: data.tenantId,
createdByUserId: data.createdByUserId ?? null,
createdByApiKeyId: data.createdByApiKeyId ?? null,
...data.properties,
values: {
create: data.dynamicProperties
// .filter((f) => !f.id)
?.map((value) => {
return {
propertyId: value.propertyId,
textValue: value.textValue,
numberValue: value.numberValue,
dateValue: value.dateValue,
booleanValue: value.booleanValue,
media: {
create: value.media?.map((m) => {
return {
name: m.name,
title: m.title,
type: m.type,
file: m.file,
publicUrl: m.publicUrl,
};
}),
},
multiple: {
create: value.multiple?.map((m) => {
return {
order: m.order,
value: m.value,
};
}),
},
range: {
create: {
numberMin: value.range?.numberMin,
numberMax: value.range?.numberMax,
dateMin: value.range?.dateMin,
dateMax: value.range?.dateMax,
},
},
};
}),
},
parentRows: {
create: data.parentRows?.map(({ relationshipId, parentId }) => {
return {
relationshipId,
parentId,
};
}),
},
childRows: {
create: data.childRows?.map(({ relationshipId, childId }) => {
return {
relationshipId,
childId,
};
}),
},
...data.rowCreateInput,
};
const row = await db.row.create({
data: createInput,
});
return row;
}
export async function updateRow(
scope: RowMutationScope,
data: {
properties: any;
dynamicProperties: {
propertyId: string;
id?: string | null;
textValue?: string | null;
numberValue?: number | string | null;
dateValue?: Date | string | null;
booleanValue?: boolean | null;
media?: MediaDto[];
multiple?: RowValueMultipleDto[];
range?: RowValueRangeDto | undefined;
}[];
parentRows?: { relationshipId: string; parentId: string }[];
childRows?: { relationshipId: string; childId: string }[];
rowUpdateInput?: Prisma.RowUpdateInput;
}
) {
const row = await updateRowWithValues(scope, {
properties: data.properties,
dynamicProperties: data.dynamicProperties as RowMutationValueInput[],
parentRows: data.parentRows as RowMutationRelationshipParentInput[] | undefined,
childRows: data.childRows as RowMutationRelationshipChildInput[] | undefined,
rowUpdateInput: data.rowUpdateInput,
} satisfies Omit<RowMutationData, "tenantId" | "createdByUserId" | "createdByApiKeyId" | "rowCreateInput">) as LegacyRowWithDetails as RowWithDetails;
const entity = await getEntityById({ tenantId: row.tenantId, id: row.entityId });
if (entity) {
await storeRowMediaInStorageProvider(entity, row);
}
return row;
}
export async function deleteRow(scope: RowMutationScope) {
const row = await getRowById(scope.id, { entityId: scope.entityId, tenantId: scope.tenantId });
await deleteRowMediaFromStorageProvider(row);
return await hardDeleteRowById(scope);
}
export async function deleteRows({ entityId, tenantId }: { entityId: string; tenantId: string | null }) {
return await db.row.deleteMany({
where: { entityId, tenantId },
});
}
export async function deleteRowsInIds({ ids, entityId, tenantId }: { ids: string[]; entityId: string; tenantId: string | null }) {
return await db.row.deleteMany({
where: { id: { in: ids }, entityId, tenantId },
});
}
export async function updateRowMedia(
scope: { id: string; rowId: string; entityId: string; tenantId: string | null },
data: {
file?: string;
publicUrl?: string | null;
storageBucket?: string | null;
storageProvider?: string | null;
}
) {
const result = await db.rowMedia.updateMany({
where: {
id: scope.id,
rowValue: {
rowId: scope.rowId,
row: { entityId: scope.entityId, tenantId: scope.tenantId, deletedAt: null },
},
},
data,
});
if (result.count !== 1) {
throw new Error(`Row media ${scope.id} not found`);
}
}
async function getAccessFilters({ tenantId, userId }: { tenantId?: string | null; userId?: string }) {
let tenantFilters: Prisma.RowWhereInput | undefined = undefined;
let userPermissionFilters: Prisma.RowWhereInput | undefined = undefined;
if (tenantId !== undefined) {
tenantFilters = TenantHelper.tenantCondition({ tenantId });
}
if (userId) {
userPermissionFilters = await getRowPermissionsCondition({ tenantId, userId });
}
const filters: Prisma.RowWhereInput = {
AND: [{ ...tenantFilters }, { ...userPermissionFilters }],
};
return filters;
}
@@ -1,4 +1,4 @@
import { IpAddress } from "@toolctrl/db/prisma-browser";
import { IpAddress } from "@hivegrid/db/prisma-browser";
import Constants from "~/application/Constants";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { db } from "~/utils/db.server";
@@ -1,39 +1,22 @@
import { Tenant, Log, ApiKey, Prisma } from "@toolctrl/db/prisma-browser";
import { Tenant, Log, ApiKey } from "@hivegrid/db/prisma-browser";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { DefaultLogActions } from "~/application/dtos/shared/DefaultLogActions";
import { db } from "../db.server";
import ApiHelper from "../helpers/ApiHelper";
import RowFiltersHelper from "../helpers/RowFiltersHelper";
import { getUserInfo } from "../session.server";
import { EntityWithDetails } from "./entities/entities.db.server";
import { callEntityWebhooks } from "./entities/entityWebhooks.db.server";
import { RowCommentWithDetails } from "./entities/rowComments.db.server";
import { RowWithDetails } from "./entities/rows.db.server";
import { UserWithoutPassword } from "./users.db.server";
import UserModelHelper from "../helpers/models/UserModelHelper";
export type LogWithDetails = Log & {
user: UserWithoutPassword | null;
apiKey: ApiKey | null;
tenant?: Tenant | null;
comment?: RowCommentWithDetails | null;
};
const include = {
user: true,
tenant: true,
apiKey: true,
comment: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
reactions: {
include: {
...UserModelHelper.includeSimpleCreatedByUser,
},
},
},
},
};
export async function getAllLogs(
@@ -89,73 +72,6 @@ export async function getLogs(
};
}
export async function getAllRowLogs({
entityId,
rowId,
tenantId,
pagination,
}: {
entityId?: string;
rowId?: string;
tenantId?: string | null;
pagination: { page: number; pageSize: number };
}): Promise<{ items: LogWithDetails[]; pagination: PaginationDto }> {
let where: Prisma.LogWhereInput = { rowId: { not: null } };
if (entityId) {
where = { ...where, row: { entityId } };
}
if (rowId) {
where = { ...where, rowId };
}
if (tenantId !== undefined) {
where = { ...where, tenantId };
}
const items = await db.log.findMany({
take: pagination.pageSize,
skip: pagination.pageSize * (pagination.page - 1),
where,
include,
});
const totalItems = await db.log.count({
where,
});
return {
items,
pagination: {
page: pagination.page,
pageSize: pagination.pageSize,
totalItems,
totalPages: Math.ceil(totalItems / pagination.pageSize),
},
};
}
export async function getRowLogs(tenantId: string | null, rowId: string): Promise<LogWithDetails[]> {
return await db.log.findMany({
where: {
tenantId,
rowId,
},
include,
orderBy: {
createdAt: "desc",
},
});
}
export async function getRowLogsById(rowId: string): Promise<LogWithDetails[]> {
return await db.log.findMany({
where: {
rowId,
},
include,
orderBy: {
createdAt: "desc",
},
});
}
export async function createLog(request: Request, tenantId: string | null, action: string, details: string) {
const userInfo = await getUserInfo(request);
await db.log.create({
@@ -181,78 +97,6 @@ export async function createManualLog(userId: string, tenantId: string | null, p
});
}
export async function createRowLog(
request: Request,
data: {
tenantId: string | null;
createdByUserId?: string | null;
createdByApiKey?: string | null;
action: string;
entity: EntityWithDetails;
item: RowWithDetails | null;
commentId?: string | null;
details?: string;
}
) {
const log = await db.log.create({
data: {
tenantId: data.tenantId,
userId: data.createdByUserId ?? null,
apiKeyId: data.createdByApiKey ?? null,
url: new URL(request.url).pathname,
rowId: data.item?.id ?? null,
action: data.action,
details: data.details ?? null,
commentId: data.commentId ?? null,
},
});
const apiFormat = ApiHelper.getApiFormat(data.entity, data.item);
await callEntityWebhooks({
logId: log.id,
entityId: data.entity.id,
action: data.action,
body: apiFormat,
request,
});
return log;
}
export async function createManualRowLog(
data: {
tenantId: string | null;
createdByUserId?: string | null;
createdByApiKey?: string | null;
action: string;
entity: EntityWithDetails;
item: RowWithDetails | null;
commentId?: string | null;
},
request?: Request
) {
let details = "";
const log = await db.log.create({
data: {
tenantId: data.tenantId,
userId: data.createdByUserId ?? null,
apiKeyId: data.createdByApiKey ?? null,
url: request ? new URL(request.url).pathname : "",
rowId: data.item?.id ?? null,
action: data.action,
details,
commentId: data.commentId ?? null,
},
});
const apiFormat = ApiHelper.getApiFormat(data.entity, data.item);
await callEntityWebhooks({
logId: log.id,
entityId: data.entity.id,
action: data.action,
body: apiFormat,
// request,
});
return log;
}
export async function createLogLogin(request: Request, user: UserWithoutPassword) {
// eslint-disable-next-line no-console
// console.log({ clientIpAddress: getClientIPAddress(request.headers) });
@@ -1,4 +1,4 @@
import { Group, GroupUser } from "@toolctrl/db/prisma-browser";
import { Group, GroupUser } from "@hivegrid/db/prisma-browser";
import { db } from "~/utils/db.server";
import { UserSimple } from "../users.db.server";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
@@ -17,19 +17,15 @@ vi.mock("../../db.server", () => ({
vi.mock("./roles.db.server", () => ({ getAllRolesNames: vi.fn(), getRoleByName: vi.fn() }));
vi.mock("./rolePermissions.db.server", () => ({ createRolePermission: vi.fn(), getAllRolePermissions: vi.fn() }));
vi.mock("~/utils/cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
vi.mock("~/utils/helpers/PermissionsHelper", () => ({ getEntityPermissions: vi.fn() }));
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: { getFiltersCondition: vi.fn() } }));
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import { db } from "../../db.server";
import { createRolePermission, getAllRolePermissions } from "./rolePermissions.db.server";
import { getAllRolesNames, getRoleByName } from "./roles.db.server";
import { getRoleByName } from "./roles.db.server";
import {
createEntityPermissions,
createPermissions,
deleteEntityPermissions,
deletePermission,
getAllPermissions,
getAllPermissionsIdsAndNames,
@@ -118,6 +114,17 @@ describe("permission persistence", () => {
expect(createRolePermission).toHaveBeenCalledWith({ permissionId: "permission_1", roleId: "role_1" });
});
it("leaves an already-linked role permission untouched instead of recreating it", async () => {
vi.mocked(db.permission.findMany).mockResolvedValue([{ id: "permission_1", name: "admin.users.view" }] as never);
vi.mocked(getAllRolePermissions).mockResolvedValue([{ roleId: "role_1", permission: { name: "admin.users.view" } }] as never);
vi.mocked(getRoleByName).mockResolvedValue({ id: "role_1", name: "SuperAdmin" } as never);
await createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["SuperAdmin"] }]);
expect(db.permission.create).not.toHaveBeenCalled();
expect(createRolePermission).not.toHaveBeenCalled();
});
it("clears the permission lookup cache after creating a previously missing permission", async () => {
vi.mocked(db.permission.findMany).mockResolvedValue([]);
vi.mocked(db.permission.create).mockResolvedValue({ id: "permission_1", name: "admin.users.view" } as never);
@@ -166,42 +173,4 @@ describe("permission persistence", () => {
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.view");
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.delete");
});
it("deletes entity permissions only when generated permission names exist", async () => {
vi.mocked(getEntityPermissions)
.mockResolvedValueOnce([{ name: "entity.view" }, { name: "entity.edit" }] as never)
.mockResolvedValueOnce([] as never);
vi.mocked(db.permission.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
await expect(deleteEntityPermissions({ id: "entity_1" } as never)).resolves.toEqual({ count: 2 });
await expect(deleteEntityPermissions({ id: "entity_1" } as never)).resolves.toBeUndefined();
expect(db.permission.deleteMany).toHaveBeenCalledTimes(1);
expect(db.permission.deleteMany).toHaveBeenCalledWith({
where: { name: { in: ["entity.view", "entity.edit"] } },
});
});
it("creates entity permissions for every generated permission and all app roles", async () => {
vi.mocked(getAllRolesNames).mockResolvedValue([{ id: "role_1", name: "Member" }] as never);
vi.mocked(getEntityPermissions).mockResolvedValue([{ name: "entity.view", description: "View entity" }] as never);
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
vi.mocked(db.permission.findMany).mockResolvedValue([]);
vi.mocked(db.permission.create).mockResolvedValue({ id: "permission_1", name: "entity.view" } as never);
vi.mocked(getRoleByName).mockResolvedValue({ id: "role_1", name: "Member" } as never);
await createEntityPermissions({ id: "entity_1" } as never);
expect(db.permission.create).toHaveBeenCalledWith({
data: {
order: 2,
name: "entity.view",
description: "View entity",
type: "app",
isDefault: true,
entityId: "entity_1",
},
});
expect(createRolePermission).toHaveBeenCalledWith({ permissionId: "permission_1", roleId: "role_1" });
});
});
@@ -1,10 +1,9 @@
import { db } from "../../db.server";
import { Entity, Permission, Role, RolePermission } from "@toolctrl/db/prisma-browser";
import { getAllRolesNames, getRoleByName } from "./roles.db.server";
import { Permission, Role, RolePermission } from "@hivegrid/db/prisma-browser";
import { getRoleByName } from "./roles.db.server";
import { createRolePermission, getAllRolePermissions } from "./rolePermissions.db.server";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
@@ -45,7 +44,6 @@ export async function getAllPermissions(type?: string, filters?: FiltersDto): Pr
orderBy: [{ type: "asc" }, { name: "asc" }],
});
}
export async function getAllPermissionsIdsAndNames(): Promise<{ id: string; name: string }[]> {
return await db.permission.findMany({
select: { id: true, name: true },
@@ -134,7 +132,7 @@ export async function getNextPermissionsOrder(type?: string): Promise<number> {
}
export async function createPermissions(
permissions: { inRoles: string[]; name: string; description: string; type: string; entityId?: string | null }[],
permissions: { inRoles: string[]; name: string; description: string; type: string }[],
fromOrder: number = 0
) {
const allRolePermissions = await getAllRolePermissions();
@@ -155,7 +153,6 @@ export async function createPermissions(
description: data.description,
type: data.type,
isDefault: true,
entityId: data.entityId ?? null,
}));
createdPermissionNames.add(permission.name);
if (existing) {
@@ -184,7 +181,7 @@ export async function createPermissions(
}
}
export async function createPermission(data: { order: number; name: string; description: string; type: string; isDefault: boolean; entityId: string | null }) {
export async function createPermission(data: { order: number; name: string; description: string; type: string; isDefault: boolean }) {
return await db.permission.create({
data,
});
@@ -220,35 +217,3 @@ export async function deletePermission(id: string) {
return item;
});
}
export async function deleteEntityPermissions(entity: Entity) {
const entityPermissions = await getEntityPermissions(entity);
const names = entityPermissions.map((p) => p.name);
if (names.length > 0) {
return await db.permission.deleteMany({
where: {
name: {
in: names,
},
},
});
}
}
export async function createEntityPermissions(entity: Entity) {
const allUserRoles = await getAllRolesNames();
// const assignToAllUserRoles = allUserRoles.filter((f) => f.assignToNewUsers);
const entityPermissions = await getEntityPermissions(entity);
await Promise.all(
entityPermissions.map(async (permission, idx) => {
const entityPermission = {
inRoles: allUserRoles.map((f) => f.name),
name: permission.name,
description: permission.description,
type: "app",
entityId: entity.id,
};
return await createPermissions([entityPermission], allUserRoles.length + idx);
})
);
}
@@ -117,6 +117,21 @@ describe("role persistence", () => {
);
});
it("lists roles with users across every type when no type is provided", async () => {
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
await getAllRolesWithUsers(undefined, undefined, "tenant_1");
expect(dbMock.role.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: { OR: [{ tenantId: null }, { tenantId: "tenant_1" }] },
include: expect.objectContaining({
users: expect.objectContaining({ where: { tenantId: "tenant_1" } }),
}),
})
);
});
it("lists global roles with users when filters do not target a permission", async () => {
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue({ name: { contains: "member" } } as never);
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
@@ -175,6 +190,14 @@ describe("role persistence", () => {
expect(dbMock.role.aggregate).toHaveBeenNthCalledWith(2, { where: {}, _max: { order: true } });
});
it("scopes next role order to the global tenant when no tenant id is given", async () => {
vi.mocked(dbMock.role.aggregate).mockResolvedValueOnce({ _max: { order: 2 } } as never);
await expect(getNextRolesOrder("admin")).resolves.toBe(3);
expect(dbMock.role.aggregate).toHaveBeenCalledWith({ where: { type: "admin", tenantId: null }, _max: { order: true } });
});
it("clears role-list caches after create, update, and delete mutations", async () => {
vi.mocked(dbMock.role.create).mockResolvedValueOnce({ id: "role_1", type: "app" } as never);
vi.mocked(dbMock.role.update).mockResolvedValueOnce({ id: "role_1", type: "admin" } as never);
@@ -1,5 +1,5 @@
import { db } from "../../db.server";
import { Permission, Role, RolePermission, UserRole } from "@toolctrl/db/prisma-browser";
import { Permission, Role, RolePermission, UserRole } from "@hivegrid/db/prisma-browser";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import { UserSimple } from "../users.db.server";
@@ -199,6 +199,19 @@ export async function getTenantAssignableAppRole(id: string, tenantId: string):
});
}
// R-P2b (D01 inline role dropdown): all app roles a tenant may assign — the
// shared assignable defaults plus the tenant's own custom/SHK roles. Mirrors
// the per-role check in getTenantAssignableAppRole above.
export async function getTenantAssignableAppRoles(tenantId: string): Promise<Role[]> {
return await db.role.findMany({
where: {
type: "app",
OR: [{ isDefault: true, tenantId: null }, { tenantId }],
},
orderBy: [{ type: "asc" }, { order: "asc" }],
});
}
export async function getTenantMutableAppRole(id: string, tenantId: string): Promise<RoleWithPermissions | null> {
return await db.role.findFirst({
where: {
@@ -1,81 +0,0 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../db.server", () => ({
db: {
rowPermission: {
create: vi.fn(),
deleteMany: vi.fn(),
findFirst: vi.fn(),
findMany: vi.fn(),
updateMany: vi.fn(),
},
},
}));
import { db } from "../../db.server";
import {
createRowPermission,
deleteRowPermission,
deleteRowPermissionByIdForRow,
getRowPermissionByGroups,
getRowPermissionByRoles,
getRowPermissionByTenant,
getRowPermissionByUsers,
getRowPermissions,
updateRowPermissionForRow,
} from "./rowPermissions.db.server";
const dbMock = vi.mocked(db);
describe("row permission persistence", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("lists row permissions with tenant, role, group, and user display details", async () => {
vi.mocked(dbMock.rowPermission.findMany).mockResolvedValueOnce([{ id: "rp_1" }] as never);
await expect(getRowPermissions("row_1")).resolves.toEqual([{ id: "rp_1" }]);
expect(dbMock.rowPermission.findMany).toHaveBeenCalledWith({
where: { rowId: "row_1" },
include: {
tenant: { select: { id: true, name: true } },
role: { select: { id: true, name: true } },
group: { select: { id: true, name: true } },
user: { select: { id: true, email: true } },
},
});
});
it("looks up row permissions by scoped principals", async () => {
vi.mocked(dbMock.rowPermission.findFirst).mockResolvedValue({ id: "rp_1" } as never);
await getRowPermissionByTenant("row_1", "tenant_1");
await getRowPermissionByGroups("row_1", ["group_1", "group_2"]);
await getRowPermissionByRoles("row_1", ["role_1"]);
await getRowPermissionByUsers("row_1", ["user_1"]);
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(1, { where: { rowId: "row_1", tenantId: "tenant_1" } });
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(2, { where: { rowId: "row_1", groupId: { in: ["group_1", "group_2"] } } });
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(3, { where: { rowId: "row_1", roleId: { in: ["role_1"] } } });
expect(dbMock.rowPermission.findFirst).toHaveBeenNthCalledWith(4, { where: { rowId: "row_1", userId: { in: ["user_1"] } } });
});
it("creates, updates, and deletes row permissions through row-scoped predicates", async () => {
vi.mocked(dbMock.rowPermission.create).mockResolvedValueOnce({ id: "rp_1" } as never);
vi.mocked(dbMock.rowPermission.updateMany).mockResolvedValueOnce({ count: 1 } as never);
vi.mocked(dbMock.rowPermission.deleteMany).mockResolvedValue({ count: 1 } as never);
await expect(createRowPermission({ rowId: "row_1", tenantId: "tenant_1", access: "view" })).resolves.toEqual({ id: "rp_1" });
await expect(updateRowPermissionForRow("row_1", "rp_1", { access: "edit" })).resolves.toEqual({ count: 1 });
await expect(deleteRowPermission("row_1")).resolves.toEqual({ count: 1 });
await expect(deleteRowPermissionByIdForRow("row_1", "rp_1")).resolves.toEqual({ count: 1 });
expect(dbMock.rowPermission.create).toHaveBeenCalledWith({ data: { rowId: "row_1", tenantId: "tenant_1", access: "view" } });
expect(dbMock.rowPermission.updateMany).toHaveBeenCalledWith({ where: { id: "rp_1", rowId: "row_1" }, data: { access: "edit" } });
expect(dbMock.rowPermission.deleteMany).toHaveBeenNthCalledWith(1, { where: { rowId: "row_1" } });
expect(dbMock.rowPermission.deleteMany).toHaveBeenNthCalledWith(2, { where: { id: "rp_1", rowId: "row_1" } });
});
});
@@ -1,102 +0,0 @@
import { RowPermission } from "@toolctrl/db/prisma-browser";
import { db } from "~/utils/db.server";
export type RowPermissionsWithDetails = RowPermission & {
tenant: { id: string; name: string } | null;
role?: { id: string; name: string } | null;
group?: { id: string; name: string } | null;
user?: { id: string; email: string } | null;
};
export async function getRowPermissions(rowId: string): Promise<RowPermissionsWithDetails[]> {
return await db.rowPermission.findMany({
where: {
rowId,
},
include: {
tenant: { select: { id: true, name: true } },
role: { select: { id: true, name: true } },
group: { select: { id: true, name: true } },
user: { select: { id: true, email: true } },
},
});
}
export async function getRowPermissionByTenant(rowId: string, tenantId?: string | null) {
return await db.rowPermission.findFirst({
where: {
rowId,
tenantId,
},
});
}
export async function getRowPermissionByGroups(rowId: string, groups: string[]) {
return await db.rowPermission.findFirst({
where: {
rowId,
groupId: {
in: groups,
},
},
});
}
export async function getRowPermissionByRoles(rowId: string, roles: string[]) {
return await db.rowPermission.findFirst({
where: {
rowId,
roleId: {
in: roles,
},
},
});
}
export async function getRowPermissionByUsers(rowId: string, users: string[]) {
return await db.rowPermission.findFirst({
where: {
rowId,
userId: {
in: users,
},
},
});
}
export async function createRowPermission(data: {
rowId: string;
tenantId?: string | null;
roleId?: string | null;
groupId?: string | null;
userId?: string | null;
public?: boolean | null;
access: string;
}) {
return await db.rowPermission.create({
data,
});
}
export async function updateRowPermissionForRow(rowId: string, id: string, data: { access: string }) {
return await db.rowPermission.updateMany({
where: { id, rowId },
data,
});
}
export async function deleteRowPermission(rowId: string) {
return await db.rowPermission.deleteMany({
where: {
rowId,
},
});
}
export async function deleteRowPermissionByIdForRow(rowId: string, id: string) {
return await db.rowPermission.deleteMany({
where: {
id,
rowId,
},
});
}
@@ -8,6 +8,7 @@ vi.mock("../../db.server", () => ({
count: vi.fn(),
},
role: {
findFirst: vi.fn(),
findMany: vi.fn(),
},
userRole: {
@@ -33,6 +34,7 @@ import {
createUserRoles,
deleteAllUserRoles,
deleteUserRole,
ensureAdminUserRoleByName,
ensureTenantUserAppRoles,
findPermissionByUser,
findUserRolesByIds,
@@ -299,6 +301,32 @@ describe("user role persistence", () => {
await expect(createUserRole("user_1", "role_1", null)).rejects.toBe(error);
});
it("does not grant an admin role by name when no matching admin role exists", async () => {
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce(null);
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
expect(dbMock.role.findFirst).toHaveBeenCalledWith({
where: { name: "SuperAdmin", type: "admin" },
select: { id: true },
});
expect(dbMock.userRole.create).not.toHaveBeenCalled();
expect(clearCacheKey).not.toHaveBeenCalled();
});
it("grants a matching admin role by name with admin scope and invalidates the role cache", async () => {
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce({ id: "role_super_admin" } as never);
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null);
vi.mocked(dbMock.userRole.create).mockResolvedValueOnce({ id: "ur_admin" } as never);
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
expect(dbMock.userRole.create).toHaveBeenCalledWith({
data: { userId: "user_1", roleId: "role_super_admin", tenantId: null },
});
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
});
it("creates, bulk-creates, and deletes user roles while clearing tenant-specific caches", async () => {
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null);
vi.mocked(dbMock.userRole.create).mockResolvedValueOnce({ id: "ur_1" } as never);
@@ -1,4 +1,4 @@
import { Permission, Role, RolePermission, UserRole } from "@toolctrl/db/prisma-browser";
import { Permission, Role, RolePermission, UserRole } from "@hivegrid/db/prisma-browser";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { db } from "../../db.server";
import { cachified, clearCacheKey } from "~/utils/cache.server";
Loaded 100 of 3781 files, more files were not shown because too many files have changed in this diff. Show more