Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -0,0 +1,33 @@
import { beforeAll, describe, expect, it, vi } from "vitest";
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: () => ({
nodeEnv: "test",
routing: {},
sessionSecret: "test-session-secret-that-is-long-enough",
}),
resolveSessionCookiePolicy: () => ({
name: "app_analytics",
httpOnly: true,
path: "/",
sameSite: "lax",
secure: false,
}),
}));
let generateAnalyticsUserId: () => string;
beforeAll(async () => {
({ generateAnalyticsUserId } = await import("./analyticsCookie.server"));
});
describe("analytics identifier", () => {
it("uses a compact 128-bit base64url identifier", () => {
const first = generateAnalyticsUserId();
const second = generateAnalyticsUserId();
expect(first).toMatch(/^[A-Za-z0-9_-]{22}$/);
expect(Buffer.from(first, "base64url")).toHaveLength(16);
expect(second).not.toBe(first);
});
});
@@ -1,6 +1,7 @@
import { createCookieSessionStorage, redirect, Session } from "react-router";
import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@hivegrid/config";
import { randomBytes } from "crypto";
import { safeSessionRedirectTarget } from "./app/SessionRedirectSafety.server";
export type AnalyticsSession = {
userAnalyticsId: string;
@@ -35,7 +36,7 @@ export async function getAnalyticsInfo(request: Request): Promise<AnalyticsSessi
export async function createAnalyticsSession(analyticsSession: AnalyticsSession, redirectTo = "/") {
const session = await storage.getSession();
session.set("userAnalyticsId", analyticsSession.userAnalyticsId);
return redirect(redirectTo, {
return redirect(safeSessionRedirectTarget(redirectTo, webConfig.routing), {
headers: {
"Set-Cookie": await storage.commitSession(session),
},
@@ -51,5 +52,8 @@ export async function destroyAnalyticsSession(session: Session) {
}
export function generateAnalyticsUserId() {
return randomBytes(100).toString("base64");
// 128 bits are sufficient for a non-secret pseudonymous identifier. The
// compact base64url form avoids sending an unnecessary ~110 cookie bytes on
// every authenticated request.
return randomBytes(16).toString("base64url");
}
@@ -1,64 +0,0 @@
import { getDefaultTenantTypes } from "../../db/tenants/tenantTypes.db.server";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import { addTenantTypeToTenant, getTenant } from "../../db/tenants.db.server";
export namespace TenantTypesApi {
export async function setTenantTypes({
tenantId,
subscriptionProduct,
types,
}: {
tenantId: string;
subscriptionProduct?: SubscriptionProductDto;
types?: string[];
}) {
const tenant = await getTenant(tenantId);
if (!tenant) {
return;
}
if (types) {
await Promise.all(
types.map(async (typeId) => {
await addTenantTypeToTenant(tenant.id, { typeId });
})
);
return;
}
const defaultTenantTypes = await getDefaultTenantTypes();
const allTenantTypes = [...defaultTenantTypes, ...(subscriptionProduct?.assignsTenantTypes ?? [])].filter(
(v, i, a) => a.findIndex((t) => t.id === v.id) === i
);
await Promise.all(
allTenantTypes.map(async (tenantType) => {
if (!tenant.types.find((f) => f.id === tenantType.id)) {
await addTenantTypeToTenant(tenant.id, {
typeId: tenantType.id,
});
}
})
);
}
// export async function filterEntities({
// tenant,
// entities,
// entityGroups,
// }: {
// tenant: TenantSimple;
// entities: EntityWithDetails[];
// entityGroups?: EntityGroupWithDetails[];
// }) {
// const tenantTypes = await getAllTenantTypes();
// if (tenantTypes.length > 0) {
// const tenantEntities = await TenantEntitiesApi.getEntities({ inTypes: tenant.types, enabledOnly: true });
// entities = tenantEntities.allEntities;
// let newGroups: EntityGroupWithDetails[] = [];
// entityGroups?.forEach((group) => {
// group.entities = group.entities.filter((f) => entities.some((e) => e.id === f.id));
// if (group.entities.length > 0) {
// newGroups.push(group);
// }
// });
// entityGroups = newGroups;
// }
// }
}
@@ -0,0 +1,210 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext, runWithRlsTransaction } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => ({
createOwnedTenantWithShkDefaults: vi.fn(),
getUser: vi.fn(),
getUserInfo: vi.fn(),
createIdempotentTenantEvent: vi.fn(),
autosubscribeToTrialOrFreePlan: vi.fn(),
postCommitWarn: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
}));
vi.mock("~/domain/tenant-bootstrap/tenantBootstrapService.server", () => ({
createOwnedTenantWithShkDefaults: mocks.createOwnedTenantWithShkDefaults,
}));
vi.mock("~/utils/db/users.db.server", () => ({ getUser: mocks.getUser }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: mocks.getUserInfo }));
vi.mock("~/modules/events/services/.server/EventsService", () => ({
default: { createIdempotentTenantEvent: mocks.createIdempotentTenantEvent },
}));
vi.mock("~/utils/services/.server/pricingService", () => ({
autosubscribeToTrialOrFreePlan: mocks.autosubscribeToTrialOrFreePlan,
}));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: vi.fn(() => ({ warn: mocks.postCommitWarn })),
}));
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`,
}));
import { TenantsApi } from "./TenantsApi";
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const ACCOUNT_EVENT_IDEMPOTENCY_KEY = `tenant-bootstrap:tenant_1:${CREATION_REQUEST_KEY}:account-created`;
describe("TenantsApi.create RLS provisioning", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
const user = {
id: "user_1",
email: "owner@example.test",
firstName: "Ada",
lastName: "Lovelace",
locale: "de",
createdAt: new Date("2026-07-15T08:00:00.000Z"),
defaultTenantId: null,
};
mocks.getUser.mockResolvedValue(user);
mocks.createOwnedTenantWithShkDefaults.mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1" });
return {
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
user: { ...user, defaultTenantId: "tenant_1" },
replayed: false,
};
});
mocks.autosubscribeToTrialOrFreePlan.mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" });
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
});
mocks.createIdempotentTenantEvent.mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_1" });
expect(getRlsExecutionContext()?.transaction).toBeUndefined();
});
});
it("runs replay-safe post-commit work outside any bootstrap or marker transaction", async () => {
const request = new Request("https://admin.example.test/accounts", { method: "POST" });
const result = await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
expect(mocks.createOwnedTenantWithShkDefaults).toHaveBeenCalledWith({
user: expect.objectContaining({ id: "user_1", email: "owner@example.test" }),
name: "Acme",
slug: "acme",
creationRequestKey: CREATION_REQUEST_KEY,
t: expect.any(Function),
});
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
userId: "user_1",
throwOnFailure: true,
idempotencyKey: CREATION_REQUEST_KEY,
})
);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledWith(
expect.objectContaining({
event: "account.created",
tenantId: "tenant_1",
userId: "user_1",
idempotencyKey: ACCOUNT_EVENT_IDEMPOTENCY_KEY,
})
);
expect(mocks.autosubscribeToTrialOrFreePlan.mock.invocationCallOrder[0]).toBeGreaterThan(
mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0]
);
expect(mocks.createIdempotentTenantEvent.mock.invocationCallOrder[0]).toBeGreaterThan(
mocks.createOwnedTenantWithShkDefaults.mock.invocationCallOrder[0]
);
expect(result).toMatchObject({ redirectTo: "/app/acme/dashboard", tenant: { id: "tenant_1" }, user: { id: "user_1" } });
expect(getRlsExecutionContext()).toBeNull();
});
it("does not run post-commit work when the atomic owner bootstrap fails", async () => {
mocks.createOwnedTenantWithShkDefaults.mockRejectedValueOnce(new Error("bootstrap failed"));
const request = new Request("https://admin.example.test/accounts", { method: "POST" });
await expect(
runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
)
).rejects.toThrow("bootstrap failed");
expect(mocks.autosubscribeToTrialOrFreePlan).not.toHaveBeenCalled();
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
});
it("isolates post-commit work from a previously-bound tenant", async () => {
const request = new Request("https://old.example.test/new-account", { method: "POST" });
await runWithRlsContext({ userId: "user_1", tenantId: "tenant_old" }, async () => {
await TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY });
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1", tenantId: "tenant_old" });
});
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce();
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("drops an inherited transaction before dispatching post-commit work", async () => {
const request = new Request("https://app.example.test/new-account", { method: "POST" });
const oldTransaction = {};
await runWithRlsContext({ userId: "user_1" }, () =>
runWithRlsTransaction(oldTransaction, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
)
);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledOnce();
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
it("replays both intrinsically idempotent steps with their original stable keys after response loss", async () => {
const request = new Request("https://app.example.test/new-account", { method: "POST" });
await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
const user = await mocks.getUser();
mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
user: { ...user, defaultTenantId: "tenant_1" },
replayed: true,
});
const replay = await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
expect(replay.replayed).toBe(true);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
expect(mocks.autosubscribeToTrialOrFreePlan.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([
CREATION_REQUEST_KEY,
CREATION_REQUEST_KEY,
]);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent.mock.calls.map(([args]) => args.idempotencyKey)).toEqual([
ACCOUNT_EVENT_IDEMPOTENCY_KEY,
ACCOUNT_EVENT_IDEMPOTENCY_KEY,
]);
});
it("propagates a replayable post-commit failure and completes it on an exact retry", async () => {
const request = new Request("https://app.example.test/new-account", { method: "POST" });
mocks.autosubscribeToTrialOrFreePlan.mockRejectedValueOnce(new Error("billing unavailable"));
await expect(
runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
)
).rejects.toThrow("billing unavailable");
expect(mocks.createIdempotentTenantEvent).not.toHaveBeenCalled();
expect(mocks.postCommitWarn).toHaveBeenCalledWith(
expect.objectContaining({ op: "workspace.postcommit.trial-autosubscribe", tenantId: "tenant_1" }),
expect.stringContaining("Workspace creation committed")
);
const user = await mocks.getUser();
mocks.createOwnedTenantWithShkDefaults.mockResolvedValueOnce({
tenant: { id: "tenant_1", name: "Acme", slug: "acme" },
user: { ...user, defaultTenantId: "tenant_1" },
replayed: true,
});
await runWithRlsContext({ userId: "user_1" }, () =>
TenantsApi.create({ request, name: "Acme", slug: "acme", creationRequestKey: CREATION_REQUEST_KEY })
);
expect(mocks.autosubscribeToTrialOrFreePlan).toHaveBeenCalledTimes(2);
expect(mocks.createIdempotentTenantEvent).toHaveBeenCalledOnce();
});
});
@@ -1,48 +1,119 @@
import { getTranslations } from "~/locale/i18next.server";
import { createTenant } from "../../db/tenants.db.server";
import { getUser, updateUserDefaultTenantId } from "../../db/users.db.server";
import { createOwnedTenantWithShkDefaults } from "~/domain/tenant-bootstrap/tenantBootstrapService.server";
import { getUser } from "../../db/users.db.server";
import { getUserInfo } from "../../session.server";
import { TenantTypesApi } from "./TenantTypesApi";
import EventsService from "../../../modules/events/services/.server/EventsService";
import { AccountCreatedDto } from "~/modules/events/dtos/AccountCreatedDto";
import { autosubscribeToTrialOrFreePlan } from "../../services/.server/pricingService";
import { appPath } from "../../app/CanonicalUrlUtils";
import { getRlsExecutionContext, runWithIsolatedUserRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { createScopedLogger } from "~/utils/logger.server";
const tenantsApiLogger = createScopedLogger("tenants-api");
type WorkspacePostCommitOperation = "account-created-event" | "trial-autosubscribe";
function runWithPostCommitTenantRlsContext<T>(tenantId: string, userId: string, callback: () => T): T {
const current = getRlsExecutionContext();
if (current?.userId === userId && (current.transaction !== undefined || (current.tenantId !== undefined && current.tenantId !== tenantId))) {
return runWithIsolatedUserRlsContext(userId, () => runWithRlsContext({ tenantId, userId }, callback));
}
return runWithRlsContext({ tenantId, userId }, callback);
}
async function runWorkspacePostCommitStep({
operation,
tenantId,
userId,
callback,
}: {
operation: WorkspacePostCommitOperation;
tenantId: string;
userId: string;
callback: () => Promise<unknown>;
}): Promise<void> {
try {
await callback();
} catch (error) {
tenantsApiLogger.warn(
{
op: `workspace.postcommit.${operation}`,
tenantId,
userId,
err: { name: error instanceof Error ? error.name : "Error" },
},
"Workspace creation committed, but a replayable post-commit step failed."
);
throw error;
}
}
export namespace TenantsApi {
export async function create({ request, name, slug }: { request: Request; name: string; slug?: string }) {
export async function create({ request, name, slug, creationRequestKey }: { request: Request; name: string; slug?: string; creationRequestKey: string }) {
const { t } = await getTranslations(request);
let userInfo = await getUserInfo(request);
const userInfo = await getUserInfo(request);
const user = await getUser(userInfo.userId);
if (!user) {
throw new Error("User not found");
throw new CatalogError(foundationErrors.notFound, { resource: "workspace-owner" });
}
if (!name) {
throw new Error("Name is required");
throw new CatalogError(foundationErrors.notFound, { resource: "workspace-creation-input" });
}
const tenant = await createTenant({ name, slug });
const {
tenant,
user: bootstrappedUser,
replayed,
} = await runWithRlsContext({ userId: user.id }, () =>
createOwnedTenantWithShkDefaults({
user,
name,
slug,
creationRequestKey,
t,
})
);
await updateUserDefaultTenantId({ defaultTenantId: tenant.id }, user.id);
await autosubscribeToTrialOrFreePlan({ request, t, tenantId: tenant.id, userId: user.id });
await EventsService.create({
request,
event: "account.created",
tenantId: tenant.id,
userId: user.id,
data: {
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
user: { id: user.id, email: user.email },
} satisfies AccountCreatedDto,
await runWithPostCommitTenantRlsContext(tenant.id, bootstrappedUser.id, async () => {
await runWorkspacePostCommitStep({
operation: "trial-autosubscribe",
tenantId: tenant.id,
userId: bootstrappedUser.id,
callback: () =>
autosubscribeToTrialOrFreePlan({
request,
t,
tenantId: tenant.id,
userId: bootstrappedUser.id,
throwOnFailure: true,
idempotencyKey: creationRequestKey,
}),
});
await runWorkspacePostCommitStep({
operation: "account-created-event",
tenantId: tenant.id,
userId: bootstrappedUser.id,
callback: () =>
EventsService.createIdempotentTenantEvent({
request,
event: "account.created",
tenantId: tenant.id,
userId: bootstrappedUser.id,
idempotencyKey: `tenant-bootstrap:${tenant.id}:${creationRequestKey}:account-created`,
data: {
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
user: { id: bootstrappedUser.id, email: bootstrappedUser.email },
} satisfies AccountCreatedDto,
}),
});
});
await TenantTypesApi.setTenantTypes({ tenantId: tenant.id });
return {
redirectTo: appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" }),
tenant,
user,
user: bootstrappedUser,
replayed,
};
}
}
@@ -0,0 +1,115 @@
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
import { createTwoTierCache, type CacheSerializer, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("api-key-auth-cache");
// Pub/sub is the primary revocation path. The short TTL bounds exposure when a
// replica misses an invalidation while disconnected from Redis.
export const API_KEY_AUTH_CACHE_TTL_SECONDS = 30;
type SerializedApiKeySnapshot = Omit<LegacyApiKeySimple, "expires"> & { expires: string | null };
const apiKeySerializer: CacheSerializer<LegacyApiKeySimple> = {
serialize(value) {
const serialized: SerializedApiKeySnapshot = {
...value,
expires: value.expires?.toISOString() ?? null,
};
return JSON.stringify(serialized);
},
deserialize(raw) {
const value = JSON.parse(raw) as SerializedApiKeySnapshot;
return {
...value,
expires: value.expires ? new Date(value.expires) : null,
};
},
};
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
export function createApiKeyAuthCache(store: SharedStore, options: { now?: () => number } = {}): TwoTierCache<LegacyApiKeySimple> {
return createTwoTierCache<LegacyApiKeySimple>({
store,
namespace: "api-key-auth",
ttlSeconds: API_KEY_AUTH_CACHE_TTL_SECONDS,
l1MaxEntries: 10_000,
l1Now: options.now,
serializer: apiKeySerializer,
pubsubEnabled: pubsubEnabledFromEnv(),
logger: {
warn: (obj, msg) => log.warn(obj, msg),
info: (obj, msg) => log.info(obj, msg),
error: (obj, msg) => log.error(obj, msg),
},
});
}
let cacheSingleton: TwoTierCache<LegacyApiKeySimple> | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
export function getApiKeyAuthCache(): TwoTierCache<LegacyApiKeySimple> {
cacheSingleton ??= createApiKeyAuthCache(getSharedStore());
return cacheSingleton;
}
/**
* Cache an already-verified authorization snapshot. The raw credential is
* neither part of LegacyApiKeySimple nor passed to this module; callers use a
* SHA-256 lookup key so Redis never receives plaintext API keys.
*/
export async function loadCachedApiKeySnapshot(
lookupCacheKey: string,
getFreshValue: () => Promise<LegacyApiKeySimple | null>
): Promise<LegacyApiKeySimple | null> {
const cache = getApiKeyAuthCache();
try {
const cached = await cache.get(lookupCacheKey);
if (cached !== null) return cached;
} catch (error) {
log.warn(
{ op: "api-key-auth-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
"API-key cache read failed; falling back to the database."
);
}
const fresh = await getFreshValue();
if (fresh !== null) {
try {
await cache.set(lookupCacheKey, fresh);
} catch (error) {
log.warn(
{ op: "api-key-auth-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
"API-key cache write failed; continuing with the database result."
);
}
}
return fresh;
}
/** Fail closed after key rotation, revocation, or deletion. */
export async function invalidateApiKeySnapshot(lookupCacheKey: string): Promise<void> {
const cache = getApiKeyAuthCache();
cache.deleteLocal(lookupCacheKey);
await cache.l2.invalidate(lookupCacheKey);
}
export async function subscribeApiKeyAuthCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
subscribeDisposer = await getApiKeyAuthCache().subscribe();
log.info({ namespace: "api-key-auth" }, "API-key authorization cache subscriber started.");
return subscribeDisposer;
}
/** Test seam. */
export function __resetApiKeyAuthCacheForTests(): void {
cacheSingleton = null;
subscribeDisposer = null;
}
@@ -22,7 +22,7 @@ function currentHost(input: SurfaceInput) {
return hostFromUrl(input.serverUrl) ?? hostFromUrl(input.publicBaseUrl);
}
export function isAdminSurface(input: SurfaceInput, pathname: string) {
export function isAdminSurface(input: SurfaceInput, _pathname: string) {
return currentHost(input) === input.routing?.adminAppHost;
}
@@ -1,5 +1,6 @@
import { describe, expect, test } from "vitest";
import { describe, expect, it, test } from "vitest";
import {
getAdminBookingHost,
getCanonicalHostRedirectUrl,
getHostAwareInternalPath,
getHostAwareInternalUrlPath,
@@ -13,6 +14,7 @@ const config: DomainRoutingConfig = {
webAppHost: "app.localhost:3000",
adminAppHost: "admin.localhost:3000",
apiHost: "api.localhost:3000",
portalAppHost: "portal.localhost:3000",
protocol: "http",
};
@@ -29,9 +31,27 @@ describe("HostRouting", () => {
expect(getHostRoutingContext("app.localhost:3000", config)).toBe("app");
expect(getHostRoutingContext("admin.localhost:3000", config)).toBe("admin");
expect(getHostRoutingContext("api.localhost:3000", config)).toBe("api");
expect(getHostRoutingContext("meet.localhost:3000", config)).toBe("booking");
expect(getHostRoutingContext("localhost:3000", config)).toBe("root");
});
it("maps public booking management links without treating the token as a page slug", () => {
expect(getHostAwareInternalPath("/manage/token_1", "booking")).toBe("/meet/manage/token_1");
});
test("maps the dedicated booking host to isolated public routes", () => {
expect(getAdminBookingHost(config)).toBe("meet.localhost:3000");
expect(getHostAwareInternalUrlPath("http://meet.localhost:3000/erstgespraech?date=2026-08-03", config)).toBe("/meet/erstgespraech?date=2026-08-03");
expect(getHostAwareInternalUrlPath("http://meet.localhost:3000/assets/app.js", config)).toBe("/assets/app.js");
expect(
getAdminBookingHost({
...config,
appBaseDomain: "hivegrid.de",
protocol: "https",
})
).toBe("meet.hivegrid.de");
});
test("maps host-aware app paths to canonical internal route paths", () => {
expect(getHostAwareInternalPath("/acme/dashboard", "app")).toBe("/acme/dashboard");
expect(getHostAwareInternalPath("/", "app")).toBe("/app");
@@ -39,19 +59,18 @@ describe("HostRouting", () => {
test("maps app host request URLs without adding removed prefixes", () => {
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/acme/dashboard?tab=activity#events", config)).toBe("/acme/dashboard?tab=activity#events");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/app/acme/dashboard?tab=activity#events", config)).toBe(
"/acme/dashboard?tab=activity#events"
);
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/app/acme/dashboard?tab=activity#events", config)).toBe("/acme/dashboard?tab=activity#events");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/app/acme/dashboard.data?_routes=routes%2Fapp.%24tenant%2Fdashboard", config)).toBe(
"/acme/dashboard.data?_routes=routes%2Fapp.%24tenant%2Fdashboard"
);
});
test("keeps public auth routes on app and admin hosts from becoming tenant routes", () => {
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBe(
"/login?redirectTo=%2Facme%2Fdashboard"
);
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBe("/login?redirectTo=%2Facme%2Fdashboard");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/auth/magic-link", config)).toBe("/auth/magic-link");
// Password-policy banner snooze endpoint: must stay reachable on the app
// host (a /api/* path would be rejected by the host-routing runtime).
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/auth/password-policy-remind", config)).toBe("/auth/password-policy-remind");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/plan-required/acme", config)).toBe("/plan-required/acme");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/subscribe/acme?plan=pro", config)).toBe("/subscribe/acme?plan=pro");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/new-account", config)).toBe("/new-account");
@@ -59,6 +78,8 @@ describe("HostRouting", () => {
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/onboarding/session_123", config)).toBe("/onboarding/session_123");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/feature-disabled?feature=summary", config)).toBe("/feature-disabled?feature=summary");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/postman_collection.json", config)).toBe("/postman_collection.json");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/api/status", config)).toBe("/api/status");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/api/metrics", config)).toBe("/api/metrics");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/sitemap.xml", config)).toBe("/sitemap.xml");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/docs/en", config)).toBe("/docs/en");
expect(getHostAwareInternalUrlPath("http://app.localhost:3000/healthcheck", config)).toBe("/healthcheck");
@@ -72,6 +93,8 @@ describe("HostRouting", () => {
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/onboarding/session_123", config)).toBe("/onboarding/session_123");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/feature-disabled?feature=summary", config)).toBe("/feature-disabled?feature=summary");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/postman_collection.json", config)).toBe("/postman_collection.json");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/api/status", config)).toBe("/api/status");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/api/metrics", config)).toBe("/api/metrics");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/sitemap.xml", config)).toBe("/sitemap.xml");
});
@@ -86,6 +109,9 @@ describe("HostRouting", () => {
test("keeps canonical admin host routes on the admin host", () => {
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/dashboard?tab=users#active", config)).toBe("/dashboard?tab=users#active");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/deploys", config)).toBe("/deploys");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/webhooks?status=failed", config)).toBe("/webhooks?status=failed");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/system", config)).toBe("/system");
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/dashboard.data?_routes=routes%2Fdashboard", config)).toBe(
"/dashboard.data?_routes=routes%2Fdashboard"
);
@@ -109,15 +135,9 @@ describe("HostRouting", () => {
});
test("maps API host request URLs without path double-prefixing and preserves suffixes", () => {
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/health?check=deep#status", config)).toBe(
"/v1/health?check=deep#status"
);
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/v1/health?check=deep#status", config)).toBe(
"/v1/health?check=deep#status"
);
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/api/v1/health?check=deep#status", config)).toBe(
"/v1/health?check=deep#status"
);
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/health?check=deep#status", config)).toBe("/v1/health?check=deep#status");
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/v1/health?check=deep#status", config)).toBe("/v1/health?check=deep#status");
expect(getHostAwareInternalUrlPath("http://api.localhost:3000/api/v1/health?check=deep#status", config)).toBe("/v1/health?check=deep#status");
});
test("maps admin host request URLs without double-prefixing", () => {
@@ -187,6 +207,10 @@ describe("HostRouting", () => {
"http://admin.localhost:3000/dashboard?tab=activity#events"
);
expect(getCanonicalHostRedirectUrl("http://localhost:3000/accounts", config)).toBe("http://admin.localhost:3000/accounts");
expect(getCanonicalHostRedirectUrl("http://localhost:3000/deploys", config)).toBe("http://admin.localhost:3000/deploys");
expect(getCanonicalHostRedirectUrl("http://localhost:3000/jobs", config)).toBe("http://admin.localhost:3000/jobs");
expect(getCanonicalHostRedirectUrl("http://localhost:3000/system", config)).toBe("http://admin.localhost:3000/system");
expect(getCanonicalHostRedirectUrl("http://localhost:3000/webhooks?status=failed", config)).toBe("http://admin.localhost:3000/webhooks?status=failed");
expect(getCanonicalHostRedirectUrl("http://localhost:3000/acme/dashboard?tab=activity#events", config)).toBe(
"http://app.localhost:3000/acme/dashboard?tab=activity#events"
);
@@ -198,6 +222,9 @@ describe("HostRouting", () => {
);
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin/settings?tab=users#active", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin", config)).toBeNull();
// Password-policy banner snooze endpoint: /auth/* is a public web route,
// so the app host must serve it directly instead of redirecting anywhere.
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/auth/password-policy-remind", config)).toBeNull();
});
test("does not redirect a canonical route to itself when adminAppHost equals webAppHost (no 308 loop)", () => {
@@ -219,6 +246,12 @@ describe("HostRouting", () => {
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/accounts/users?filter=active", config)).toBe(
"http://admin.localhost:3000/accounts/users?filter=active"
);
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/deploys", config)).toBe("http://admin.localhost:3000/deploys");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/jobs", config)).toBe("http://admin.localhost:3000/jobs");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/system", config)).toBe("http://admin.localhost:3000/system");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/webhooks?status=failed", config)).toBe("http://admin.localhost:3000/webhooks?status=failed");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/webhooks/email/google", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/webhooks/email/google", config)).toBe("http://app.localhost:3000/webhooks/email/google");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/internal/imports/dry-run", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/dashboard?tab=activity#events", config)).toBe(
"http://admin.localhost:3000/dashboard?tab=activity#events"
@@ -231,8 +264,8 @@ describe("HostRouting", () => {
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/acme/dashboard?tab=activity#events", config)).toBe(
"http://app.localhost:3000/acme/dashboard?tab=activity#events"
);
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/portals/customer", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/widgets", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/internal/ai/chat", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/crm", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/workflow-engine", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/contact", config)).toBe("http://app.localhost:3000/acme/contact");
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/v1/users?cursor=next", config)).toBe("http://api.localhost:3000/v1/users?cursor=next");
@@ -253,17 +286,10 @@ describe("HostRouting", () => {
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/health?check=deep#status", config)).toBe(
"http://api.localhost:3000/v1/health?check=deep#status"
);
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/accounts?cursor=next", config)).toBe(
"http://api.localhost:3000/v1/accounts?cursor=next"
);
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/accounts?cursor=next", config)).toBe("http://api.localhost:3000/v1/accounts?cursor=next");
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/auth/login", config)).toBe("http://api.localhost:3000/v1/auth/login");
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/analytics/events", config)).toBe("http://api.localhost:3000/v1/analytics/events");
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/entities/contact/rows", config)).toBe(
"http://api.localhost:3000/v1/entities/contact/rows"
);
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/api-keys/validate", config)).toBe(
"http://api.localhost:3000/v1/api-keys/validate"
);
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/api-keys/validate", config)).toBe("http://api.localhost:3000/v1/api-keys/validate");
});
test("does not canonicalize unsupported API host aliases", () => {
@@ -272,20 +298,43 @@ describe("HostRouting", () => {
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/workflows/run/workflow_1", config)).toBeNull();
});
test("keeps public root-host routes on the root host", () => {
expect(getCanonicalHostRedirectUrl("http://localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBeNull();
test("moves session-bound root routes to the app host for host-only cookies", () => {
expect(getCanonicalHostRedirectUrl("http://localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBe(
"http://app.localhost:3000/login?redirectTo=%2Facme%2Fdashboard"
);
expect(getCanonicalHostRedirectUrl("http://localhost:3000/invitation/token-1", config)).toBe("http://app.localhost:3000/invitation/token-1");
expect(getCanonicalHostRedirectUrl("http://localhost:3000/auth/admin/login", config)).toBe("http://admin.localhost:3000/auth/admin/login");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/auth/admin/callback?code=1", config)).toBe(
"http://admin.localhost:3000/auth/admin/callback?code=1"
);
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/auth/session-handoff?code=opaque", config)).toBe(
"http://app.localhost:3000/auth/session-handoff?code=opaque"
);
});
test("keeps the pending login MFA route on the host that issued its host-only cookie", () => {
expect(getHostAwareInternalUrlPath("http://admin.localhost:3000/login-mfa", config)).toBe("/login-mfa");
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/login-mfa", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/login-mfa", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/login-mfa", config)).toBe("http://app.localhost:3000/login-mfa");
});
test("redirects public web routes away from the API host", () => {
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/login?redirectTo=%2Facme%2Fdashboard", config)).toBe(
"http://app.localhost:3000/login?redirectTo=%2Facme%2Fdashboard"
);
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/contacts", config)).toBe("http://app.localhost:3000/contacts");
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/healthcheck", config)).toBe("http://app.localhost:3000/healthcheck");
});
test("redirects app-host reserved admin slugs instead of treating them as tenants", () => {
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/crm/dashboard", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/accounts/users", config)).toBe("http://admin.localhost:3000/accounts/users");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/knowledge-base/articles", config)).toBe(
"http://admin.localhost:3000/knowledge-base/articles"
);
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/help-desk/tickets", config)).toBe("http://admin.localhost:3000/help-desk/tickets");
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/incoming-leads-board", config)).toBe("http://admin.localhost:3000/incoming-leads-board");
});
test("does not canonicalize disabled plugin route trees to active hosts", () => {
@@ -296,17 +345,15 @@ describe("HostRouting", () => {
expect(getCanonicalHostRedirectUrl("http://localhost:3000/workflows/run/workflow_1", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin/internal/ai/chat", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/admin/__workflows/jobs", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/knowledge-base/articles", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/help/getting-started", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/mcp", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/help/getting-started", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/mcp", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/internal/ai/chat", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://api.localhost:3000/__workflows/jobs", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/knowledge-base/articles", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://app.localhost:3000/acme/internal/ai/chat", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/crm", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/__widgets/widget_1", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/workflow-engine", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/acme/internal/ai/chat", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://admin.localhost:3000/__workflows/jobs", config)).toBeNull();
expect(getCanonicalHostRedirectUrl("http://localhost:3000/acme/internal/ai/chat", config)).toBeNull();
@@ -2,6 +2,7 @@ import { getDomainRoutingConfig, hostMatches, normalizeHost, type DomainRoutingC
import { adminPath, apiPath, appPath } from "./CanonicalUrlUtils";
import {
canonicalAdminRouteSlugs,
canonicalAdminRouteExactPaths,
disabledPluginRouteSlugs,
isPublicWebRoutePath,
isWebRoutePath,
@@ -11,7 +12,7 @@ import {
reservedTenantRouteSlugs,
} from "./PublicRouteSegments";
export type HostRoutingContext = "app" | "admin" | "api" | "root" | "unknown";
export type HostRoutingContext = "app" | "admin" | "api" | "booking" | "root" | "unknown";
type UrlInput = string | URL | Request;
export function getHostRoutingContext(host: string | undefined, config: DomainRoutingConfig = getDomainRoutingConfig()): HostRoutingContext {
@@ -24,6 +25,9 @@ export function getHostRoutingContext(host: string | undefined, config: DomainRo
if (hostMatches(host, config.apiHost)) {
return "api";
}
if (hostMatches(host, getAdminBookingHost(config))) {
return "booking";
}
if (hostMatches(host, config.appBaseDomain)) {
return "root";
}
@@ -40,6 +44,18 @@ export function getHostAwareInternalPath(pathname: string, context: HostRoutingC
return pathname.startsWith("/") ? pathname : `/${pathname}`;
}
if (context === "booking") {
const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
if (isBookingStaticAssetPath(normalized) || pathMatchesRoutePrefix(normalized, "/meet")) {
return normalized;
}
if (pathMatchesRoutePrefix(normalized, "/manage")) {
return `/meet${normalized}`;
}
const slug = trimPath(normalized);
return slug ? `/meet/${slug}` : "/meet";
}
if (context === "admin" && isCanonicalAdminHostRoute(pathname)) {
return pathname.startsWith("/") ? pathname : `/${pathname}`;
}
@@ -124,6 +140,17 @@ export function isCanonicalHostForContext(
return getHostRoutingContext(normalizedHost, config) === context;
}
export function getAdminBookingHost(
config: DomainRoutingConfig = getDomainRoutingConfig()
): string {
const base = new URL(`${config.protocol}://${config.appBaseDomain}`);
const hostname =
base.hostname === "localhost" || base.hostname.endsWith(".localhost")
? "meet.localhost"
: `meet.${base.hostname}`;
return base.port ? `${hostname}:${base.port}` : hostname;
}
function trimPath(pathname: string) {
return pathname.replace(/^\/+|\/+$/g, "");
}
@@ -137,6 +164,20 @@ function isFrameworkInternalRoute(pathname: string) {
return normalizedPathname === "/__manifest";
}
function isBookingStaticAssetPath(pathname: string) {
return (
["/assets/", "/fonts/", "/images/", "/locales/"].some((prefix) =>
pathname.startsWith(prefix)
) ||
[
"/favicon.ico",
"/favicon.svg",
"/favicon-32x32.png",
"/site.webmanifest",
].includes(pathname)
);
}
const activeWebInternalRoutePrefixes = ["/internal/imports/dry-run"] as const;
function isActiveWebInternalRoute(pathname: string) {
@@ -152,6 +193,9 @@ export function isCanonicalAdminHostRoute(pathname: string) {
if (isDisabledAdminHostRoute(routePathname)) {
return false;
}
if ((canonicalAdminRouteExactPaths as readonly string[]).includes(routePathname)) {
return true;
}
const firstSegment = trimPath(routePathname).split("/")[0];
return Boolean(firstSegment && (canonicalAdminRouteSlugs as readonly string[]).includes(firstSegment));
}
@@ -211,6 +255,18 @@ function getRootHostCanonicalRedirect(pathname: string, context: HostRoutingCont
}
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
if (isAdminAuthenticationRoute(normalizedPathname)) {
return {
origin: `${config.protocol}://${config.adminAppHost}`,
pathname: normalizedPathname,
};
}
if (isSessionBoundPublicRoute(normalizedPathname)) {
return {
origin: `${config.protocol}://${config.webAppHost}`,
pathname: normalizedPathname,
};
}
if (isLegacyApiV1HostRoute(normalizedPathname)) {
return {
origin: `${config.protocol}://${config.apiHost}`,
@@ -248,6 +304,13 @@ function getRootHostCanonicalRedirect(pathname: string, context: HostRoutingCont
};
}
if (isCanonicalAppWebhookSubroute(normalizedPathname)) {
return {
origin: `${config.protocol}://${config.webAppHost}`,
pathname: normalizedPathname,
};
}
if (isCanonicalAdminHostRoute(normalizedPathname)) {
return {
origin: `${config.protocol}://${config.adminAppHost}`,
@@ -274,19 +337,7 @@ function isDisabledPluginHostRoute(pathname: string) {
const disabledAdminHostRoutePrefixes = ["/__workflows", "/internal/ai", "/internal/api/__workflows", "/internal/api/workflows", "/workflows"] as const;
const disabledTenantHostRouteChildPrefixes = [
"/__portals",
"/__widgets",
"/__workflows",
"/chat",
"/crm",
"/email-marketing",
"/internal/ai",
"/portals",
"/sites",
"/widgets",
"/workflow-engine",
] as const;
const disabledTenantHostRouteChildPrefixes = ["/__workflows", "/chat", "/crm", "/email-marketing", "/internal/ai", "/workflow-engine"] as const;
function isDisabledAdminHostRoute(pathname: string) {
const routePathname = normalizeRoutePath(pathname);
@@ -329,6 +380,13 @@ function getCrossHostCanonicalRedirect(pathname: string, context: HostRoutingCon
};
}
if (isAppOnlySessionRoute(normalizedPathname) && context !== "app") {
return {
origin: `${config.protocol}://${config.webAppHost}`,
pathname: normalizedPathname,
};
}
if (context === "api" && isUnversionedApiHostAlias(normalizedPathname)) {
return {
origin: `${config.protocol}://${config.apiHost}`,
@@ -336,14 +394,21 @@ function getCrossHostCanonicalRedirect(pathname: string, context: HostRoutingCon
};
}
if ((normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname)) && context === "api" && !isApiOperationalRoute(normalizedPathname)) {
if (isAdminAuthenticationRoute(normalizedPathname) && context !== "admin") {
return {
origin: `${config.protocol}://${config.adminAppHost}`,
pathname: normalizedPathname,
};
}
if ((normalizedPathname === "/" || isWebRoutePath(normalizedPathname)) && context === "api" && !isApiOperationalRoute(normalizedPathname)) {
return {
origin: `${config.protocol}://${config.webAppHost}`,
pathname: normalizedPathname,
};
}
if (normalizedPathname === "/" || isPublicWebRoutePath(normalizedPathname) || isFrameworkInternalRoute(normalizedPathname)) {
if (normalizedPathname === "/" || isWebRoutePath(normalizedPathname) || isFrameworkInternalRoute(normalizedPathname)) {
return null;
}
@@ -360,6 +425,15 @@ function getCrossHostCanonicalRedirect(pathname: string, context: HostRoutingCon
};
}
if (isCanonicalAppWebhookSubroute(normalizedPathname)) {
return context === "app"
? null
: {
origin: `${config.protocol}://${config.webAppHost}`,
pathname: normalizedPathname,
};
}
if (isCanonicalApiHostRoute(normalizedPathname) && context !== "api") {
return {
origin: `${config.protocol}://${config.apiHost}`,
@@ -384,6 +458,34 @@ function getCrossHostCanonicalRedirect(pathname: string, context: HostRoutingCon
return null;
}
function isAdminAuthenticationRoute(pathname: string) {
return pathMatchesRoutePrefix(normalizeRoutePath(pathname), "/auth/admin");
}
function isAppOnlySessionRoute(pathname: string) {
return pathMatchesRoutePrefix(normalizeRoutePath(pathname), "/auth/session-handoff");
}
const sessionBoundPublicRoutePrefixes = [
"/auth/magic-link",
"/auth/session-handoff",
"/forgot-password",
"/invitation",
"/login",
"/login-mfa",
"/new-account",
"/register",
"/reset",
"/select-tenant",
"/signup",
"/verify",
] as const;
function isSessionBoundPublicRoute(pathname: string) {
const routePathname = normalizeRoutePath(pathname);
return sessionBoundPublicRoutePrefixes.some((prefix) => pathMatchesRoutePrefix(routePathname, prefix));
}
function getHostAwareInternalPathWithoutDoublePrefix(pathname: string, context: HostRoutingContext): string {
const normalizedPathname = pathname.startsWith("/") ? pathname : `/${pathname}`;
if (context === "app" && isLegacyAppHostRoute(normalizedPathname)) {
@@ -410,15 +512,7 @@ function isCanonicalTenantHostRoute(pathname: string) {
return true;
}
const canonicalTenantSegments = new Set([
"$entity",
"apps",
"dashboard",
"g",
"internal",
"notifications",
"settings",
]);
const canonicalTenantSegments = new Set(["$entity", "apps", "dashboard", "g", "internal", "notifications", "settings"]);
if ((reservedTenantChildRouteSlugs as readonly string[]).includes(secondSegment) && !canonicalTenantSegments.has(secondSegment)) {
return false;
}
@@ -426,6 +520,11 @@ function isCanonicalTenantHostRoute(pathname: string) {
return Boolean(secondSegment && (canonicalTenantSegments.has(secondSegment) || !secondSegment.startsWith("__")));
}
function isCanonicalAppWebhookSubroute(pathname: string) {
const routePathname = normalizeRoutePath(pathname);
return routePathname !== "/webhooks" && pathMatchesRoutePrefix(routePathname, "/webhooks");
}
function isUnversionedApiHostAlias(pathname: string) {
if (isApiOperationalRoute(pathname) || isCanonicalApiHostRoute(pathname) || isFrameworkInternalRoute(pathname)) {
return false;
@@ -481,7 +580,12 @@ function getHostFromInput(input: UrlInput, url: URL, config: DomainRoutingConfig
export function getRequestRoutingHost(request: Request, url: URL = new URL(request.url), config: DomainRoutingConfig = getDomainRoutingConfig()) {
const directHost = request.headers.get("host") ?? url.host;
const directContext = getHostRoutingContext(directHost, config);
if (directContext === "app" || directContext === "admin" || directContext === "api") {
if (
directContext === "app" ||
directContext === "admin" ||
directContext === "api" ||
directContext === "booking"
) {
return directHost;
}
@@ -1,11 +1,5 @@
import { describe, expect, test } from "vitest";
import {
isAbsoluteWebHostPath,
isPublicWebRoutePath,
isWebRoutePath,
reservedTenantChildRouteSlugs,
reservedTenantRouteSlugs,
} from "./PublicRouteSegments";
import { isAbsoluteWebHostPath, isPublicWebRoutePath, isWebRoutePath, reservedTenantChildRouteSlugs, reservedTenantRouteSlugs } from "./PublicRouteSegments";
describe("public route segments", () => {
test("classifies top-level public routes that must not become tenant slugs", () => {
@@ -14,6 +8,7 @@ describe("public route segments", () => {
"/healthcheck",
"/healthz",
"/readyz",
"/login-mfa",
"/mfa-challenge",
"/signup",
"/unauthorized/foo",
@@ -53,7 +48,32 @@ 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", "signup"]));
expect(reservedTenantChildRouteSlugs).toEqual(expect.arrayContaining(["settings", "crm", "email-marketing", "workflow-engine", "g", "chat", "internal", "widgets"]));
expect(reservedTenantRouteSlugs).toEqual(
expect.arrayContaining([
"accounts",
"analytics",
"api",
"crm",
"docs",
"help",
"healthcheck",
"healthz",
"readyz",
"swagger",
"mcp",
"login-mfa",
"mfa-challenge",
"signup",
"webhooks",
"jobs",
"system",
"deploys",
"help-desk",
"knowledge-base",
"incoming-leads-board",
])
);
expect(reservedTenantChildRouteSlugs).toEqual(expect.arrayContaining(["settings", "crm", "email-marketing", "workflow-engine", "g", "chat", "internal"]));
expect(reservedTenantChildRouteSlugs).not.toEqual(expect.arrayContaining(["__portals", "__widgets", "portals", "sites", "widgets"]));
});
});
@@ -1,5 +1,5 @@
export const publicWebRouteExactPaths = ["/sitemap.xml"] as const;
export const protectedWebRouteExactPaths = ["/postman_collection.json"] as const;
export const publicWebRouteExactPaths = ["/api/status", "/sitemap.xml"] as const;
export const protectedWebRouteExactPaths = ["/api/metrics", "/postman_collection.json"] as const;
export const publicWebRoutePrefixes = [
"/401",
@@ -15,6 +15,7 @@ export const publicWebRoutePrefixes = [
"/healthz",
"/invitation/",
"/login",
"/login-mfa",
"/logout",
"/mfa-challenge",
"/new-account",
@@ -35,21 +36,33 @@ export const publicWebRoutePrefixes = [
"/verify/",
] as const;
export const protectedWebRoutePrefixes = ["/swagger"] as const;
// "/avatars/" is the authorized media proxy for profile pictures (AD-23). It has
// to resolve as a root web route on the app host as well as the admin host, and
// listing it here also reserves the slug against tenant names.
export const protectedWebRoutePrefixes = ["/avatars/", "/swagger"] as const;
export const absoluteWebHostRoutePrefixes = publicWebRoutePrefixes;
export const canonicalAdminRouteSlugs = [
"accounts",
"admin-users",
"analytics",
"api",
"audit",
"audit-trails",
"dashboard",
"deploys",
"email-sequences",
"entities",
"events",
"feature-flags",
"health",
"help-desk",
"internal",
"incoming-leads-board",
"jobs",
"knowledge-base",
"kwp-contracts",
"leads",
"marketing-funnels",
"marketing-integrations",
"marketing-leads",
@@ -57,23 +70,16 @@ export const canonicalAdminRouteSlugs = [
"mfa-challenge",
"notifications",
"onboarding",
"sales",
"settings",
"select-tenant",
"support",
"system",
] as const;
export const disabledPluginRouteSlugs = [
"ai",
"chat",
"crm",
"email-marketing",
"help",
"help-desk",
"knowledge-base",
"mcp",
"portals",
"prompts",
"workflow-engine",
] as const;
export const canonicalAdminRouteExactPaths = ["/webhooks"] as const;
export const disabledPluginRouteSlugs = ["ai", "chat", "crm", "email-marketing", "help", "mcp", "prompts", "workflow-engine"] as const;
export const reservedTenantRouteSlugs = [
"admin",
@@ -83,6 +89,7 @@ export const reservedTenantRouteSlugs = [
"undefined",
"v1",
...canonicalAdminRouteSlugs,
...canonicalAdminRouteExactPaths.flatMap((path) => path.split("/").filter(Boolean).slice(0, 1)),
...disabledPluginRouteSlugs,
...new Set(
[...publicWebRoutePrefixes, ...protectedWebRoutePrefixes]
@@ -93,8 +100,6 @@ export const reservedTenantRouteSlugs = [
] as const;
export const reservedTenantChildRouteSlugs = [
"__portals",
"__widgets",
"__workflows",
"chat",
"crm",
@@ -103,10 +108,7 @@ export const reservedTenantChildRouteSlugs = [
"g",
"internal",
"notifications",
"portals",
"settings",
"sites",
"widgets",
"workflow-engine",
] as const;
@@ -1,51 +1 @@
type SafeRedirectOptions = {
fallbackPath?: string;
};
export function safeRedirectPath(value: string | null | undefined, options: SafeRedirectOptions = {}) {
const fallbackPath = options.fallbackPath ?? "/";
if (!value) {
return fallbackPath;
}
const trimmed = value.trim();
if (
!trimmed ||
!trimmed.startsWith("/") ||
trimmed.startsWith("//") ||
trimmed.includes("\\") ||
/[\u0000-\u001f\u007f]/.test(trimmed) ||
/%(?:2f|5c|00|0a|0d)/i.test(trimmed)
) {
return fallbackPath;
}
try {
const parsed = new URL(trimmed, "http://local.invalid");
if (isRemovedRoutePath(parsed.pathname)) {
return fallbackPath;
}
return `${parsed.pathname}${parsed.search}${parsed.hash}`;
} catch {
return fallbackPath;
}
}
export function safeRedirectPathFromRequest(request: Request, value: string | null | undefined) {
const url = new URL(request.url);
return safeRedirectPath(value, { fallbackPath: `${url.pathname}${url.search}${url.hash}` });
}
export function isRemovedRoutePath(pathname: string) {
const normalizedPathname = pathname.replace(/\/+$/g, "") || "/";
return (
normalizedPathname === "/app" ||
normalizedPathname.startsWith("/app/") ||
normalizedPathname === "/admin" ||
normalizedPathname.startsWith("/admin/") ||
normalizedPathname === "/api" ||
normalizedPathname.startsWith("/api/") ||
normalizedPathname === "/v1" ||
normalizedPathname.startsWith("/v1/")
);
}
export { isRemovedRoutePath, safeRedirectPath, safeRedirectPathFromRequest } from "./RedirectSafety";
@@ -0,0 +1,51 @@
type SafeRedirectOptions = {
fallbackPath?: string;
};
export function safeRedirectPath(value: string | null | undefined, options: SafeRedirectOptions = {}) {
const fallbackPath = options.fallbackPath ?? "/";
if (!value) {
return fallbackPath;
}
const trimmed = value.trim();
if (
!trimmed ||
!trimmed.startsWith("/") ||
trimmed.startsWith("//") ||
trimmed.includes("\\") ||
/[\u0000-\u001f\u007f]/.test(trimmed) ||
/%(?:2f|5c|00|0a|0d)/i.test(trimmed)
) {
return fallbackPath;
}
try {
const parsed = new URL(trimmed, "http://local.invalid");
if (isRemovedRoutePath(parsed.pathname)) {
return fallbackPath;
}
return `${parsed.pathname}${parsed.search}${parsed.hash}`;
} catch {
return fallbackPath;
}
}
export function safeRedirectPathFromRequest(request: Request, value: string | null | undefined) {
const url = new URL(request.url);
return safeRedirectPath(value, { fallbackPath: `${url.pathname}${url.search}${url.hash}` });
}
export function isRemovedRoutePath(pathname: string) {
const normalizedPathname = pathname.replace(/\/+$/g, "") || "/";
return (
normalizedPathname === "/app" ||
normalizedPathname.startsWith("/app/") ||
normalizedPathname === "/admin" ||
normalizedPathname.startsWith("/admin/") ||
normalizedPathname === "/api" ||
normalizedPathname.startsWith("/api/") ||
normalizedPathname === "/v1" ||
normalizedPathname.startsWith("/v1/")
);
}
@@ -0,0 +1,29 @@
import { describe, expect, it } from "vitest";
import { safeSessionRedirectTarget } from "./SessionRedirectSafety.server";
const routing = {
protocol: "https" as const,
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
};
describe("safeSessionRedirectTarget", () => {
it("keeps safe relative and canonical app/admin redirects", () => {
expect(safeSessionRedirectTarget("/acme/dashboard?tab=tasks#today", routing)).toBe("/acme/dashboard?tab=tasks#today");
expect(safeSessionRedirectTarget("https://app.example.test/acme/dashboard", routing)).toBe("https://app.example.test/acme/dashboard");
expect(safeSessionRedirectTarget("https://admin.example.test/dashboard?tab=audit", routing)).toBe("https://admin.example.test/dashboard?tab=audit");
});
it.each([
"https://evil.example/phish",
"https://app.example.test.evil.example/phish",
"https://user:password@app.example.test/phish",
"//evil.example/phish",
"javascript:alert(1)",
"/%2f%2fevil.example/phish",
"/dashboard%0d%0aLocation:%20//evil.example",
])("falls back to root for an unsafe session redirect: %s", (value) => {
expect(safeSessionRedirectTarget(value, routing)).toBe("/");
});
});
@@ -0,0 +1,42 @@
import type { DomainRoutingConfig } from "@hivegrid/config";
import { safeRedirectPath } from "./RedirectSafety.server";
type SessionRedirectRouting = Pick<DomainRoutingConfig, "protocol" | "webAppHost" | "adminAppHost">;
/**
* Session issuance may redirect between the canonical app and admin hosts,
* but never to an arbitrary origin supplied by a form/query parameter.
*/
export function safeSessionRedirectTarget(value: string | null | undefined, routing: SessionRedirectRouting): string {
const trimmed = value?.trim();
if (!trimmed) {
return "/";
}
if (trimmed.startsWith("/")) {
return safeRedirectPath(trimmed);
}
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
return "/";
}
if (parsed.username || parsed.password) {
return "/";
}
const allowedOrigins = new Set([
new URL(`${routing.protocol}://${routing.webAppHost}`).origin,
new URL(`${routing.protocol}://${routing.adminAppHost}`).origin,
]);
if (!allowedOrigins.has(parsed.origin)) {
return "/";
}
const safePath = safeRedirectPath(`${parsed.pathname}${parsed.search}${parsed.hash}`);
return `${parsed.origin}${safePath}`;
}
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vitest";
import { hasTenantSubscriptionAccess, requiresTenantSubscriptionActivation, type TenantSubscriptionAccessState } from "./SubscriptionAccess";
const NOW = new Date("2026-08-03T12:00:00.000Z");
function baseProduct(overrides: Record<string, unknown> = {}) {
return {
cancelledAt: null,
currentPeriodStart: new Date("2026-08-01T00:00:00.000Z"),
endsAt: null,
subscriptionProduct: { kind: "base_plan" },
...overrides,
};
}
function subscription(overrides: Record<string, unknown> = {}): TenantSubscriptionAccessState {
return {
status: "active",
trialStartsAt: null,
trialEndsAt: null,
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
products: [baseProduct()],
...overrides,
} as TenantSubscriptionAccessState;
}
describe("tenant subscription access", () => {
it("allows an active base-plan subscription in its effective period", () => {
expect(hasTenantSubscriptionAccess(subscription(), NOW)).toBe(true);
});
it("allows a bounded trial only while its real Prisma window is active", () => {
expect(
hasTenantSubscriptionAccess(
subscription({
status: "trial",
products: [],
trialStartsAt: new Date("2026-08-01T00:00:00.000Z"),
trialEndsAt: new Date("2026-08-10T00:00:00.000Z"),
}),
NOW
)
).toBe(true);
expect(hasTenantSubscriptionAccess(subscription({ status: "trial", products: [], trialEndsAt: NOW }), NOW)).toBe(false);
expect(hasTenantSubscriptionAccess(subscription({ status: "trial", products: [], trialEndsAt: null }), NOW)).toBe(false);
expect(
hasTenantSubscriptionAccess(
subscription({
status: "trial",
products: [],
trialStartsAt: new Date("2026-08-04T00:00:00.000Z"),
trialEndsAt: new Date("2026-08-10T00:00:00.000Z"),
}),
NOW
)
).toBe(false);
});
it.each(["past_due", "cancelled", "canceled", "frozen", "terminated"])("denies a %s subscription even with a base plan", (status) => {
expect(hasTenantSubscriptionAccess(subscription({ status }), NOW)).toBe(false);
});
it.each([
["past-due marker", { pastDueSince: NOW }],
["frozen marker", { frozenAt: NOW }],
["cancelled marker", { cancelledAt: NOW }],
])("denies an inconsistent active subscription carrying a %s", (_label, marker) => {
expect(hasTenantSubscriptionAccess(subscription(marker), NOW)).toBe(false);
});
it("denies add-on-only, cancelled, ended, and not-yet-effective products", () => {
expect(
hasTenantSubscriptionAccess(subscription({ products: [baseProduct({ subscriptionProduct: { kind: "recurring_add_on" } })] }), NOW)
).toBe(false);
expect(hasTenantSubscriptionAccess(subscription({ products: [baseProduct({ cancelledAt: NOW })] }), NOW)).toBe(false);
expect(hasTenantSubscriptionAccess(subscription({ products: [baseProduct({ endsAt: NOW })] }), NOW)).toBe(false);
expect(
hasTenantSubscriptionAccess(subscription({ products: [baseProduct({ currentPeriodStart: new Date("2026-08-04T00:00:00.000Z") })] }), NOW)
).toBe(false);
});
it("fails closed for malformed dates and drives the activation gate", () => {
const malformed = subscription({ products: [baseProduct({ endsAt: "not-a-date" })] });
expect(hasTenantSubscriptionAccess(malformed, NOW)).toBe(false);
expect(requiresTenantSubscriptionActivation(true, malformed)).toBe(true);
expect(requiresTenantSubscriptionActivation(false, malformed)).toBe(false);
});
});
@@ -0,0 +1,62 @@
type SubscriptionAccessDate = Date | string | null | undefined;
type TenantSubscriptionProductAccessState = {
readonly cancelledAt?: SubscriptionAccessDate;
readonly currentPeriodStart?: SubscriptionAccessDate;
readonly endsAt?: SubscriptionAccessDate;
readonly subscriptionProduct?: { readonly kind?: string | null } | null;
};
export type TenantSubscriptionAccessState =
| {
readonly status?: string | null;
readonly trialStartsAt?: SubscriptionAccessDate;
readonly trialEndsAt?: SubscriptionAccessDate;
readonly pastDueSince?: SubscriptionAccessDate;
readonly frozenAt?: SubscriptionAccessDate;
readonly cancelledAt?: SubscriptionAccessDate;
readonly products?: readonly TenantSubscriptionProductAccessState[] | null;
}
| null
| undefined;
function timestamp(value: SubscriptionAccessDate): number | null {
if (value === null || value === undefined) return null;
const parsed = new Date(value).getTime();
return Number.isFinite(parsed) ? parsed : Number.NaN;
}
function isValidOptionalTimestamp(value: number | null): boolean {
return value === null || Number.isFinite(value);
}
function hasTerminalBillingMarker(subscription: NonNullable<TenantSubscriptionAccessState>): boolean {
return subscription.pastDueSince != null || subscription.frozenAt != null || subscription.cancelledAt != null;
}
function hasActiveBasePlan(subscription: NonNullable<TenantSubscriptionAccessState>, nowMs: number): boolean {
if (subscription.status?.trim().toLowerCase() !== "active" || hasTerminalBillingMarker(subscription)) return false;
return (subscription.products ?? []).some((product) => {
if (product.subscriptionProduct?.kind !== "base_plan" || product.cancelledAt != null) return false;
const startsAt = timestamp(product.currentPeriodStart);
const endsAt = timestamp(product.endsAt);
return isValidOptionalTimestamp(startsAt) && isValidOptionalTimestamp(endsAt) && (startsAt === null || startsAt <= nowMs) && (endsAt === null || endsAt > nowMs);
});
}
function hasActiveTrial(subscription: NonNullable<TenantSubscriptionAccessState>, nowMs: number): boolean {
if (subscription.status?.trim().toLowerCase() !== "trial" || hasTerminalBillingMarker(subscription)) return false;
const startsAt = timestamp(subscription.trialStartsAt);
const endsAt = timestamp(subscription.trialEndsAt);
return isValidOptionalTimestamp(startsAt) && endsAt !== null && Number.isFinite(endsAt) && (startsAt === null || startsAt <= nowMs) && endsAt > nowMs;
}
export function hasTenantSubscriptionAccess(subscription: TenantSubscriptionAccessState, now = new Date()): boolean {
if (!subscription || !Number.isFinite(now.getTime())) return false;
return hasActiveBasePlan(subscription, now.getTime()) || hasActiveTrial(subscription, now.getTime());
}
export function requiresTenantSubscriptionActivation(subscriptionRequired: boolean, subscription: TenantSubscriptionAccessState): boolean {
return subscriptionRequired && !hasTenantSubscriptionAccess(subscription);
}
@@ -0,0 +1,49 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { featureGateRegistry } from "@hivegrid/entitlements";
import { getSubscriptionFeatureBadge, getSubscriptionFeatureTitle, getSubscriptionFeatureTitleKey } from "./SubscriptionFeatureText";
function localeCatalog(locale: "de" | "en") {
const repositoryRoot = process.cwd();
return JSON.parse(fs.readFileSync(path.join(repositoryRoot, `apps/web/public/locales/${locale}/translations.json`), "utf8")) as {
admin?: { connectors?: { feature?: Record<string, string> } };
};
}
describe("subscription feature text", () => {
it("resolves known feature names through their stable catalog key", () => {
expect(getSubscriptionFeatureTitleKey({ name: "workflow-engine", title: "Workflows" })).toBe("admin.connectors.feature.workflow-engine");
expect(
getSubscriptionFeatureTitle((key) => (key === "admin.connectors.feature.workflow-engine" ? "Workflow-Engine" : key), {
name: "workflow-engine",
title: "Workflows",
})
).toBe("Workflow-Engine");
});
it("keeps custom feature copy verbatim without treating it as a translation key", () => {
const t = vi.fn((key: string) => `translated:${key}`);
const feature = { name: "tenant-custom-report", title: "Monatsreport für Nord" };
expect(getSubscriptionFeatureTitleKey(feature)).toBe(feature.title);
expect(getSubscriptionFeatureTitle(t, feature)).toBe(feature.title);
expect(t).not.toHaveBeenCalled();
});
it("falls back to the persisted legacy title when a known catalog entry cannot be loaded", () => {
expect(getSubscriptionFeatureTitle((key) => key, { name: "tasks", title: "Tasks" })).toBe("Tasks");
});
it("localizes only canonical system badges and preserves customized badges", () => {
const t = (key: string) => (key === "admin.connectors.feature.tasks" ? "Aufgaben" : key);
expect(getSubscriptionFeatureBadge(t, { name: "tasks", title: "Tasks", badge: "Tasks" })).toBe("Aufgaben");
expect(getSubscriptionFeatureBadge(t, { name: "tasks", title: "Tasks", badge: "Bestseller" })).toBe("Bestseller");
expect(getSubscriptionFeatureBadge(t, { name: "tenant-custom", title: "Custom", badge: "Kundenspezifisch" })).toBe("Kundenspezifisch");
});
it.each(["en", "de"] as const)("has a %s catalog entry for every known system feature", (locale) => {
const featureCatalog = localeCatalog(locale).admin?.connectors?.feature ?? {};
expect(featureGateRegistry.map((feature) => feature.key).filter((key) => !featureCatalog[key])).toEqual([]);
});
});
@@ -0,0 +1,37 @@
import { getFeatureGate, isFeatureKey } from "@hivegrid/entitlements";
type SubscriptionFeatureTranslator = (key: string, options?: Record<string, unknown>) => unknown;
type SubscriptionFeatureTextInput = {
readonly name: string;
readonly title: string;
};
type SubscriptionFeatureBadgeInput = SubscriptionFeatureTextInput & {
readonly badge?: string | null;
};
export function getSubscriptionFeatureTitleKey(feature: SubscriptionFeatureTextInput): string {
return isFeatureKey(feature.name) ? `admin.connectors.feature.${feature.name}` : feature.title;
}
export function getSubscriptionFeatureTitle(
t: SubscriptionFeatureTranslator,
feature: SubscriptionFeatureTextInput,
values?: Record<string, unknown>
): string {
if (!isFeatureKey(feature.name)) return feature.title;
const key = getSubscriptionFeatureTitleKey(feature);
const translated = String(t(key, { defaultValue: feature.title, ...(values ?? {}) }));
return translated === key ? feature.title : translated;
}
export function getSubscriptionFeatureBadge(t: SubscriptionFeatureTranslator, feature: SubscriptionFeatureBadgeInput): string | null {
if (!feature.badge) return null;
if (!isFeatureKey(feature.name)) return feature.badge;
const registryFeature = getFeatureGate(feature.name);
if (!registryFeature || feature.badge !== registryFeature.title) return feature.badge;
return getSubscriptionFeatureTitle(t, { name: feature.name, title: feature.badge });
}
@@ -6,7 +6,7 @@ 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("/acme/settings/subscription?subscription_required=1");
expect(subscriptionRequiredCheckoutPath("acme")).toBe("/acme/settings/billing?subscription_required=1");
});
it("encodes tenant slugs as one route segment", () => {
@@ -26,5 +26,5 @@ export function subscriptionRequiredCheckoutPath(tenantSlug: string) {
throw new Error("tenantSlug is required");
}
return appPath({ tenantSlug: tenantSegment, path: "settings/subscription?subscription_required=1", mode: "host-aware" });
return appPath({ tenantSlug: tenantSegment, path: "settings/billing?subscription_required=1", mode: "host-aware" });
}
@@ -3,13 +3,23 @@ import { SubscriptionBillingPeriod } from "~/application/enums/subscriptions/Sub
import { SubscriptionPriceWithProduct } from "../db/subscriptionProducts.db.server";
import DateUtils from "../shared/DateUtils";
import { getFormattedPriceInCurrency } from "../helpers/PricingHelper";
import { TenantSubscriptionProductWithDetails } from "../db/subscriptions/tenantSubscriptionProducts.db.server";
type SubscriptionProductTitleItem = {
subscriptionProduct: { title: string };
prices: Array<{
subscriptionPrice: {
price: unknown;
currency: string | null;
billingPeriod: number;
} | null;
}>;
endsAt: Date | null;
};
function formatSubscriptionPrice(price: number, currency?: string | null) {
return getFormattedPriceInCurrency({ price, currency: currency ?? "usd" });
}
function getProductTitle({ t, item }: { t: TFunction; item: TenantSubscriptionProductWithDetails }) {
function getProductTitle({ t, item }: { t: TFunction; item: SubscriptionProductTitleItem }) {
let title =
t(item.subscriptionProduct.title) +
" " +
@@ -18,7 +28,7 @@ function getProductTitle({ t, item }: { t: TFunction; item: TenantSubscriptionPr
(f) =>
`${formatSubscriptionPrice(Number(f.subscriptionPrice?.price ?? 0), f.subscriptionPrice?.currency)} - ${getBillingPeriodDescription(
t,
f.subscriptionPrice!.billingPeriod
f.subscriptionPrice!.billingPeriod as SubscriptionBillingPeriod
)}`
)
.join(", ");
@@ -49,9 +49,9 @@ describe("UrlUtils", () => {
expect(actualOutput).toEqual(expectedOutput);
});
test("getModulePath should keep legacy tenant module rules through canonical builders", () => {
expect(UrlUtils.getModulePath({ tenant: "foo" }, "entities/contact")).toEqual("/foo/settings/entities/contact");
expect(UrlUtils.getModulePath({ tenant: "foo" }, "api/keys")).toEqual("/foo/settings/api/keys");
test("getModulePath should keep tenant module rules through canonical builders", () => {
expect(UrlUtils.getModulePath({ tenant: "foo" }, "contacts")).toEqual("/foo/contacts");
expect(UrlUtils.getModulePath({ tenant: "foo" }, "api/keys")).toEqual("/foo/api/keys");
expect(UrlUtils.getModulePath({ tenant: "foo" }, "workflow-engine/workflows")).toEqual("/foo/workflow-engine/workflows");
expect(UrlUtils.getModulePath({}, "accounts")).toEqual("/accounts");
});
@@ -69,9 +69,9 @@ describe("UrlUtils", () => {
expect(UrlUtils.getModulePath(tenantParams, "workflow-engine/workflows")).toEqual("/acme/workflow-engine/workflows");
});
test("Portals and Sites remain direct tenant modules", () => {
expect(UrlUtils.getModulePath(tenantParams, "portals/customer/pages")).toEqual("/acme/portals/customer/pages");
expect(UrlUtils.getModulePath(tenantParams, "sites/storefront/site_123/settings")).toEqual("/acme/sites/storefront/site_123/settings");
test("API management stays inside the tenant settings workspace", () => {
expect(UrlUtils.currentTenantUrl(tenantParams, "settings/api/keys")).toEqual("/acme/settings/api/keys");
expect(UrlUtils.currentTenantUrl(tenantParams, "settings/api/logs")).toEqual("/acme/settings/api/logs");
});
});
});
@@ -53,11 +53,7 @@ function getParentRoute(pathname: string) {
function getModulePath(params: Params, path: string) {
if (params.tenant) {
let modulePath = path;
if (path.startsWith("entities")) {
modulePath = `settings/${path}`;
} else if (path.startsWith("api")) {
modulePath = `settings/${path}`;
} else if (path.startsWith("workflow-engine")) {
if (path.startsWith("workflow-engine")) {
modulePath = path;
} else if (path.startsWith("logs")) {
modulePath = `settings/${path}`;
@@ -0,0 +1,15 @@
import { describe, expect, test } from "vitest";
import { validatePassword } from "./UserValidationUtils";
describe("login password pre-validation", () => {
test("accepts legacy-compatible passwords while bounding hash work", () => {
expect(validatePassword("four")).toBe(true);
expect(validatePassword("x".repeat(1_024))).toBe(true);
expect(validatePassword("x".repeat(1_025))).toBe(false);
});
test("rejects absent and too-short values", () => {
expect(validatePassword(undefined)).toBe(false);
expect(validatePassword("abc")).toBe(false);
});
});
@@ -1,6 +1,6 @@
import type { TFunction } from "i18next";
import MailChecker from "mailchecker";
import { validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
import { PASSWORD_ABSOLUTE_MAX_LENGTH, validatePassword as validatePolicyPassword } from "~/services/auth/password-policy.server";
export const validateEmail = (email: unknown) => {
const regexp = new RegExp(
@@ -24,7 +24,7 @@ export const validateEmail = (email: unknown) => {
* MUST use {@link validatePasswords} or the underlying policy directly.
*/
export const validatePassword = (password: unknown) => {
if (typeof password !== "string" || password.length < 4) {
if (typeof password !== "string" || password.length < 4 || password.length > PASSWORD_ABSOLUTE_MAX_LENGTH) {
return false;
}
return true;
@@ -0,0 +1,37 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { AVATAR_PROXY_PREFIX, avatarProxyPath, avatarStorageKey, isAvatarProxyPath, isAvatarUpload } from "./avatarPaths";
describe("avatar paths", () => {
it("derives a deterministic object key per user", () => {
expect(avatarStorageKey("user-1")).toBe("users/user-1/avatar");
});
it("builds a stable proxy path with a cache-busting version", () => {
expect(avatarProxyPath("user-1", "abc")).toBe(`${AVATAR_PROXY_PREFIX}/user-1?v=abc`);
});
it("escapes the version so it cannot smuggle extra query parameters", () => {
expect(avatarProxyPath("user-1", "a&b=c")).toBe(`${AVATAR_PROXY_PREFIX}/user-1?v=a%26b%3Dc`);
});
it("recognises a proxy-backed avatar", () => {
expect(isAvatarProxyPath(avatarProxyPath("user-1", "1"))).toBe(true);
});
it("treats legacy values as not proxy-backed, so no object is assumed behind them", () => {
expect(isAvatarProxyPath("data:image/png;base64,AAAA")).toBe(false);
expect(isAvatarProxyPath("https://cdn.example.test/a.png")).toBe(false);
expect(isAvatarProxyPath("")).toBe(false);
expect(isAvatarProxyPath(null)).toBe(false);
expect(isAvatarProxyPath(undefined)).toBe(false);
});
it("only counts freshly picked bytes as an upload", () => {
expect(isAvatarUpload("data:image/png;base64,AAAA")).toBe(true);
// The screen re-submits the rendered value on an unrelated save — that must
// never be pushed back through the scanner.
expect(isAvatarUpload(avatarProxyPath("user-1", "1"))).toBe(false);
expect(isAvatarUpload("")).toBe(false);
});
});
@@ -0,0 +1,38 @@
// Avatar delivery (AD-23). The media bucket is private, so a profile picture is
// never a public object URL: the bytes live under a deterministic key and
// user.avatar carries a stable app path that the /avatars/:userId auth-proxy
// resolves into a short-lived signed URL — the same shape the Files module uses
// for media.$fileId.$variant.
//
// Pure path helpers, no storage/db imports, so both the proxy route and the
// profile actions can share them.
export const AVATAR_PROXY_PREFIX = "/avatars";
/** Object key of a user's avatar inside the private storage bucket. */
export function avatarStorageKey(userId: string): string {
return `users/${userId}/avatar`;
}
/**
* Value persisted in user.avatar. The path is stable (the object key never
* changes), so a version token is appended to bust the browser cache whenever
* the user swaps the picture.
*/
export function avatarProxyPath(userId: string, version: string): string {
return `${AVATAR_PROXY_PREFIX}/${userId}?v=${encodeURIComponent(version)}`;
}
/**
* True when user.avatar points at the proxy, i.e. an object exists behind it.
* Legacy values (data: URIs, absolute URLs from the boilerplate era) render
* straight from the DB and must never be treated as a stored object.
*/
export function isAvatarProxyPath(value: string | null | undefined): boolean {
return typeof value === "string" && value.startsWith(`${AVATAR_PROXY_PREFIX}/`);
}
/** True when the submitted avatar field carries freshly picked image bytes. */
export function isAvatarUpload(value: string): boolean {
return value.startsWith("data:");
}
@@ -14,14 +14,18 @@
* possible here. Audit-LOG-row retention is handled by the existing worker job
* (`audit-retention`).
*/
import { randomBytes } from "node:crypto";
import { getDbClient } from "@hivegrid/db/client.server";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { loadAuditVerificationContext } from "@hivegrid/db/audit-chain-checkpoint.server";
import { putBufferAsFile, resolveStorageBucket, hasStorageCredentials } from "~/utils/integrations/storageService";
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
import {
AUDIT_EXPORT_MAX_ROWS,
buildAuditExportWhere,
computeAuditIntegritySummary,
hasAuditExportPrefixFilters,
renderAuditExportCsv,
renderAuditExportNdjson,
type AuditExportFilters,
@@ -93,14 +97,17 @@ export async function runAuditExportToStorage(input: AuditExportToStorageInput):
take: AUDIT_EXPORT_MAX_ROWS,
})) as unknown as AuditExportRow[];
const integrity = computeAuditIntegritySummary(rows);
const verification = await loadAuditVerificationContext(db as never, rows, {
allowPartialPrefix: hasAuditExportPrefixFilters(input.filters),
});
const integrity = computeAuditIntegritySummary(rows, verification);
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 rand = randomBytes(8).toString("hex");
const filename = `audit-export-${scope}-${stamp}.${ext}`;
const key = `audit-exports/${scope}/${stamp}-${rand}.${ext}`;
@@ -7,10 +7,11 @@ function makeRequest(headers: Record<string, string>): Request {
}
describe("extractWebActorIp", () => {
it("prefers cf-connecting-ip > x-real-ip > x-forwarded-for first hop", () => {
expect(extractWebActorIp(makeRequest({ "cf-connecting-ip": "1.1.1.1", "x-forwarded-for": "2.2.2.2" }))).toBe("1.1.1.1");
it("accepts Cloudflare client IPs only behind a verified Cloudflare peer", () => {
expect(extractWebActorIp(makeRequest({ "cf-connecting-ip": "1.1.1.1", "x-forwarded-for": "2.2.2.2, 173.245.48.10" }))).toBe("1.1.1.1");
expect(extractWebActorIp(makeRequest({ "x-real-ip": "2.2.2.2" }))).toBe("2.2.2.2");
expect(extractWebActorIp(makeRequest({ "x-forwarded-for": "3.3.3.3, 8.8.8.8" }))).toBe("3.3.3.3");
expect(extractWebActorIp(makeRequest({ "x-forwarded-for": "3.3.3.3, 8.8.8.8" }))).toBe("8.8.8.8");
expect(extractWebActorIp(makeRequest({ "cf-connecting-ip": "not-an-ip" }))).toBeNull();
expect(extractWebActorIp(makeRequest({}))).toBeNull();
});
});
@@ -34,7 +35,17 @@ describe("extractWebRequestId", () => {
describe("withAuditContext", () => {
it("binds the context for the duration of the callback", async () => {
expect(getWebAuditContext()).toBeNull();
const captured = await withAuditContext({ request: makeRequest({ "cf-connecting-ip": "5.5.5.5", "user-agent": "Test/1.0", "x-request-id": "req_1" }) }, async () => getWebAuditContext());
const captured = await withAuditContext(
{
request: makeRequest({
"cf-connecting-ip": "5.5.5.5",
"x-forwarded-for": "198.51.100.5, 173.245.48.10",
"user-agent": "Test/1.0",
"x-request-id": "req_1",
}),
},
async () => getWebAuditContext()
);
expect(captured).toEqual({ actorIp: "5.5.5.5", actorUserAgent: "Test/1.0", requestId: "req_1" });
expect(getWebAuditContext()).toBeNull();
});
@@ -1,4 +1,5 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
/**
* Phase 10 Task #67 — Audit auto-capture (React-Router web).
@@ -23,16 +24,8 @@ export type WebAuditContext = {
const webAuditContextStore = new AsyncLocalStorage<WebAuditContext>();
const FORWARDED_HEADERS = ["cf-connecting-ip", "x-real-ip", "x-forwarded-for"] as const;
export function extractWebActorIp(request: Request): string | null {
for (const name of FORWARDED_HEADERS) {
const raw = request.headers.get(name);
if (typeof raw !== "string") continue;
const first = raw.split(",")[0]?.trim();
if (first && first.length > 0 && first.length <= 64) return first;
}
return null;
return getTrustedClientIpOrNull(request);
}
export function extractWebActorUserAgent(request: Request): string | null {
@@ -19,7 +19,6 @@ const baseWebConfig: WebConfig = {
novu: {},
mailerSend: {},
ipProviders: {},
portalServer: {},
magicLink: {
enabled: true,
tokenTtlMinutes: 15,
@@ -23,12 +23,10 @@ afterEach(async () => {
const toKey = (userId: string, ip: string) => ({ userId, perIp: `${userId}:${ip}` });
describe("MFA challenge rate limiter", () => {
it("keys attempts by user and a TRUSTED client IP, ignoring spoofable X-Forwarded-For", () => {
it("keys attempts by a Cloudflare client IP only behind a verified Cloudflare peer", () => {
const request = new Request("https://admin.example.test/mfa-challenge", {
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.
"x-forwarded-for": "1.2.3.4, 173.245.48.10",
"cf-connecting-ip": "203.0.113.5",
},
});
@@ -36,7 +34,7 @@ describe("MFA challenge rate limiter", () => {
expect(mfaChallengeRateLimitKey(request, "user_1")).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.5" });
});
it("falls back to x-real-ip and then unknown, never to x-forwarded-for", () => {
it("falls back to the Traefik-appended XFF or X-Real-IP peer and then unknown", () => {
expect(
mfaChallengeRateLimitKey(
new Request("https://admin.example.test/mfa-challenge", {
@@ -45,13 +43,12 @@ describe("MFA challenge rate limiter", () => {
"user_1",
),
).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" });
).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.9" });
expect(mfaChallengeRateLimitKey(new Request("https://admin.example.test/mfa-challenge"), "user_1")).toEqual({
userId: "user_1",
perIp: "user_1:unknown",
@@ -103,7 +100,7 @@ describe("MFA challenge rate limiter", () => {
await expect(checkMfaChallengeRateLimit(key, now)).resolves.toEqual({
allowed: true,
remaining: 5,
remaining: 4,
resetAt: new Date("2026-05-11T12:05:00.000Z"),
});
});
@@ -111,17 +108,37 @@ describe("MFA challenge rate limiter", () => {
it("resetMfaChallengeRateLimiterForTests clears cached fixed-window keys", async () => {
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);
await resetMfaChallengeRateLimiterForTests();
const freshStore = createSharedStore({ namespace: "test-mfa-challenge" });
__setMfaChallengeRateLimitStoreForTests(freshStore);
await recordFailedMfaChallengeAttempt(key, now);
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
});
it("atomically caps parallel TOTP verifiers", async () => {
const key = toKey("parallel-user", "198.51.100.88");
const results = await Promise.all(
Array.from({ length: 20 }, () => checkMfaChallengeRateLimit(key)),
);
expect(results.filter((result) => result.allowed)).toHaveLength(5);
expect(results.filter((result) => !result.allowed)).toHaveLength(15);
});
it("does not let a blocked source keep consuming the per-user budget", async () => {
const blockedKey = toKey("victim", "198.51.100.89");
for (let index = 0; index < 5; index += 1) {
expect((await checkMfaChallengeRateLimit(blockedKey)).allowed).toBe(true);
}
for (let index = 0; index < 20; index += 1) {
expect((await checkMfaChallengeRateLimit(blockedKey)).allowed).toBe(false);
}
expect((await checkMfaChallengeRateLimit(toKey("victim", "198.51.100.90"))).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.
@@ -66,34 +66,54 @@ export function mfaChallengeRateLimitKey(request: Request, userId: string): MfaC
}
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) {
const { perIp, perUser, store } = getLimiters();
// Reserve before TOTP/recovery-code verification. Read-then-consume permits
// every request in a parallel burst to observe the same old count.
const perIpReservation = await reserveWithCorruptionRecovery(
perIp,
store,
key.perIp,
`rl:fixed:mfa-challenge:${key.perIp}`,
);
if (!perIpReservation.allowed) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000) };
}
const perUserReservation = await reserveWithCorruptionRecovery(
perUser,
store,
key.userId,
`rl:fixed:mfa-challenge-user:${key.userId}`,
);
if (!perUserReservation.allowed) {
return { allowed: false, retryAfterSeconds: MFA_CHALLENGE_USER_WINDOW_SECONDS, resetAt: new Date(now.getTime() + MFA_CHALLENGE_USER_WINDOW_SECONDS * 1000) };
}
return {
allowed: true,
remaining: Math.min(MFA_CHALLENGE_LIMIT - perIpCount, MFA_CHALLENGE_USER_LIMIT - perUserCount),
remaining: Math.min(perIpReservation.remaining, perUserReservation.remaining),
resetAt: new Date(now.getTime() + MFA_CHALLENGE_WINDOW_SECONDS * 1000),
};
}
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 recordFailedMfaChallengeAttempt(key: MfaChallengeRateLimitKey, _now: Date = new Date()): Promise<void> {
// checkMfaChallengeRateLimit already reserved this attempt before verification.
void key;
void _now;
}
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)]);
async function reserveWithCorruptionRecovery(
limiter: FixedWindowRateLimiter,
store: SharedStore,
key: string,
storageKey: string,
) {
try {
return await limiter.consume(key);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (!/non-numeric|not an integer/i.test(message)) throw error;
await store.del(storageKey);
return limiter.consume(key);
}
}
export async function resetMfaChallengeRateLimit(key: MfaChallengeRateLimitKey): Promise<void> {
@@ -4,6 +4,7 @@ import type { UserTotpStatus } from "~/utils/db/users.db.server";
import type { MfaStepUpCheckResult } from "./step-up.server";
import {
ADMIN_MFA_CHALLENGE_PATH,
ADMIN_MFA_ENROLLMENT_PATH,
enforceAdminMfa,
type AdminMfaEnforcementResult,
} from "./enforcement.server";
@@ -48,21 +49,21 @@ describe("enforceAdminMfa", () => {
});
});
test("allows admins without active TOTP so the profile enrollment path is opt-in and non-blocking", () => {
test("fails closed when TOTP status is unavailable and requires enrollment when disabled", () => {
expect(enforce({ totpStatus: null })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "missing-totp-status",
redirectTo: "/login",
});
expect(enforce({ totpStatus: { enabled: false, pending: false, enabledAt: null, pendingCreatedAt: null } })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "totp-not-enabled",
redirectTo: ADMIN_MFA_ENROLLMENT_PATH,
});
expect(enforce({ totpStatus: pendingOnlyTotp })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "totp-not-enabled",
redirectTo: ADMIN_MFA_ENROLLMENT_PATH,
});
});
@@ -127,9 +128,9 @@ describe("enforceAdminMfa", () => {
});
expect(enforce({ totpStatus: null, redirectMode: "host-aware" })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
allowed: false,
reason: "missing-totp-status",
redirectTo: "/login",
});
});
@@ -139,6 +140,11 @@ describe("enforceAdminMfa", () => {
reason: "allowed",
redirectTo: "/settings/profile?mfa=setup",
});
expect(enforce({ requestUrl: "https://admin.example.com/settings/profile/", totpStatus: pendingOnlyTotp, redirectMode: "host-aware" })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/settings/profile/",
});
});
test("allows the admin MFA challenge route without existing step-up", () => {
@@ -186,6 +192,34 @@ describe("enforceAdminMfa", () => {
});
});
test("local dev bypass allows admins without TOTP or step-up under the dev:local contract", () => {
const localEnv = { LOCAL_DEV_CREDENTIALS: "1", NODE_ENV: "development" };
expect(enforce({ totpStatus: pendingOnlyTotp, stepUp: { verified: false, reason: "missing" }, env: localEnv })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
});
expect(enforce({ totpStatus: null, stepUp: { verified: false, reason: "missing" }, env: localEnv })).toEqual({
allowed: true,
reason: "allowed",
redirectTo: "/users?tenant=tenant-1#section",
});
});
test("local dev bypass never activates outside the dev:local contract and never bypasses auth itself", () => {
const localEnv = { LOCAL_DEV_CREDENTIALS: "1", NODE_ENV: "development" };
const denied = { allowed: false, reason: "totp-not-enabled", redirectTo: ADMIN_MFA_ENROLLMENT_PATH };
expect(enforce({ totpStatus: pendingOnlyTotp, env: {} })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, NODE_ENV: "production" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, LOCAL_DEV_CREDENTIALS: "" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, CI: "true" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, SENTRY_ENVIRONMENT: "staging" } })).toEqual(denied);
expect(enforce({ totpStatus: pendingOnlyTotp, env: { ...localEnv, RLS_RUNTIME_MODE: "required" } })).toEqual(denied);
expect(enforce({ userId: null, env: localEnv })).toEqual({ allowed: false, reason: "missing-user", redirectTo: "/login" });
expect(enforce({ isAdmin: false, env: localEnv })).toEqual({ allowed: false, reason: "missing-admin", redirectTo: "/" });
});
test("result payloads contain no TOTP secrets, recovery codes, hashes, cookies, tokens, or passwords", () => {
const result = enforce({
requestUrl: "https://admin.example.com/dashboard?tab=secrets",
@@ -1,7 +1,7 @@
import type { UserTotpStatus } from "~/utils/db/users.db.server";
import type { MfaStepUpCheckReason, MfaStepUpCheckResult } from "./step-up.server";
export { ADMIN_MFA_CHALLENGE_PATH, ADMIN_MFA_DEFAULT_REDIRECT_PATH, ADMIN_MFA_ENROLLMENT_PATH } from "./paths";
import { ADMIN_MFA_CHALLENGE_PATH, ADMIN_MFA_DEFAULT_REDIRECT_PATH } from "./paths";
import { ADMIN_MFA_CHALLENGE_PATH, ADMIN_MFA_DEFAULT_REDIRECT_PATH, ADMIN_MFA_ENROLLMENT_PATH } from "./paths";
export type AdminMfaEnforcementFailureReason =
| "missing-user"
@@ -27,12 +27,39 @@ export type AdminMfaEnforcementInput = {
stepUp: MfaStepUpCheckResult;
redirectMode?: "host-aware";
appFallbackPath?: string;
env?: AdminMfaLocalBypassEnvironment;
};
function isAdminMfaChallengePath(requestUrl: string | URL): boolean {
export type AdminMfaLocalBypassEnvironment = {
LOCAL_DEV_CREDENTIALS?: string;
NODE_ENV?: string;
CI?: string;
SENTRY_ENVIRONMENT?: string;
RLS_RUNTIME_MODE?: string;
};
/**
* The canonical local launcher (pnpm dev:local) disables admin TOTP enrollment
* and step-up challenges entirely. Gated on the same environment contract as
* the local credential normalization so it can never activate on CI, staging,
* or production (which additionally never set LOCAL_DEV_CREDENTIALS).
*/
export function isLocalAdminMfaBypassActive(env: AdminMfaLocalBypassEnvironment = process.env): boolean {
return (
env.LOCAL_DEV_CREDENTIALS === "1" &&
env.NODE_ENV === "development" &&
!env.CI?.trim() &&
!env.SENTRY_ENVIRONMENT?.trim() &&
env.RLS_RUNTIME_MODE?.trim().toLowerCase() !== "required"
);
}
function isAdminMfaPath(requestUrl: string | URL, expectedPath: string): boolean {
try {
const url = requestUrl instanceof URL ? requestUrl : new URL(requestUrl);
return url.pathname === ADMIN_MFA_CHALLENGE_PATH;
const pathname = url.pathname.replace(/\/+$/, "") || "/";
const normalizedExpectedPath = expectedPath.replace(/\/+$/, "") || "/";
return pathname === normalizedExpectedPath;
} catch {
return false;
}
@@ -75,11 +102,22 @@ export function enforceAdminMfa(input: AdminMfaEnforcementInput): AdminMfaEnforc
return { allowed: false, reason: "missing-admin", redirectTo: input.appFallbackPath ?? "/" };
}
if (!input.totpStatus || !input.totpStatus.enabled) {
if (isLocalAdminMfaBypassActive(input.env)) {
return { allowed: true, reason: "allowed", redirectTo: safePathFromRequestUrl(input.requestUrl) };
}
if (!input.stepUp.verified && !isAdminMfaChallengePath(input.requestUrl)) {
if (!input.totpStatus) {
return { allowed: false, reason: "missing-totp-status", redirectTo: "/login" };
}
if (!input.totpStatus.enabled) {
if (isAdminMfaPath(input.requestUrl, ADMIN_MFA_ENROLLMENT_PATH)) {
return { allowed: true, reason: "allowed", redirectTo: safePathFromRequestUrl(input.requestUrl) };
}
return { allowed: false, reason: "totp-not-enabled", redirectTo: ADMIN_MFA_ENROLLMENT_PATH };
}
if (!input.stepUp.verified && !isAdminMfaPath(input.requestUrl, ADMIN_MFA_CHALLENGE_PATH)) {
return { allowed: false, reason: stepUpReason(input.stepUp.reason), redirectTo: challengeRedirectTo(input.requestUrl) };
}
@@ -4,11 +4,26 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const { testWebConfig } = vi.hoisted(() => ({
testWebConfig: {
nodeEnv: "test" as string,
sessionSecret: "test-session-secret-please-change",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https" as "http" | "https",
},
},
}));
const resolveTrustedDeviceRlsIdentityMock = vi.hoisted(() => vi.fn());
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" }),
loadRequiredWebConfig: () => testWebConfig,
};
});
vi.mock("~/utils/db.server", () => ({
@@ -25,6 +40,9 @@ vi.mock("~/utils/db.server", () => ({
vi.mock("~/services/auth/sessionLifecycle.server", () => ({
buildSessionDeviceContext: vi.fn().mockResolvedValue({ ipHash: null, userAgent: "UA", approxLocation: "DE" }),
}));
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolveTrustedDeviceRlsIdentity: resolveTrustedDeviceRlsIdentityMock,
}));
import { db } from "~/utils/db.server";
import {
@@ -36,6 +54,7 @@ import {
rememberDeviceForUser,
revokeAllTrustedDevices,
revokeTrustedDevice,
LOCAL_TRUSTED_DEVICE_COOKIE_NAME,
TRUSTED_DEVICE_COOKIE_NAME,
} from "./trusted-device.server";
@@ -69,6 +88,10 @@ async function rememberAndGetRequest(userId = "user-1") {
beforeEach(() => {
vi.clearAllMocks();
resolveTrustedDeviceRlsIdentityMock.mockResolvedValue({ resourceId: "td-1", userId: "user-1" });
testWebConfig.nodeEnv = "test";
testWebConfig.routing.protocol = "https";
testWebConfig.routing.appBaseDomain = "example.test";
__resetTrustedDeviceCookieForTests();
});
afterEach(() => __resetTrustedDeviceCookieForTests());
@@ -79,6 +102,9 @@ describe("trusted-device (DB-backed)", () => {
const setCookie = await rememberDeviceForUser({ request: new Request("https://app.example.com/login-mfa"), userId: "user-1" });
expect(create).toHaveBeenCalledTimes(1);
expect(setCookie).toContain(TRUSTED_DEVICE_COOKIE_NAME);
expect(setCookie).toContain("Secure");
expect(setCookie).toContain("Path=/");
expect(setCookie).not.toContain("Domain=");
// Nur der Hash, nie der rohe Token, wird persistiert.
const data = (create.mock.calls[0][0] as { data: { tokenHash: string } }).data;
expect(data.tokenHash).toMatch(/^[0-9a-f]{64}$/);
@@ -129,6 +155,43 @@ describe("trusted-device (DB-backed)", () => {
expect(findUnique).not.toHaveBeenCalled();
});
it("ignores a legacy parent-domain cookie even when its signed value is otherwise valid", async () => {
const validRequest = await rememberAndGetRequest("user-1");
const cookie = validRequest.headers.get("Cookie") ?? "";
const legacyCookie = cookie.replace(TRUSTED_DEVICE_COOKIE_NAME, LOCAL_TRUSTED_DEVICE_COOKIE_NAME);
const request = new Request("https://app.example.test/login", { headers: { Cookie: legacyCookie } });
await expect(isTrustedDevice(request, "user-1")).resolves.toBe(false);
expect(findUnique).not.toHaveBeenCalled();
});
it("does not let a legacy cookie shadow the host-prefixed marker", async () => {
const validRequest = await rememberAndGetRequest("user-1");
const secureCookie = validRequest.headers.get("Cookie") ?? "";
const request = new Request("https://app.example.test/login", {
headers: { Cookie: `${LOCAL_TRUSTED_DEVICE_COOKIE_NAME}=attacker; ${secureCookie}` },
});
findUnique.mockResolvedValue(activeRow() as never);
await expect(isTrustedDevice(request, "user-1")).resolves.toBe(true);
expect(findUnique).toHaveBeenCalledTimes(1);
});
it("uses a distinct non-Secure fallback name on local HTTP", async () => {
testWebConfig.nodeEnv = "development";
testWebConfig.routing.protocol = "http";
testWebConfig.routing.appBaseDomain = "localhost:3000";
__resetTrustedDeviceCookieForTests();
create.mockResolvedValue(activeRow() as never);
const setCookie = await rememberDeviceForUser({ request: new Request("http://localhost:3000/login-mfa"), userId: "user-1" });
expect(setCookie).toContain(`${LOCAL_TRUSTED_DEVICE_COOKIE_NAME}=`);
expect(setCookie).not.toContain(TRUSTED_DEVICE_COOKIE_NAME);
expect(setCookie).not.toContain("Secure");
expect(setCookie).not.toContain("Domain=");
});
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);
@@ -138,7 +201,7 @@ describe("trusted-device (DB-backed)", () => {
expect.objectContaining({
where: expect.objectContaining({ userId: "user-1", revokedAt: null }),
orderBy: { lastUsedAt: "desc" },
}),
})
);
});
@@ -1,14 +1,17 @@
import { createHash, randomBytes } from "node:crypto";
import { createCookie } from "react-router";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { db } from "~/utils/db.server";
import { buildSessionDeviceContext } from "~/services/auth/sessionLifecycle.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTrustedDeviceRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
// 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 = "hivegrid_trusted_device";
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 Tage
export const TRUSTED_DEVICE_COOKIE_NAME = "__Host-hivegrid_trusted_device";
export const LOCAL_TRUSTED_DEVICE_COOKIE_NAME = "hivegrid_trusted_device";
export const TRUSTED_DEVICE_MAX_AGE_SECONDS = 60 * 60 * 24 * 30; // 30 days
const TRUSTED_DEVICE_TOKEN_BYTES = 32;
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // throttle lastUsedAt updates to every 5 minutes
@@ -21,12 +24,19 @@ function getTrustedDeviceCookie() {
return cachedCookie;
}
const webConfig = loadRequiredWebConfig();
cachedCookie = createCookie(TRUSTED_DEVICE_COOKIE_NAME, {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: webConfig.nodeEnv === "production",
const policy = resolveHostOnlyCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
secureName: TRUSTED_DEVICE_COOKIE_NAME,
localName: LOCAL_TRUSTED_DEVICE_COOKIE_NAME,
maxAge: TRUSTED_DEVICE_MAX_AGE_SECONDS,
});
cachedCookie = createCookie(policy.name, {
httpOnly: policy.httpOnly,
sameSite: policy.sameSite,
path: policy.path,
secure: policy.secure,
maxAge: policy.maxAge,
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
});
return cachedCookie;
@@ -54,10 +64,14 @@ async function readRawTokenFromCookie(request: Request): Promise<string | null>
}
/**
* Markiert das aktuelle Geraet fuer `userId` als vertrauenswuerdig: legt die Tabellen-Zeile mit
* (pseudonymisiertem) Geraete-Kontext an und gibt den Set-Cookie-String mit dem rohen Token zurueck.
* Marks the current device as trusted for `userId`, persists only the
* pseudonymized device context, and returns the raw token in a Set-Cookie value.
*/
export async function rememberDeviceForUser({ request, userId, now = new Date() }: { request: Request; userId: string; now?: Date }): Promise<string> {
return withUserRlsContext(userId, () => rememberDeviceForUserScoped({ request, userId, now }));
}
async function rememberDeviceForUserScoped({ request, userId, now }: { request: Request; userId: string; now: Date }): Promise<string> {
const rawToken = generateTrustedDeviceToken();
const context = await buildSessionDeviceContext(request);
await db.trustedDevice.create({
@@ -74,11 +88,14 @@ export async function rememberDeviceForUser({ request, userId, now = new Date()
}
/**
* Prueft, ob der Request ein vertrauenswuerdiges Geraet fuer `userId` traegt: Cookie-Token -> Hash ->
* aktive Tabellen-Zeile mit passender userId. Best-effort: jeder Fehler gilt als "nicht vertraut".
* Schreibt lastUsedAt gedrosselt fort.
* Resolves the cookie token to an active row owned by `userId`. This is
* best-effort and fail-closed; `lastUsedAt` writes are throttled.
*/
export async function isTrustedDevice(request: Request, userId: string, now: Date = new Date()): Promise<boolean> {
return withUserRlsContext(userId, () => isTrustedDeviceScoped(request, userId, now));
}
async function isTrustedDeviceScoped(request: Request, userId: string, now: Date): Promise<boolean> {
try {
const rawToken = await readRawTokenFromCookie(request);
if (!rawToken) {
@@ -97,50 +114,69 @@ export async function isTrustedDevice(request: Request, userId: string, now: Dat
}
}
/** Aktive vertrauenswuerdige Geraete eines Nutzers (Geraete-Liste in Settings > Sicherheit). */
/** Lists active trusted devices for the security settings screen. */
export async function listTrustedDevices(userId: string): Promise<TrustedDeviceRow[]> {
return db.trustedDevice.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastUsedAt: "desc" },
});
return withUserRlsContext(userId, () =>
db.trustedDevice.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastUsedAt: "desc" },
}),
);
}
/** Widerruft genau ein eigenes vertrauenswuerdiges Geraet (Eigentuemerschaft ueber userId gesichert). */
/** Revokes one trusted device after enforcing user ownership in the query. */
export async function revokeTrustedDevice({ userId, deviceId }: { userId: string; deviceId: string }): Promise<boolean> {
const result = await db.trustedDevice.updateMany({
where: { id: deviceId, userId, revokedAt: null },
data: { revokedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.trustedDevice.updateMany({
where: { id: deviceId, userId, revokedAt: null },
data: { revokedAt: new Date() },
});
return result.count > 0;
});
return result.count > 0;
}
/** "Alle Geraete vergessen": widerruft alle aktiven Trust-Marker des Nutzers. */
/** Revokes every active trusted-device marker owned by the user. */
export async function revokeAllTrustedDevices(userId: string): Promise<number> {
const result = await db.trustedDevice.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.trustedDevice.updateMany({
where: { userId, revokedAt: null },
data: { revokedAt: new Date() },
});
return result.count;
});
return result.count;
}
/**
* Vergisst das aktuelle Geraet: widerruft die zum Cookie gehoerende Zeile (falls vorhanden) und gibt
* den Set-Cookie-String zurueck, der den Trust-Marker im Browser loescht.
*/
/** Revokes the current marker, if present, and clears its browser cookie. */
export async function forgetCurrentTrustedDevice(request: Request): Promise<string> {
const rawToken = await readRawTokenFromCookie(request);
if (rawToken) {
await db.trustedDevice.updateMany({ where: { tokenHash: hashTrustedDeviceToken(rawToken), revokedAt: null }, data: { revokedAt: new Date() } }).catch(() => undefined);
const tokenHash = hashTrustedDeviceToken(rawToken);
const identity = await resolveTrustedDeviceRlsIdentity(tokenHash).catch(() => null);
if (identity) {
await runWithRlsContext({ userId: identity.userId }, () =>
db.trustedDevice.updateMany({
where: { id: identity.resourceId, tokenHash, userId: identity.userId, revokedAt: null },
data: { revokedAt: new Date() },
}),
).catch(() => undefined);
}
}
return clearTrustedDeviceCookie();
}
/** Set-Cookie-String, der den Trust-Marker im Browser loescht (ohne DB-Zugriff). */
/** Returns a Set-Cookie value that clears the marker without a database read. */
export async function clearTrustedDeviceCookie(): Promise<string> {
return getTrustedDeviceCookie().serialize("", { maxAge: 0, expires: new Date(0) });
}
/** Test-Naht: erzwingt eine Neuauflage des Cookies (z.B. nach geaenderter Config im Test). */
/** Test seam for rebuilding the cookie after configuration changes. */
export function __resetTrustedDeviceCookieForTests() {
cachedCookie = null;
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}
@@ -46,6 +46,14 @@ describe("passwordHasher.server", () => {
expect(result.rehashedHash).toBeUndefined();
});
test("verifyPassword rejects bcrypt credentials that would be silently truncated after 72 bytes", async () => {
const exactPrefix = "x".repeat(72);
const legacyHash = await bcryptjs.hash(exactPrefix, 4);
await expect(verifyPassword(exactPrefix, legacyHash)).resolves.toMatchObject({ valid: true });
await expect(verifyPassword(`${exactPrefix}attacker-controlled-suffix`, legacyHash)).resolves.toEqual({ valid: false });
});
test("verifyPassword rejects unknown / empty hashes without throwing", async () => {
await expect(verifyPassword(PLAINTEXT, "")).resolves.toEqual({ valid: false });
await expect(verifyPassword(PLAINTEXT, "garbage")).resolves.toEqual({ valid: false });
@@ -6,6 +6,9 @@
import argon2 from "argon2";
import bcryptjs from "bcryptjs";
import { createScopedLogger } from "~/utils/logger.server";
const passwordHasherLogger = createScopedLogger("auth.password-hasher");
// OWASP 2024 recommendation for argon2id at modest server cost.
// memoryCost is in KiB (19456 = 19 MiB).
@@ -18,6 +21,7 @@ const ARGON2_OPTIONS = {
const ARGON2_PREFIX_RE = /^\$argon2(?:i|d|id)\$/;
const BCRYPT_PREFIX_RE = /^\$2[abxy]\$/;
const BCRYPT_MAX_PASSWORD_BYTES = 72;
export type VerifyPasswordResult = {
valid: boolean;
@@ -56,15 +60,28 @@ export async function verifyPassword(plain: string, hash: string | null | undefi
try {
const valid = await argon2.verify(hash, plain);
return { valid };
} catch {
} catch (error: unknown) {
passwordHasherLogger.warn(
{ op: "verify.argon2.failed", error: toSafeVerificationError(error) },
"Argon2 password verification raised; treating the credential as invalid."
);
return { valid: false };
}
}
if (BCRYPT_PREFIX_RE.test(hash)) {
// bcrypt silently truncates after 72 bytes. Reject an overlong legacy
// credential so a different suffix cannot authenticate as the same key.
if (Buffer.byteLength(plain, "utf8") > BCRYPT_MAX_PASSWORD_BYTES) {
return { valid: false };
}
let valid = false;
try {
valid = await bcryptjs.compare(plain, hash);
} catch {
} catch (error: unknown) {
passwordHasherLogger.warn(
{ op: "verify.bcrypt.failed", error: toSafeVerificationError(error) },
"Bcrypt password verification raised; treating the credential as invalid."
);
return { valid: false };
}
if (!valid) {
@@ -85,3 +102,11 @@ export function isKnownHashFormat(hash: string): "argon2" | "bcrypt" | "unknown"
if (BCRYPT_PREFIX_RE.test(hash)) return "bcrypt";
return "unknown";
}
function toSafeVerificationError(error: unknown): { name: string; code?: string } {
const candidate = error as { name?: unknown; code?: unknown } | null;
return {
name: typeof candidate?.name === "string" ? candidate.name : "Error",
...(typeof candidate?.code === "string" ? { code: candidate.code } : {}),
};
}
@@ -31,9 +31,9 @@ const EMPTY_CHUNK_ALLOWLIST = new Set([
"api.embed.forms._formKey.submit",
"api.leads.capture",
"api.metrics",
"api.password-policy-remind",
"api.status",
"api.tenants._tenant.plugins",
"auth.password-policy-remind",
"callback",
"dry-run",
"healthcheck",
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { getManualChunkName } from "./manualChunks";
import { getChunkFileName, getManualChunkName } from "./manualChunks";
describe("manual chunk boundaries", () => {
it.each([
@@ -10,10 +10,9 @@ describe("manual chunk boundaries", () => {
["/repo/node_modules/clsx/dist/clsx.mjs", "vendor-core-utils"],
["/repo/node_modules/tailwind-merge/dist/lib/index.mjs", "vendor-core-utils"],
["/repo/node_modules/class-variance-authority/dist/index.mjs", "vendor-core-utils"],
["/repo/node_modules/tslib/tslib.es6.mjs", "vendor-tslib"],
["/repo/node_modules/recharts/es6/index.js", "vendor-charts"],
["/repo/node_modules/d3-shape/src/index.js", "vendor-charts"],
["/repo/node_modules/@monaco-editor/react/dist/index.mjs", "vendor-monaco"],
["/repo/node_modules/monaco-editor/esm/vs/editor/editor.api.js", "vendor-monaco"],
["/repo/node_modules/marked/lib/marked.esm.js", "vendor-markdown"],
["/repo/node_modules/katex/dist/katex.mjs", "vendor-markdown"],
["/repo/node_modules/@tiptap/react/dist/index.js", "vendor-editor-tiptap"],
@@ -28,11 +27,10 @@ describe("manual chunk boundaries", () => {
expect(getManualChunkName(id)).toBe(chunkName);
});
it("supports Windows-like node_modules paths from Rollup ids", () => {
expect(getManualChunkName("C:\\repo\\node_modules\\monaco-editor\\esm\\vs\\editor\\editor.api.js")).toBe("vendor-monaco");
});
it.each([
"/repo/node_modules/@monaco-editor/react/dist/index.mjs",
"/repo/node_modules/monaco-editor/esm/vs/editor/editor.api.js",
"C:\\repo\\node_modules\\monaco-editor\\esm\\vs\\editor\\editor.api.js",
"/repo/apps/web/app/components/monaco-editor/FakeEditor.tsx",
"/repo/apps/web/app/routes/workflows/workflow-builder.tsx",
"/repo/node_modules/streamdown/dist/index.js",
@@ -47,3 +45,12 @@ describe("manual chunk boundaries", () => {
expect(getManualChunkName(id)).toBeUndefined();
});
});
describe("lazy runtime chunk filenames", () => {
it("gives Monaco and PDF.js descendants stable lazy-runtime prefixes", () => {
expect(getChunkFileName(["/repo/node_modules/monaco-editor/esm/vs/editor/editor.api.js"])).toBe("assets/lazy-monaco-[name]-[hash].js");
expect(getChunkFileName(["C:\\repo\\node_modules\\@monaco-editor\\react\\dist\\index.mjs"])).toBe("assets/lazy-monaco-[name]-[hash].js");
expect(getChunkFileName(["/repo/node_modules/pdfjs-dist/build/pdf.mjs"])).toBe("assets/lazy-pdfjs-[name]-[hash].js");
expect(getChunkFileName(["/repo/apps/web/app/root.tsx"])).toBe("assets/[name]-[hash].js");
});
});
@@ -3,9 +3,16 @@ const NODE_MODULES_SEGMENT = "/node_modules/";
const CHUNK_MATCHERS: Array<{ chunkName: string; packages: string[] }> = [
{ chunkName: "vendor-react", packages: ["react", "react-dom", "react-router", "scheduler", "use-sync-external-store"] },
{ chunkName: "vendor-core-utils", packages: ["clsx", "tailwind-merge", "class-variance-authority"] },
// Keep the shared TypeScript runtime helpers out of lazily loaded vendor
// chunks. Otherwise Rollup can pull a 1+ MiB AWS chunk into SSR startup just
// because the main bundle also needs `__assign`/`__extends`.
{ chunkName: "vendor-tslib", packages: ["tslib"] },
{ chunkName: "vendor-charts", packages: ["recharts", "victory-vendor", "d3-", "d3"] },
{ chunkName: "vendor-markdown", packages: ["marked", "katex"] },
{ chunkName: "vendor-monaco", packages: ["@monaco-editor/react", "monaco-editor"] },
// Monaco is already behind a client-only dynamic import. Let Rollup keep
// that complete dependency graph at the lazy boundary: assigning it to a
// manual chunk can absorb Vite's preload helper and make the editor part of
// every route's static graph.
{ chunkName: "vendor-editor-tiptap", packages: ["@tiptap/"] },
{ chunkName: "vendor-editor-prosemirror", packages: ["prosemirror-"] },
{ chunkName: "vendor-pdf", packages: ["@react-pdf/renderer"] },
@@ -44,3 +51,14 @@ export function getManualChunkName(id: string): string | undefined {
return undefined;
}
export function getChunkFileName(moduleIds: readonly string[]): string {
const normalizedIds = moduleIds.map(normalizeModuleId);
if (normalizedIds.some((id) => id.includes("/node_modules/monaco-editor/") || id.includes("/node_modules/@monaco-editor/react/"))) {
return "assets/lazy-monaco-[name]-[hash].js";
}
if (normalizedIds.some((id) => id.includes("/node_modules/pdfjs-dist/"))) {
return "assets/lazy-pdfjs-[name]-[hash].js";
}
return "assets/[name]-[hash].js";
}
@@ -0,0 +1,17 @@
// @vitest-environment node
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, test } from "vitest";
describe("Tailwind and Subframe theme integration", () => {
test("addresses the Subframe white scale by shade in typography rules", () => {
const testDir = path.dirname(fileURLToPath(import.meta.url));
const config = fs.readFileSync(path.resolve(testDir, "../../../../../tailwind.config.ts"), "utf8");
const theme = fs.readFileSync(path.resolve(testDir, "../../ui/theme.css"), "utf8");
expect(theme).toContain("--color-white-1000:");
expect(config).toContain('theme("colors.white.1000")');
expect(config).not.toMatch(/theme\(["']colors\.white["']\)/);
});
});
@@ -9,7 +9,7 @@ describe("vite config integration wiring", () => {
it("wires the manual chunk helper into Rollup output without running a build", async () => {
const source = await readViteConfigSource();
expect(source).toContain('import { getManualChunkName } from "./app/utils/build/manualChunks";');
expect(source).toMatch(/import\s*\{[^}]*\bgetManualChunkName\b[^}]*\}\s*from\s*"\.\/app\/utils\/build\/manualChunks";/u);
expect(source).toMatch(/rollupOptions:\s*{[\s\S]*output:\s*{[\s\S]*manualChunks:\s*getManualChunkName/);
});
@@ -81,7 +81,10 @@ export function createRoutesFromFolders(defineRoutes: DefineRoutesFunction, opti
}
if (isRouteModuleFile(file)) {
let relativePath = path.join(routesDirectory, file);
// Route ids and manifest file paths are URL-like repo paths. Keep them
// POSIX-stable on Windows instead of leaking `path.join` backslashes into
// React Router's manifest.
let relativePath = normalizeSlashes(path.join(routesDirectory, file));
let routeId = createRouteId(relativePath);
files[routeId] = relativePath;
return;
@@ -373,6 +376,13 @@ function shouldCreateAdminHostRoute(routeId: string): boolean {
if (!routeId.startsWith("routes/admin/")) {
return false;
}
// /select-tenant exists on both app and admin hosts. Registering the admin
// file as a second pathless-host alias creates two identical manifest paths,
// and React Router always matches the admin branch first on the app host.
// The single public route dispatches to the correct loader by request host.
if (routeId === "routes/admin/select-tenant") {
return false;
}
const canonicalPath = createRoutePath(routeId.slice("routes/admin/".length));
if (!canonicalPath) {
@@ -394,23 +404,6 @@ function createAdminHostRoutePath(routeId: string, parentId: string): string | u
return createRoutePath(routeId.slice(parentId.length + 1));
}
function addPromotedTenantDescendantRouteIds(routeIds: string[]): string[] {
const routeIdSet = new Set(routeIds);
for (const routeId of routeIds) {
if (!routeId.startsWith("routes/app.$tenant/")) {
continue;
}
const segments = routeId.split("/");
for (let index = segments.length - 1; index > 1; index--) {
routeIdSet.add(segments.slice(0, index).join("/"));
}
}
return [...routeIdSet].sort(byLongestFirst);
}
function getParentRouteIds(routeIds: string[]): Record<string, string | undefined> {
return routeIds.reduce<Record<string, string | undefined>>(
(parentRouteIds, childRouteId) => ({
@@ -1,11 +1,13 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
// Cache-Abstraktion: getFreshValue direkt durchreichen (deterministisch, kein Cache-State zwischen Tests).
vi.mock("~/utils/cache.server", () => ({
cachified: vi.fn(async (opts: { getFreshValue: () => Promise<unknown> }) => opts.getFreshValue()),
clearCacheKeyPrefix: vi.fn(),
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: vi.fn((_context: unknown, callback: () => unknown) => callback()),
}));
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({
resolveTenantProductAccess: vi.fn(),
resolveTenantEntitlementSubscription: vi.fn(async () => null),
@@ -16,6 +18,7 @@ vi.mock("~/utils/services/.server/featureFlagEvaluator.server", () => ({
}));
import { clearCacheKeyPrefix } from "~/utils/cache.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTenantEntitlementSubscription, resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { evaluateFlagForContext } from "~/utils/services/.server/featureFlagEvaluator.server";
import { invalidateTenantModuleAccessCache, tenantHasFlag, tenantHasModule } from "./tenantConnector.server";
@@ -24,6 +27,7 @@ const resolveMock = vi.mocked(resolveTenantProductAccess);
const subscriptionMock = vi.mocked(resolveTenantEntitlementSubscription);
const flagMock = vi.mocked(evaluateFlagForContext);
const clearPrefixMock = vi.mocked(clearCacheKeyPrefix);
const rlsMock = vi.mocked(runWithRlsContext);
describe("tenantHasModule", () => {
beforeEach(() => {
@@ -39,6 +43,7 @@ describe("tenantHasModule", () => {
expect(allowed).toBe(true);
expect(subscriptionMock).toHaveBeenCalledWith("t1");
expect(resolveMock).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "t1", userId: "u1", featureKey: "crm-basic" }));
expect(rlsMock).toHaveBeenCalledWith({ tenantId: "t1", userId: "u1" }, expect.any(Function));
});
it("returns false when the product-access decision denies the module", async () => {
@@ -1,4 +1,5 @@
import { cachified, clearCacheKeyPrefix } from "~/utils/cache.server";
import { clearCacheKeyPrefix } from "~/utils/cache.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveTenantEntitlementSubscription, resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { evaluateFlagForContext } from "~/utils/services/.server/featureFlagEvaluator.server";
@@ -11,16 +12,16 @@ import { evaluateFlagForContext } from "~/utils/services/.server/featureFlagEval
* - `tenantHasModule()` — "Darf dieser Tenant dieses Modul nutzen?" Brücke Billing↔Feature-Gate:
* 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.
*
* - `tenantHasFlag()` — "Ist dieses Feature-Flag für diesen Kontext aktiv?" Delegiert an den
* v2-Evaluator {@link evaluateFlagForContext}, der bereits eigenen Eval-Cache mitbringt.
*
* Cache-Backing ist die App-Cache-Abstraktion (`~/utils/cache.server`, LRU heute, per
* `redisCacheAdapter` Redis-swappbar — Infra-Schalter, kein Logik-Eingriff).
* Der Connector selbst cached die kombinierte Entscheidung bewusst nicht:
* Subscription- und Permission-Resolver besitzen eigene, cross-replica
* invalidierte Caches. Ein zweiter lokaler Cache könnte eine Rollen- oder
* Abo-Änderung trotz korrekt invalidierter Quell-Caches weiter erlauben.
*/
const MODULE_CACHE_TTL_MS = 60_000;
const MODULE_CACHE_PREFIX = "connector:module:";
export interface TenantModuleAccessInput {
@@ -34,31 +35,22 @@ export interface TenantModuleAccessInput {
readonly bypassTenantRolePermission?: boolean;
}
function moduleCacheKey(input: TenantModuleAccessInput): string {
const scope = input.bypassTenantRolePermission ? "bypass" : "rbac";
return `${MODULE_CACHE_PREFIX}${input.tenantId}:${input.userId}:${input.moduleKey}:${scope}`;
}
/**
* Konnektor-Gate: Ist das Modul für den Tenant freigeschaltet?
*
* @returns `true`, wenn der Tenant das Modul nutzen darf (Abo + Blueprint + Override + Rolle ok).
*/
export async function tenantHasModule(input: TenantModuleAccessInput): Promise<boolean> {
return cachified({
key: moduleCacheKey(input),
ttl: MODULE_CACHE_TTL_MS,
getFreshValue: async () => {
const subscription = await resolveTenantEntitlementSubscription(input.tenantId);
const decision = await resolveTenantProductAccess({
tenantId: input.tenantId,
userId: input.userId,
featureKey: input.moduleKey,
subscription,
bypassTenantRolePermission: input.bypassTenantRolePermission,
});
return decision.allowed;
},
return runWithRlsContext({ tenantId: input.tenantId, userId: input.userId }, async () => {
const subscription = await resolveTenantEntitlementSubscription(input.tenantId);
const decision = await resolveTenantProductAccess({
tenantId: input.tenantId,
userId: input.userId,
featureKey: input.moduleKey,
subscription,
bypassTenantRolePermission: input.bypassTenantRolePermission,
});
return decision.allowed;
});
}
@@ -88,5 +80,7 @@ export async function tenantHasFlag(input: TenantFlagContext): Promise<boolean>
* Rollen-Änderungen (z.B. Billing-Sync, Admin-Plan-Wechsel), damit das Gate sofort nachzieht.
*/
export function invalidateTenantModuleAccessCache(tenantId: string): void {
// Rolling-deploy compatibility: remove entries produced by an older web
// process. Current code does not write connector-level decisions.
clearCacheKeyPrefix(`${MODULE_CACHE_PREFIX}${tenantId}:`);
}
@@ -1,46 +1,111 @@
import type { LoaderFunctionArgs } from "react-router";
import type { AdminDashboardVM } from "@hivegrid/view-models";
import {
isAdminRoleKey,
isAdminPermissionName,
type AdminPermissionName,
type AdminRoleKey,
} from "@hivegrid/db/admin-permissions";
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
import { getTranslations } from "~/locale/i18next.server";
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
import { adminGetAllTenantsWithUsage, type TenantWithUsage } from "~/utils/db/tenants.db.server";
import { getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
import PeriodHelper from "~/utils/helpers/PeriodHelper";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getAdminDashboardStats } from "~/utils/services/adminDashboardService";
import { getAdminDashboardOverview, getAdminDashboardStats, type AdminDashboardOverview } from "~/utils/services/adminDashboardService";
import type { Stat } from "~/application/dtos/stats/Stat";
import type { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import { ADMIN_AREA_ACCESS } from "~/services/admin/admin-access-contract";
import { loadPersonalizedAdminDashboard } from "~/services/admin/admin-dashboard-personalization.server";
import { db } from "~/utils/db.server";
export type AdminDashboardLoaderData = {
title: string;
stats: Stat[];
tenants: {
items: TenantWithUsage[];
pagination: PaginationDto;
};
dashboard: AdminDashboardVM;
superOverview: {
stats: Stat[];
overview: AdminDashboardOverview;
tenants: {
items: TenantWithUsage[];
pagination: PaginationDto;
};
} | null;
};
type AdminDashboardDataArgs = Pick<LoaderFunctionArgs, "request" | "params">;
export async function loadAdminDashboardRouteData({ request, params }: AdminDashboardDataArgs) {
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "admin.dashboard");
const urlSearchParams = new URL(request.url).searchParams;
const currentPagination = getPaginationFromCurrentUrl(urlSearchParams);
const { t } = await time(getTranslations(request), "getTranslations");
const { stats, tenants } = await time(
promiseHash({
stats: time(
getAdminDashboardStats({ t, gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }) }),
"admin.dashboard.details.getAdminDashboardStats"
),
tenants: time(adminGetAllTenantsWithUsage(undefined, currentPagination), "admin.dashboard.details.adminGetAllTenantsWithUsage"),
const { t, locale } = await time(getTranslations(request), "getTranslations");
const { dashboard, superOverview } = await time(
runAsAdminIdentity(request, ADMIN_AREA_ACCESS.dashboard, async (session) => {
const [permissionNames, roleRows] = await Promise.all([
listAdminPermissionNames(session.adminUserId),
db.adminUserRole.findMany({
where: {
adminUserId: session.adminUserId,
role: { active: true },
},
select: { role: { select: { systemKey: true } } },
orderBy: { createdAt: "asc" },
}),
]);
const permissions = permissionNames.filter(isAdminPermissionName);
const roleKeys = roleRows
.map((row) => row.role.systemKey)
.filter((roleKey): roleKey is AdminRoleKey =>
Boolean(roleKey && isAdminRoleKey(roleKey))
);
const dashboard = await loadPersonalizedAdminDashboard({
adminUserId: session.adminUserId,
roleKeys,
permissions: permissions as AdminPermissionName[],
locale,
});
const superOverview = roleKeys.includes("super_admin")
? await loadSuperAdminOverview(request, t, time)
: null;
return { dashboard, superOverview };
}),
"admin.dashboard.details"
"admin.dashboard.personalized"
);
const data: AdminDashboardLoaderData = {
title: `${t("app.sidebar.dashboard")} | ${process.env.APP_NAME}`,
stats,
tenants,
dashboard,
superOverview,
};
return { data, headers: getServerTimingHeader() };
}
async function loadSuperAdminOverview(
request: Request,
t: (key: string) => string,
time: <T>(promise: Promise<T>, name: string) => Promise<T>
) {
const currentPagination = getPaginationFromCurrentUrl(
new URL(request.url).searchParams
);
return time(
promiseHash({
stats: time(
getAdminDashboardStats({
t,
gte: PeriodHelper.getGreaterThanOrEqualsFromRequest({ request }),
}),
"admin.dashboard.details.getAdminDashboardStats"
),
overview: time(
getAdminDashboardOverview(),
"admin.dashboard.details.getAdminDashboardOverview"
),
tenants: time(
adminGetAllTenantsWithUsage(undefined, currentPagination),
"admin.dashboard.details.adminGetAllTenantsWithUsage"
),
}),
"admin.dashboard.super"
);
}
@@ -6,19 +6,20 @@ function readAdminDataSource() {
return readRepoFile("apps/web/app/utils/data/.server/adminData.ts");
}
describe("admin data MFA enforcement boundary", () => {
describe("admin data Authentik MFA assurance boundary", () => {
test("does not import MFA secret or recovery-code storage directly", () => {
const source = readAdminDataSource();
expect(source).not.toMatch(/mfaRecoveryCode|totpSecret|encryptedTotpSecret/i);
});
test("routes shared admin loader through the MFA enforcement boundary", () => {
test("accepts only a validated tenantless AdminSession", () => {
const source = readAdminDataSource();
expect(source).toContain("getUserTotpStatus");
expect(source).toContain("checkMfaStepUpState");
expect(source).toContain("enforceAdminMfa");
expect(source).toMatch(/if \(!mfaEnforcement\.allowed\) \{\s*throw redirect\(mfaEnforcement\.redirectTo\);\s*\}/);
expect(source).toContain("getValidatedServerSession");
expect(source).toContain('"adminUser" in validatedSession');
expect(source).toContain("validatedSession.adminUser");
expect(source).not.toContain("getUserTotpStatus");
expect(source).not.toContain("enforceAdminMfa");
});
});
@@ -1,81 +1,77 @@
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { TimeFunction } from "~/modules/metrics/services/.server/MetricTracker";
import OnboardingService from "~/modules/onboarding/services/OnboardingService";
import UrlUtils from "~/utils/app/UrlUtils";
import { getMyGroups } from "~/utils/db/permissions/groups.db.server";
import { getAllRolesWithoutPermissions } from "~/utils/db/permissions/roles.db.server";
import { getPermissionsByUser, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
import { getTenantsForUser as getMyTenants } from "@hivegrid/db/auth-boundary.server";
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
import { getUserTotpStatus } from "~/utils/db/users.db.server";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getUserInfo, getUserSession } from "~/utils/session.server";
import { AdminLoaderData } from "../useAdminData";
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
import { TFunction } from "i18next";
import type { TFunction } from "i18next";
import { redirect } from "react-router";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export async function loadAdminData({ request, t }: { request: Request; t: TFunction }, time: TimeFunction) {
import { adminGetAllActiveTenants } from "@hivegrid/db/auth-boundary.server";
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import type { TimeFunction } from "~/modules/metrics/services/.server/MetricTracker";
import UrlUtils from "~/utils/app/UrlUtils";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
import { getUserInfo, getValidatedServerSession } from "~/utils/session.server";
import type { AdminLoaderData } from "../useAdminData";
export async function loadAdminData({ request, t: _t }: { request: Request; t: TFunction }, time: TimeFunction) {
const userInfo = await time(getUserInfo(request), "getUserInfo");
const url = new URL(request.url);
if (UrlUtils.stripTrailingSlash(url.pathname) === `/admin`) {
if (UrlUtils.stripTrailingSlash(url.pathname) === "/admin") {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const user = await time(getUser(userInfo?.userId), "getUser");
const redirectTo = url.pathname + url.search;
if (!userInfo || !user) {
let searchParams = new URLSearchParams([["redirect", redirectTo]]);
if (!userInfo.userId) {
const searchParams = new URLSearchParams([["redirect", url.pathname + url.search]]);
throw redirect(`/login?${searchParams}`);
}
if (!user.admin) {
throw Response.json({ error: t("admin.errors.adminOnly") }, { status: 401 });
const validatedSession = await time(getValidatedServerSession(request, userInfo), "getValidatedAdminSession");
if (!validatedSession || !("adminUser" in validatedSession)) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const admin = validatedSession.adminUser;
const session = await time(getUserSession(request), "getUserSession");
const totpStatus = await time(getUserTotpStatus(user.id), "getUserTotpStatus");
const stepUp = checkMfaStepUpState(session, user.id);
const mfaEnforcement = enforceAdminMfa({
requestUrl: url,
userId: user.id,
isAdmin: Boolean(user.admin),
totpStatus,
stepUp,
redirectMode: "host-aware",
});
if (!mfaEnforcement.allowed) {
throw redirect(mfaEnforcement.redirectTo);
}
const myTenants = await time(getMyTenants(user.id), "getMyTenants");
const { allPermissions, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
promiseHash({
allPermissions: getPermissionsByUser(userInfo.userId, null),
superAdminRole: getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin),
allRoles: getAllRolesWithoutPermissions("admin"),
myGroups: getMyGroups(user.id, null),
onboardingSession: OnboardingService.getUserActiveOnboarding({ userId: user.id, tenantId: null, request }),
}),
const { permissions, roles, myTenants } = await time(
runWithRlsContext({ userId: admin.id }, async () => ({
permissions: await listAdminPermissionNames(admin.id),
roles: await db.adminRole.findMany({
where: { active: true },
select: { id: true, name: true, description: true },
orderBy: { name: "asc" },
}),
myTenants: await adminGetAllActiveTenants(),
})),
"loadAdminData.getDetails"
);
const isSuperAdmin = await runWithRlsContext({ userId: admin.id }, () =>
db.adminUserRole.findFirst({
where: { adminUserId: admin.id, role: { systemKey: "super_admin", active: true } },
select: { adminUserId: true },
})
);
const data: AdminLoaderData = {
user,
user: {
id: admin.id,
email: admin.email,
firstName: admin.firstName,
lastName: admin.lastName,
avatar: admin.avatar,
phone: null,
admin: { userId: admin.id },
defaultTenantId: null,
createdAt: validatedSession.createdAt,
locale: admin.locale,
lightOrDarkMode: null,
},
myTenants,
currentTenant: null,
// roles,
allRoles,
permissions: allPermissions.map((f) => f as DefaultPermission),
isSuperUser: !!superAdminRole,
isSuperAdmin: !!superAdminRole,
myGroups,
lng: user?.locale ?? userInfo.lng,
onboardingSession,
tenantTypes: await getAllTenantTypes(),
allRoles: roles,
permissions: permissions as DefaultPermission[],
isSuperUser: isSuperAdmin !== null,
isSuperAdmin: isSuperAdmin !== null,
myGroups: [],
lng: admin.locale ?? userInfo.lng,
onboardingSession: null,
};
return data;
}
@@ -0,0 +1,84 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
const state = vi.hoisted(() => ({ superAdmin: false }));
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "de" })) }));
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
getAuthUserWithoutPasswordById: vi.fn(async () => ({
id: "user_1",
admin: { ssoProvider: "authentik", ssoGroups: ["hivegrid-staff"] },
locale: "de",
})),
getTenantsForUser: vi.fn(async () => [{ id: "tenant_1", slug: "acme", name: "Member tenant" }]),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
adminGetAllActiveTenantSimple: vi.fn(async () => [
{ id: "tenant_1", slug: "acme", name: "Member tenant" },
{ id: "tenant_2", slug: "global", name: "Global tenant" },
]),
getTenantSimple: vi.fn(async () => ({ id: "tenant_1", slug: "acme", name: "Member tenant", deactivatedReason: null })),
getTenantUserType: vi.fn(async () => ({ type: TenantUserType.MEMBER })),
}));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: vi.fn(() => ({ routing: {} })) }));
vi.mock("~/utils/db/permissions/groups.db.server", () => ({ getMyGroups: vi.fn(async () => []) }));
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRolesWithoutPermissions: vi.fn(async () => []) }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
getPermissionsByUser: vi.fn(async () => []),
getUserRoleInAdmin: vi.fn(async () => (state.superAdmin ? { id: "superadmin_assignment" } : null)),
getUserRoleInTenant: vi.fn(async () => null),
}));
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn(async () => []) }));
vi.mock("~/utils/services/.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(async () => ({ products: [] })),
getPlanFeatureUsage: vi.fn(async () => undefined),
}));
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn(async () => null) } }));
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({ resolveTenantProductAccessBatch: vi.fn(async () => []) }));
import { getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
import { adminGetAllActiveTenantSimple } from "~/utils/db/tenants.db.server";
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
import { loadAppData } from "./appData";
function load() {
return loadAppData({
request: new Request("https://app.example.test/acme/dashboard"),
params: { tenant: "acme" },
t: ((key: string) => key) as never,
});
}
describe("loadAppData operator boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
state.superAdmin = false;
});
it("keeps Authentik staff tenant-scoped despite having an AdminUser identity", async () => {
const data = await load();
expect(data.isSuperAdmin).toBe(false);
expect(data.currentRole).toBe(TenantUserType.MEMBER);
expect(data.myTenants).toHaveLength(1);
expect(getTenantsForUser).toHaveBeenCalledWith("user_1");
expect(adminGetAllActiveTenantSimple).not.toHaveBeenCalled();
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: false }));
});
it("grants global tenant enumeration and product bypass only to the SuperAdmin RBAC role", async () => {
state.superAdmin = true;
const data = await load();
expect(data.isSuperAdmin).toBe(true);
expect(data.currentRole).toBe(TenantUserType.ADMIN);
expect(data.myTenants).toHaveLength(2);
expect(adminGetAllActiveTenantSimple).toHaveBeenCalledOnce();
expect(getTenantsForUser).not.toHaveBeenCalled();
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: true }));
});
});
@@ -18,9 +18,8 @@ function deferred<T>(): Deferred<T> {
const mocks = vi.hoisted(() => {
const postDetails = {
tenantUser: deferred<{ type: TenantUserType }>(),
tenantTypes: deferred<unknown[]>(),
credits: deferred<unknown>(),
productAccess: deferred<{ allowed: boolean }>(),
productAccess: deferred<Array<readonly [string, { allowed: boolean }]>>(),
};
return { postDetails };
});
@@ -28,7 +27,11 @@ const mocks = vi.hoisted(() => {
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(async () => "tenant_1") }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(async () => ({ userId: "user_1", lng: "en" })) }));
vi.mock("@hivegrid/db/auth-boundary.server", () => ({
getAuthUserWithoutPasswordById: vi.fn(async () => ({ id: "user_1", admin: false, locale: "en" })),
getAuthUserWithoutPasswordById: vi.fn(async () => ({
id: "user_1",
admin: { ssoProvider: "authentik", ssoGroups: ["hivegrid-staff"] },
locale: "en",
})),
getTenantsForUser: vi.fn(async () => [{ id: "tenant_1", slug: "acme", name: "Acme" }]),
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
@@ -44,20 +47,20 @@ vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
getUserRoleInAdmin: vi.fn(async () => null),
getUserRoleInTenant: vi.fn(async () => null),
}));
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn(() => mocks.postDetails.tenantTypes.promise) }));
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
vi.mock("~/utils/services/.server/subscriptionService", () => ({
getActiveTenantSubscriptions: vi.fn(async () => ({ products: [] })),
getPlanFeatureUsage: vi.fn(() => mocks.postDetails.credits.promise),
}));
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn(async () => null) } }));
vi.mock("~/utils/entitlements/.server/productAccess.server", () => ({
resolveTenantProductAccess: vi.fn(() => mocks.postDetails.productAccess.promise),
resolveTenantProductAccessBatch: vi.fn(() => mocks.postDetails.productAccess.promise),
}));
import { getTenantUserType } from "~/utils/db/tenants.db.server";
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
import { adminGetAllActiveTenantSimple, getTenantUserType } from "~/utils/db/tenants.db.server";
import { getTenantsForUser } from "@hivegrid/db/auth-boundary.server";
import { getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
import { loadAppData } from "./appData";
async function flushAsyncWork() {
@@ -75,19 +78,20 @@ describe("loadAppData performance", () => {
await flushAsyncWork();
expect(getTenantUserType).toHaveBeenCalledWith("user_1", "tenant_1");
expect(getAllTenantTypes).toHaveBeenCalled();
expect(getPlanFeatureUsage).toHaveBeenCalledWith("tenant_1", "ai-credits");
expect(resolveTenantProductAccess).toHaveBeenCalled();
expect(resolveTenantProductAccessBatch).toHaveBeenCalledTimes(1);
expect(getTenantsForUser).toHaveBeenCalledWith("user_1");
expect(adminGetAllActiveTenantSimple).not.toHaveBeenCalled();
mocks.postDetails.tenantUser.resolve({ type: TenantUserType.MEMBER });
mocks.postDetails.tenantTypes.resolve([]);
mocks.postDetails.credits.resolve(undefined);
mocks.postDetails.productAccess.resolve({ allowed: true });
mocks.postDetails.productAccess.resolve([["dashboard", { allowed: true }]]);
await expect(result).resolves.toMatchObject({
currentRole: TenantUserType.MEMBER,
tenantTypes: [],
isSuperAdmin: false,
productAccess: expect.any(Object),
});
expect(resolveTenantProductAccessBatch).toHaveBeenCalledWith(expect.objectContaining({ bypassTenantRolePermission: false }));
});
});
@@ -15,9 +15,10 @@ vi.mock("~/utils/db/permissions/groups.db.server", () => ({ getMyGroups: vi.fn()
vi.mock("~/utils/db/permissions/roles.db.server", () => ({ getAllRolesWithoutPermissions: vi.fn() }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
getPermissionsByUser: vi.fn(),
getUserRoleInAdmin: vi.fn(),
getUserRoleInAdmin: vi.fn(async () => null),
getUserRoleInTenant: vi.fn(),
}));
vi.mock("~/utils/db/permissions/seatType.db.server", () => ({ getUserEffectiveSeatType: vi.fn(async () => "office") }));
vi.mock("~/utils/db/tenants/tenantTypes.db.server", () => ({ getAllTenantTypes: vi.fn() }));
vi.mock("~/utils/services/.server/subscriptionService", () => ({ getActiveTenantSubscriptions: vi.fn(), getPlanFeatureUsage: vi.fn() }));
vi.mock("~/modules/onboarding/services/OnboardingService", () => ({ default: { getUserActiveOnboarding: vi.fn() } }));
@@ -9,4 +9,15 @@ describe("loadAppData tenant role lookup", () => {
expect(source).toContain("getTenantUserType(userInfo.userId, tenantId)");
expect(source).not.toContain("getTenantUserType(tenantId, userInfo.userId)");
});
test("builds the shell billing banner from normalized subscription data", () => {
const source = readRepoFile("apps/web/app/utils/data/.server/appData.ts");
expect(source).toContain("billingBanner = buildSubscriptionBannerVM({");
expect(source).toContain("status: normalizeBillingSubscriptionStatus(mySubscription?.status");
expect(source).toContain("frozenAt: mySubscription?.frozenAt");
expect(source).toContain("cancelledAt: mySubscription?.cancelledAt");
expect(source).toContain("trialEndsAt: mySubscription?.trialEndsAt");
expect(source).toContain("billingBanner,");
});
});
@@ -9,12 +9,14 @@ import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import UrlUtils from "~/utils/app/UrlUtils";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { normalizeBillingSubscriptionStatus } from "@hivegrid/db/billing-domain.server";
import { buildSubscriptionBannerVM } from "@hivegrid/view-models";
import { getMyGroups } from "~/utils/db/permissions/groups.db.server";
import { getAllRolesWithoutPermissions } from "~/utils/db/permissions/roles.db.server";
import { getPermissionsByUser, getUserRoleInTenant, getUserRoleInAdmin } from "~/utils/db/permissions/userRoles.db.server";
import { getUserEffectiveSeatType } from "~/utils/db/permissions/seatType.db.server";
import { adminGetAllActiveTenantSimple, getTenantSimple, getTenantUserType } from "~/utils/db/tenants.db.server";
import { getAuthUserWithoutPasswordById as getUser, getTenantsForUser as getMyTenants } from "@hivegrid/db/auth-boundary.server";
import { getAllTenantTypes } from "~/utils/db/tenants/tenantTypes.db.server";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getActiveTenantSubscriptions, getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
@@ -25,7 +27,7 @@ import { CreditTypes } from "~/modules/usage/dtos/CreditType";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { TFunction } from "i18next";
import { featureKeys, type FeatureKey } from "@hivegrid/entitlements";
import { resolveTenantProductAccess } from "~/utils/entitlements/.server/productAccess.server";
import { resolveTenantProductAccessBatch } from "~/utils/entitlements/.server/productAccess.server";
import { WALKING_SKELETON_MODULE_KEY } from "~/modules/walkingSkeleton/constants";
// Every feature key the AppSidebar gates on via hasFeatureAccess() MUST be
@@ -43,8 +45,11 @@ const tenantNavigationFeatureKeys = [
featureKeys.tasks,
featureKeys.hr,
featureKeys.integrations,
featureKeys.telephony,
featureKeys.chat,
featureKeys.booking,
featureKeys.forms,
featureKeys.billing,
featureKeys.search,
featureKeys.automation,
featureKeys.emailMarketing,
@@ -52,6 +57,8 @@ const tenantNavigationFeatureKeys = [
featureKeys.api,
featureKeys.workflowEngine,
featureKeys.credits,
// Not a sidebar entry: gates the topbar "Mit KI verbinden" launcher (VD-MCP).
featureKeys.mcp,
] as const satisfies readonly FeatureKey[];
// R-P1c: Konnektor-Demo-Modul (kein Entitlement-FeatureKey) — speist das Sidebar-Gate der
@@ -86,13 +93,25 @@ export async function loadAppData({
);
const url = new URL(request.url);
const { user, currentTenant } = await time(
const operatorAdminPromise: Promise<boolean> =
preloadedIsOperatorAdmin !== undefined
? Promise.resolve(preloadedIsOperatorAdmin)
: userInfo?.userId
? getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin).then((role) => Boolean(role))
: Promise.resolve(false);
const {
user,
currentTenant,
operatorAdmin: operatorAdminValue,
} = await time(
promiseHash({
user: preloadedUser ? Promise.resolve(preloadedUser) : getUser(userInfo?.userId),
currentTenant: getTenantSimple(tenantId),
operatorAdmin: operatorAdminPromise,
}),
"loadAppData.getUserAndTenant"
);
const operatorAdmin = operatorAdminValue === true;
const redirectTo = url.pathname + url.search;
if (!userInfo || !user) {
@@ -111,52 +130,53 @@ export async function loadAppData({
if (UrlUtils.stripTrailingSlash(url.pathname) === UrlUtils.stripTrailingSlash(appPath({ tenantSlug: tenantPathSegment, mode: "host-aware" }))) {
throw redirect(`${appPath({ tenantSlug: currentTenant.slug, path: "dashboard", mode: "host-aware" })}${url.search}`);
}
const operatorAdmin = Boolean(user.admin) || Boolean(preloadedIsOperatorAdmin);
let { myTenants, mySubscription, allPermissions, superUserRole, superAdminRole, allRoles, myGroups, onboardingSession } = await time(
let { myTenants, mySubscription, allPermissions, superUserRole, allRoles, myGroups, onboardingSession, effectiveSeatType } = await time(
promiseHash({
myTenants: time(operatorAdmin ? adminGetAllActiveTenantSimple() : getMyTenants(user.id), "loadAppData.getDetails.getMyTenants"),
mySubscription: time(getActiveTenantSubscriptions(tenantId), "loadAppData.getDetails.getActiveTenantSubscriptions"),
allPermissions: time(getPermissionsByUser(userInfo.userId, tenantId), "loadAppData.getDetails.getPermissionsByUser"),
superUserRole: time(getUserRoleInTenant(userInfo.userId, tenantId, DefaultAppRoles.SuperUser), "loadAppData.getDetails.getUserRoleInTenant"),
superAdminRole: time(getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin), "loadAppData.getDetails.getUserRoleInAdmin"),
allRoles: time(getAllRolesWithoutPermissions("app"), "loadAppData.getDetails.getAllRolesWithoutPermissions"),
myGroups: time(getMyGroups(user.id, currentTenant.id), "loadAppData.getDetails.getMyGroups"),
onboardingSession: time(
OnboardingService.getUserActiveOnboarding({ userId: user.id, tenantId: currentTenant.id, request }),
"loadAppData.getDetails.OnboardingService.getUserActiveOnboarding"
),
effectiveSeatType: time(getUserEffectiveSeatType(userInfo.userId, tenantId), "loadAppData.getDetails.getUserEffectiveSeatType"),
}),
"loadAppData.getDetails"
);
const { tenantUser, tenantTypes, credits, productAccessEntries } = await time(
const { tenantUser, credits, productAccessEntries } = await time(
promiseHash({
tenantUser: time(getTenantUserType(userInfo.userId, tenantId), "loadAppData.postDetails.getTenantUserType"),
tenantTypes: time(getAllTenantTypes(), "loadAppData.postDetails.getAllTenantTypes"),
credits:
CreditTypes.length > 0
? time(getPlanFeatureUsage(tenantId, DefaultFeatures.Credits), "loadAppData.postDetails.getPlanFeatureUsage")
: Promise.resolve(undefined as PlanFeatureUsageDto | undefined),
productAccessEntries: time(
Promise.all(
[...tenantNavigationFeatureKeys, ...tenantConnectorDemoModuleKeys].map(async (featureKey) => [
featureKey,
await resolveTenantProductAccess({
tenantId,
userId: userInfo.userId,
featureKey,
subscription: mySubscription,
tenantRolePermissionNames: allPermissions,
bypassTenantRolePermission: operatorAdmin || !!superAdminRole,
}),
] as const)
),
"loadAppData.postDetails.resolveTenantProductAccess"
resolveTenantProductAccessBatch({
tenantId,
userId: userInfo.userId,
featureKeys: [...tenantNavigationFeatureKeys, ...tenantConnectorDemoModuleKeys],
subscription: mySubscription,
tenantRolePermissionNames: allPermissions,
bypassTenantRolePermission: operatorAdmin,
}),
"loadAppData.postDetails.resolveTenantProductAccessBatch"
),
}),
"loadAppData.postDetails"
);
const currentRole = operatorAdmin ? TenantUserType.ADMIN : tenantUser?.type ?? TenantUserType.MEMBER;
const currentRole = operatorAdmin ? TenantUserType.ADMIN : (tenantUser?.type ?? TenantUserType.MEMBER);
const billingBanner = buildSubscriptionBannerVM({
status: normalizeBillingSubscriptionStatus(mySubscription?.status, {
frozenAt: mySubscription?.frozenAt,
cancelledAt: mySubscription?.cancelledAt,
}),
hasSubscription: mySubscription !== null,
trialEndsAt: mySubscription?.trialEndsAt,
});
const data: AppLoaderData = {
// i18n: i18n.translations,
user,
@@ -164,17 +184,18 @@ export async function loadAppData({
currentTenant,
currentRole,
mySubscription,
billingBanner,
// roles,
allRoles,
permissions: allPermissions.map((f) => f as DefaultPermission),
myGroups,
isSuperUser: !!superUserRole,
isSuperAdmin: !!superAdminRole,
isSuperAdmin: operatorAdmin,
lng: user?.locale ?? userInfo.lng,
onboardingSession,
tenantTypes,
credits,
productAccess: Object.fromEntries(productAccessEntries),
effectiveSeatType,
};
return data;
}
@@ -4,7 +4,8 @@ import { Params } from "react-router";
import { AnalyticsInfoDto } from "~/application/dtos/marketing/AnalyticsInfoDto";
import { ImpersonatingSessionDto } from "~/application/dtos/session/ImpersonatingSessionDto";
import { CookieCategory } from "~/application/cookies/CookieCategory";
import { remixI18Next, i18nCookie } from "~/locale/i18next.server";
import { enabledLocales, remixI18Next, i18nCookie } from "~/locale/i18next.server";
import { resolveEnabledLocale } from "~/locale/i18n";
import { resolveAnrede } from "~/locale/anrede.server";
import { getCurrentEnabledFlagNames } from "~/utils/services/.server/featureFlagsRequest.server";
import { createMetrics } from "~/modules/metrics/services/.server/MetricTracker";
@@ -13,12 +14,20 @@ import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import AnalyticsService from "~/utils/helpers/.server/AnalyticsService";
import CookieHelper from "~/utils/helpers/CookieHelper";
import { promiseHash } from "~/utils/promises/promiseHash";
import { getUserInfo, getUserSession, setCSRFToken, createUserSession, commitSession } from "~/utils/session.server";
import { getUserInfo, getUserSession, getValidatedServerSession, setCSRFToken, createUserSession, commitSession } from "~/utils/session.server";
import { getAbsoluteApiUrl, getAbsoluteUrl, getBaseURL, getDomainName } from "~/utils/url.server";
import { createScopedLogger } from "~/utils/logger.server";
import { AppRootData } from "../useRootData";
import { CSP_NONCE_REQUEST_HEADER, buildDocumentContentSecurityPolicy, getRequestCspNonce } from "~/utils/security/contentSecurityPolicy";
import { getRequestDocumentContentSecurityPolicyOptions } from "~/utils/security/requestContentSecurityPolicy.server";
const rootDataLogger = createScopedLogger("root-data");
const browserBuildEnv = ((import.meta as unknown as { env?: Record<string, string | undefined> }).env ?? {}) as Record<string, string | undefined>;
export async function loadRootData({ request, params }: { request: Request; params: Params }) {
const { time, getServerTimingHeader } = await createMetrics({ request, params }, "root");
const appConfigurationPromise = time(getAppConfiguration({ request }), "getAppConfiguration");
const localePromise = remixI18Next.getLocale(request);
const { userInfo, session, analyticsSession } = await time(
promiseHash({
userInfo: getUserInfo(request),
@@ -27,27 +36,91 @@ export async function loadRootData({ request, params }: { request: Request; para
}),
"loadRootData.session"
);
const user = userInfo.userId ? await getUser(userInfo.userId) : null;
const currentTenant = params.tenant ? await getTenantByIdOrSlug(params.tenant) : user?.defaultTenantId ? await getTenant(user.defaultTenantId) : null;
const [validatedSession, routeTenant] = await Promise.all([
userInfo.userId && !userInfo.impersonatingFromUserId ? getValidatedServerSession(request, userInfo) : Promise.resolve(null),
params.tenant ? getTenantByIdOrSlug(params.tenant) : Promise.resolve(null),
]);
const user =
validatedSession && "user" in validatedSession
? validatedSession.user
: validatedSession && "adminUser" in validatedSession
? {
id: validatedSession.adminUser.id,
email: validatedSession.adminUser.email,
firstName: validatedSession.adminUser.firstName,
lastName: validatedSession.adminUser.lastName,
avatar: validatedSession.adminUser.avatar,
phone: null,
admin: { userId: validatedSession.adminUser.id },
defaultTenantId: null,
createdAt: validatedSession.createdAt,
locale: validatedSession.adminUser.locale,
lightOrDarkMode: null,
}
: userInfo.userId
? await getUser(userInfo.userId)
: null;
const currentTenant = params.tenant ? routeTenant : user?.defaultTenantId ? await getTenant(user.defaultTenantId) : null;
const existingCsrf = session.get("csrf");
const csrf = typeof existingCsrf === "string" && existingCsrf.length > 0 ? existingCsrf : setCSRFToken(session);
let analytics: AnalyticsInfoDto | undefined = undefined;
const appConfiguration = await time(getAppConfiguration({ request }), "getAppConfiguration");
const [appConfiguration, detectedLocale] = await Promise.all([appConfigurationPromise, localePromise]);
const locale = resolveEnabledLocale({
enabledLocales,
userLocale: user?.locale,
cookieLocale: detectedLocale,
acceptLanguage: request.headers.get("Accept-Language"),
});
const hasAnalyticsConsent = CookieHelper.hasConsent(userInfo, CookieCategory.ANALYTICS);
if (appConfiguration.analytics.enabled && hasAnalyticsConsent) {
try {
analytics = await AnalyticsService.getFromRequest({ appConfiguration, request, userId: userInfo.userId ?? null });
} catch (e: any) {
// eslint-disable-next-line no-console
console.error(e.message);
}
}
const analyticsPromise: Promise<AnalyticsInfoDto | undefined> =
appConfiguration.analytics.enabled && hasAnalyticsConsent
? AnalyticsService.getFromRequest({ appConfiguration, request, userId: userInfo.userId ?? null }).catch((error: unknown) => {
rootDataLogger.warn({ err: { name: error instanceof Error ? error.name : "Error" } }, "analytics request enrichment failed");
return undefined;
})
: Promise.resolve(undefined);
const impersonatingSessionPromise: Promise<ImpersonatingSessionDto | null> =
userInfo.impersonatingFromAdminUserId && userInfo.impersonatingFromAdminEmail && userInfo.userId?.length > 0
? getUser(userInfo.userId).then((toUser) =>
toUser
? {
fromUser: { id: userInfo.impersonatingFromAdminUserId!, email: userInfo.impersonatingFromAdminEmail! },
toUser: { id: toUser.id, email: toUser.email },
}
: null
)
: userInfo.impersonatingFromUserId && userInfo.userId?.length > 0
? Promise.all([getUser(userInfo.impersonatingFromUserId), getUser(userInfo.userId)]).then(([fromUser, toUser]) =>
fromUser && toUser ? { fromUser, toUser } : null
)
: Promise.resolve(null);
const anredePromise = resolveAnrede(request, currentTenant);
const featureFlagsPromise = appConfiguration.featureFlags.enabled ? getCurrentEnabledFlagNames({ request, params }) : Promise.resolve([] as string[]);
const sessionCookiePromise = commitSession(session);
const [resolvedAnalytics, impersonatingSession, anrede, featureFlags, sessionCookie] = await Promise.all([
analyticsPromise,
impersonatingSessionPromise,
anredePromise,
featureFlagsPromise,
sessionCookiePromise,
]);
let analytics = resolvedAnalytics;
const webConfig = loadRequiredWebConfig();
const headers = new Headers();
const cspNonce = getRequestCspNonce(request);
if (cspNonce) {
headers.set(CSP_NONCE_REQUEST_HEADER, cspNonce);
headers.set(
"Content-Security-Policy",
buildDocumentContentSecurityPolicy(cspNonce, undefined, getRequestDocumentContentSecurityPolicyOptions(request, webConfig, process.env, browserBuildEnv))
);
}
let userAnalyticsId = analyticsSession.get("userAnalyticsId");
headers.append("Set-Cookie", await commitSession(session));
headers.append("Set-Cookie", sessionCookie);
if (hasAnalyticsConsent) {
if (!userAnalyticsId) {
userAnalyticsId = generateAnalyticsUserId();
@@ -62,27 +135,16 @@ export async function loadRootData({ request, params }: { request: Request; para
headers.append("Set-Cookie", await destroyAnalyticsSession(analyticsSession));
}
let impersonatingSession: ImpersonatingSessionDto | null = null;
if (userInfo.impersonatingFromUserId && userInfo.userId?.length > 0) {
const fromUser = await getUser(userInfo.impersonatingFromUserId);
const toUser = await getUser(userInfo.userId);
if (fromUser && toUser) {
impersonatingSession = { fromUser, toUser };
}
}
const locale = await remixI18Next.getLocale(request);
// Formality axis (du/Sie). Default "du" → `effectiveLng(locale, "du") === locale`,
// so the language handed to `useChangeLanguage` in root.tsx is unchanged and
// rendering stays byte-identical. The tenant's persisted default applies when
// no explicit cookie/param is present.
const anrede = await resolveAnrede(request, currentTenant);
const webConfig = loadRequiredWebConfig();
const data: AppRootData = {
metatags: [{ title: webConfig.appName }],
user,
currentTenant,
locale,
enabledLocales,
anrede,
theme: userInfo.theme || appConfiguration.app.theme,
serverUrl: getBaseURL(request),
@@ -90,7 +152,7 @@ export async function loadRootData({ request, params }: { request: Request; para
apiBaseUrl: getAbsoluteApiUrl(request, "/"),
routing: webConfig.routing,
domainName: getDomainName(request),
userSession: userInfo,
userSession: { ...userInfo, lng: locale },
authenticated: userInfo.userId?.length > 0,
debug: webConfig.nodeEnv === "development",
chatWebsiteId: webConfig.crisp.chatWebsiteId,
@@ -98,7 +160,9 @@ export async function loadRootData({ request, params }: { request: Request; para
csrf,
analytics,
analyticsToken: appConfiguration.analytics.enabled && hasAnalyticsConsent ? webConfig.analytics.token : undefined,
featureFlags: appConfiguration.featureFlags.enabled ? await getCurrentEnabledFlagNames({ request, params }) : [],
webPushVapidPublicKey: webConfig.webPush.vapidPublicKey,
cspNonce,
featureFlags,
impersonatingSession,
};
@@ -110,7 +174,8 @@ export async function loadRootData({ request, params }: { request: Request; para
...userInfo,
metrics: appConfiguration.metrics,
},
new URL(request.url).pathname + new URL(request.url).search
new URL(request.url).pathname + new URL(request.url).search,
{ request }
);
}
@@ -1,4 +1,6 @@
import { useMatches } from "react-router";
import type { SeatType } from "@hivegrid/db/prisma-browser";
import type { SubscriptionBannerVM } from "@hivegrid/view-models";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { TenantSimple } from "../db/tenants.db.server";
import { TenantSubscriptionWithDetails } from "../db/tenantSubscriptions.db.server";
@@ -7,7 +9,16 @@ import { AppOrAdminData } from "./useAppOrAdminData";
export type AppLoaderData = AppOrAdminData & {
currentTenant: TenantSimple;
mySubscription: TenantSubscriptionWithDetails | null;
/**
* Root-route decision for the focused first-purchase gate. A persisted
* signup selection keeps a new tenant locked even where subscriptions are
* not globally required (for example staging demo environments).
*/
subscriptionActivationRequired?: boolean;
billingBanner: SubscriptionBannerVM;
currentRole: TenantUserType;
/** Effective seat type of the current user in this tenant (office vs field, Fundament C). */
effectiveSeatType: SeatType;
};
export function useAppData(): AppLoaderData {
@@ -6,7 +6,6 @@ import { AdminLoaderData } from "./useAdminData";
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 { TenantTypeWithDetails } from "../db/tenants/tenantTypes.db.server";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import type { ProductAccessDecision } from "@hivegrid/entitlements";
@@ -23,7 +22,6 @@ export type AppOrAdminData = {
myGroups: GroupWithDetails[];
lng?: string;
onboardingSession: OnboardingSessionWithDetails | null;
tenantTypes: TenantTypeWithDetails[];
credits?: PlanFeatureUsageDto | undefined;
productAccess?: Record<string, ProductAccessDecision>;
};
@@ -11,7 +11,7 @@ export function useDashboardData(): DashboardLoaderData {
return (useMatches().find((f) => f.id === "routes/app.$tenant/dashboard")?.data ?? {}) as DashboardLoaderData;
}
export async function loadDashboardData({ request, params }: { request: Request; params: Params }): Promise<DashboardLoaderData> {
export async function loadDashboardData({ request: _request, params }: { request: Request; params: Params }): Promise<DashboardLoaderData> {
const tenantId = await getTenantIdFromUrl(params);
const data: DashboardLoaderData = {
users: await getTenantUsersCount(tenantId),
@@ -8,5 +8,5 @@ export type MembersLoaderData = {
};
export function useMembersData(params: Params): MembersLoaderData {
return (useMatches().find((f) => f.pathname === UrlUtils.currentTenantUrl(params, "settings/members"))?.data ?? {}) as MembersLoaderData;
return (useMatches().find((f) => f.pathname === UrlUtils.currentTenantUrl(params, "settings/team"))?.data ?? {}) as MembersLoaderData;
}
@@ -7,7 +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";
import type { Anrede, SupportedLocale } from "@hivegrid/i18n";
export type AppRootData = {
metatags: MetaTagsDto;
@@ -15,6 +15,7 @@ export type AppRootData = {
currentTenant: TenantSimple | null;
theme: string;
locale: string;
enabledLocales: readonly SupportedLocale[];
anrede: Anrede;
serverUrl: string;
publicBaseUrl: string;
@@ -29,6 +30,8 @@ export type AppRootData = {
csrf?: string;
analytics?: AnalyticsInfoDto;
analyticsToken?: string;
webPushVapidPublicKey?: string;
cspNonce?: string;
featureFlags: string[];
impersonatingSession: ImpersonatingSessionDto | null;
};
@@ -0,0 +1,133 @@
// Breadcrumb helper unit test — the parent-nav-crumb rule that decides whether
// the responsible sidebar entry is prefixed to the loader-derived trail.
import { describe, expect, it } from "vitest";
import { shouldShowParentNavCrumb, type BreadcrumbTrailEntry } from "./useTitleData";
const CONTACTS_TRAIL: BreadcrumbTrailEntry[] = [
{ label: "Kontakte", href: "/app/acme/contacts" },
{ label: "Tags", href: "/app/acme/contacts/admin/tags" },
];
describe("shouldShowParentNavCrumb", () => {
it("drops a nav crumb whose target the trail already points at under a different name", () => {
// The CRM sidebar entry links to the contact list; the trail names that very
// page "Kontakte". A "CRM" crumb would be a second crumb for one route.
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/contacts",
navTitle: "CRM",
currentPathname: "/app/acme/contacts/admin/tags",
currentCrumbLabel: "Tags",
trail: CONTACTS_TRAIL,
}),
).toBe(false);
});
it("ignores a trailing slash when comparing the nav target with the trail", () => {
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/contacts/",
navTitle: "CRM",
currentPathname: "/app/acme/contacts/admin/tags",
currentCrumbLabel: "Tags",
trail: CONTACTS_TRAIL,
}),
).toBe(false);
});
it("drops a nav crumb that the trail already carries under the same label", () => {
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/other",
navTitle: "Kontakte",
currentPathname: "/app/acme/contacts/admin/tags",
currentCrumbLabel: "Tags",
trail: CONTACTS_TRAIL,
}),
).toBe(false);
});
it("drops the nav crumb when it is the current page", () => {
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/contacts",
navTitle: "CRM",
currentPathname: "/app/acme/contacts/",
currentCrumbLabel: "Kontakte",
trail: [{ label: "Kontakte", href: "/app/acme/contacts" }],
}),
).toBe(false);
});
it("keeps a nav crumb that names a section the trail does not cover", () => {
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/bookings/pages",
navTitle: "Buchungsseiten",
currentPathname: "/app/acme/bookings/pages/p1/edit",
currentCrumbLabel: "Editor",
trail: [{ label: "Editor", href: "/app/acme/bookings/pages/p1/edit" }],
}),
).toBe(true);
});
it("drops the nav crumb when the current page has its own row in the inner sub-sidenav", () => {
// /leads-statistics is a sibling entry under the Leads area. The rail
// already shows that context, so a "Leads" crumb would invent a level.
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/leads",
navTitle: "Leads",
currentPathname: "/app/acme/leads-statistics",
currentCrumbLabel: "Lead-Statistiken",
trail: [{ label: "Lead-Statistiken", href: "/app/acme/leads-statistics" }],
navContextPaths: ["/app/acme/leads", "/app/acme/leads-statistics"],
}),
).toBe(false);
});
it("keeps the nav crumb for a sub-page that has no row of its own in the rail", () => {
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/leads",
navTitle: "Leads",
currentPathname: "/app/acme/leads/l1",
currentCrumbLabel: "Karin Lehmann",
trail: [{ label: "Karin Lehmann", href: "/app/acme/leads/l1" }],
navContextPaths: ["/app/acme/leads", "/app/acme/leads-statistics"],
}),
).toBe(true);
});
it("drops the nav crumb when the trail already links to a row of the inner sub-sidenav", () => {
// Booking detail below the "Buchungen" row of the Termine rail: the trail
// names that row itself, so the area crumb would add a third level for a
// path the user walked in two steps.
expect(
shouldShowParentNavCrumb({
navPath: "/app/acme/calendar",
navTitle: "Termine",
currentPathname: "/app/acme/bookings/b1",
currentCrumbLabel: "Buchung",
trail: [
{ label: "Buchungen", href: "/app/acme/bookings" },
{ label: "Buchung", href: "/app/acme/bookings/b1" },
],
navContextPaths: ["/app/acme/calendar", "/app/acme/bookings", "/app/acme/availability"],
}),
).toBe(false);
});
it("drops the nav crumb when the entry has no path to link to", () => {
expect(
shouldShowParentNavCrumb({
navPath: "",
navTitle: "CRM",
currentPathname: "/app/acme/contacts/admin/tags",
currentCrumbLabel: "Tags",
trail: CONTACTS_TRAIL,
}),
).toBe(false);
});
});
@@ -1,5 +1,9 @@
import { useMatches } from "react-router";
function cleanTitle(raw: unknown): string {
return typeof raw === "string" ? (raw.split("|")[0]?.trim() ?? "") : "";
}
export function useTitleData(): string {
try {
const titles = useMatches()
@@ -9,8 +13,98 @@ export function useTitleData(): string {
if (!titles || titles.length === 0) {
return "";
}
return titles[titles.length - 1].split("|")[0].trim() ?? "";
return cleanTitle(titles[titles.length - 1]);
} catch {
return "";
}
}
export type BreadcrumbTrailEntry = { label: string; href: string };
function normalizeCrumbPath(path: string): string {
return path.length > 1 ? path.replace(/\/+$/, "") : path;
}
/**
* Should the responsible sidebar entry be rendered as an extra parent crumb in
* front of the loader-derived trail?
*
* No, if it is the current page, or if the trail already covers it — either by
* label or by target path. The path check matters because a nav entry may carry
* a section name ("CRM") while the trail names the page it links to
* ("Kontakte"): rendering both yields two crumbs for one route, and the section
* crumb then looks like a level that does not exist.
*
* Also no, when the current page is itself one of the entry's `contextItems` —
* i.e. it has its own row in the inner sub-sidenav. That rail already shows
* which area the page belongs to, so repeating the area as a crumb adds a level
* the user never navigated through (e.g. "Leads > Lead-Statistiken", where
* "Leads" just leads back to a sibling of the current page).
*
* And no, when the trail itself already links to one of those `contextItems`.
* A sub-page below such a row is reached through the row, not through the nav
* entry, so the trail already names the path the user took — the nav crumb only
* adds the rail's own area on top ("Termine > Buchungen > Buchung" for what is
* really "Buchungen > Buchung").
*/
export function shouldShowParentNavCrumb(args: {
navPath: string | null | undefined;
navTitle: string;
currentPathname: string;
currentCrumbLabel: string;
trail: readonly BreadcrumbTrailEntry[];
navContextPaths?: readonly (string | undefined)[];
}): boolean {
if (!args.navPath) return false;
const navPath = normalizeCrumbPath(args.navPath);
const currentPath = normalizeCrumbPath(args.currentPathname);
if (navPath === currentPath) return false;
const contextPaths = (args.navContextPaths ?? []).filter((path): path is string => Boolean(path)).map(normalizeCrumbPath);
if (contextPaths.includes(currentPath)) return false;
if (args.trail.some((crumb) => contextPaths.includes(normalizeCrumbPath(crumb.href ?? "")))) return false;
if (args.navTitle === args.currentCrumbLabel) return false;
return !args.trail.some((crumb) => crumb.label === args.navTitle || normalizeCrumbPath(crumb.href ?? "") === navPath);
}
function pushCrumb(trail: BreadcrumbTrailEntry[], entry: BreadcrumbTrailEntry): void {
if (!entry.label) return;
// Collapse consecutive duplicates (layout + index route often share a title,
// and an ancestor may repeat the parent it points at).
if (trail.length > 0 && trail[trail.length - 1].label === entry.label) {
trail[trail.length - 1] = entry;
return;
}
trail.push(entry);
}
/**
* Breadcrumb trail derived from route matches that expose a loader `title`
* (or `meta.title`). Each entry links to its match's pathname, so sub-pages
* get a clickable path back to their parent page.
*
* A match may also expose `breadcrumbAncestors: { label, href }[]` in its
* loader data — extra crumbs inserted before the match's own crumb. Sub-areas
* without their own sidebar entry (e.g. the booking-page editor under
* /bookings/pages) use this to name the list page they were reached through,
* since the flat route convention gives them no shared layout to hang a crumb on.
*/
export function useBreadcrumbTrail(): BreadcrumbTrailEntry[] {
try {
const trail: BreadcrumbTrailEntry[] = [];
for (const match of useMatches()) {
const data = match.data as any;
const ancestors = Array.isArray(data?.breadcrumbAncestors) ? (data.breadcrumbAncestors as BreadcrumbTrailEntry[]) : [];
for (const ancestor of ancestors) {
if (typeof ancestor?.label === "string" && typeof ancestor?.href === "string") {
pushCrumb(trail, { label: ancestor.label, href: ancestor.href });
}
}
const label = cleanTitle(data?.title ?? data?.meta?.title);
if (!label) continue;
pushCrumb(trail, { label, href: match.pathname });
}
return trail;
} catch {
return [];
}
}
@@ -43,6 +43,9 @@ describeIfDb("Apps-Engine RLS tenant isolation gate proof (DataConnection, AppSy
await admin.connect();
await admin.query(fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/tenant-isolation.sql"), "utf8"));
// Production credentials are intentionally not part of the rollout SQL.
// Set a disposable password only inside this throwaway integration database.
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
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}`);
@@ -0,0 +1,47 @@
// @vitest-environment node
import { readFileSync, readdirSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const repoRoot = path.resolve(process.cwd());
const rlsDirectory = path.join(repoRoot, "prisma", "rls");
function executableSql(relativePath: string): string {
return readFileSync(path.join(rlsDirectory, relativePath), "utf8").replace(/--.*$/gm, "");
}
describe("RLS rollout artifacts", () => {
it("never provisions a reusable database password from repository SQL", () => {
const violations = readdirSync(rlsDirectory)
.filter((file) => file.endsWith(".sql"))
.filter((file) => /\b(?:CREATE|ALTER)\s+(?:ROLE|USER)\b[^;]*\bPASSWORD\b/is.test(executableSql(file)));
expect(violations).toEqual([]);
});
it("uses the canonical transaction-local tenant context name in every isolation policy", () => {
const isolationFiles = readdirSync(rlsDirectory).filter((file) => file.endsWith("-isolation.sql"));
const violations = isolationFiles.filter((file) => {
const sql = executableSql(file);
return !sql.includes("app.tenant_id") || sql.includes("app.current_tenant_id");
});
expect(violations).toEqual([]);
});
it("keeps global automation templates read-only for the tenant runtime role", () => {
const sql = executableSql("automation-isolation.sql");
const selectPolicy = /CREATE POLICY "tenant_isolation_automation_template_select"[\s\S]*?;/i.exec(sql)?.[0];
const mutablePolicies = [...sql.matchAll(/CREATE POLICY "tenant_isolation_automation_template_(?:insert|update|delete)"[\s\S]*?;/gi)].map(
(match) => match[0],
);
expect(selectPolicy).toContain('"tenantId" IS NULL OR');
expect(mutablePolicies).toHaveLength(3);
for (const policy of mutablePolicies) {
expect(policy).toContain("current_setting('app.tenant_id', true)");
expect(policy).not.toContain('"tenantId" IS NULL');
}
});
});
@@ -52,6 +52,9 @@ describeIfDb("Email-inbox RLS tenant isolation gate proof (EmailIntegrationMailb
// 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);
// Production credentials are intentionally not part of the rollout SQL.
// Set a disposable password only inside this throwaway integration database.
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
// 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");
@@ -53,6 +53,9 @@ describeIfDb("File RLS tenant isolation gate proof (File, FileEntityLink)", () =
// 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);
// Production credentials are intentionally not part of the rollout SQL.
// Set a disposable password only inside this throwaway integration database.
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
// 2) File RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
// four Files tables (the deferred P5 activation artifact, applied here).
const fileRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/file-isolation.sql"), "utf8");
@@ -14,7 +14,7 @@ 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
// tenant's HR rows (including all three password-safe tables), 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
@@ -53,6 +53,9 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
// 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);
// Production credentials are intentionally not part of the rollout SQL.
// Set a disposable password only inside this throwaway integration database.
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
// 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");
@@ -74,6 +77,18 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
('rls_entryA',now(),'rls_tenantA','rls_vaultA','Entry A'),
('rls_entryB',now(),'rls_tenantB','rls_vaultB','Entry B')
ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "EmployeePasswordSafeAccess"(id,"updatedAt","tenantId","vaultId","userId","permissionLevel","grantedByUserId") VALUES
('rls_accessA',now(),'rls_tenantA','rls_vaultA','rls_userA','admin','rls_userA'),
('rls_accessB',now(),'rls_tenantB','rls_vaultB','rls_userB','admin','rls_userB')
ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "HrAnnouncement"(id,"updatedAt","tenantId","authorUserId",title,body,"audienceKind","audienceRef") VALUES
('rls_announcementA',now(),'rls_tenantA','rls_userA','Team A','Body A','team','team-A'),
('rls_announcementB',now(),'rls_tenantB','rls_userB','Team B','Body B','team','team-B')
ON CONFLICT (id) DO NOTHING`);
await admin.query(`INSERT INTO "HrSurvey"(id,"updatedAt","tenantId","authorUserId",title,"audienceKind","audienceRef") VALUES
('rls_surveyA',now(),'rls_tenantA','rls_userA','Survey A','location','location-A'),
('rls_surveyB',now(),'rls_tenantB','rls_userB','Survey B','location','location-B')
ON CONFLICT (id) DO NOTHING`);
app = new pg.Client({ connectionString: appUrlFrom(ADMIN_URL!) });
await app.connect();
@@ -112,6 +127,23 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
expect(count).toBe(0);
});
it("isolates audience-targeted announcements and surveys before object gates run", async () => {
const visible = await underTenant("rls_tenantA", async () => {
const announcements = (
await app.query(`SELECT id FROM "HrAnnouncement" ORDER BY id`)
).rows.map((row) => row.id);
const surveys = (await app.query(`SELECT id FROM "HrSurvey" ORDER BY id`)).rows.map(
(row) => row.id,
);
return { announcements, surveys };
});
expect(visible).toEqual({
announcements: ["rls_announcementA"],
surveys: ["rls_surveyA"],
});
});
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);
@@ -131,4 +163,56 @@ describeIfDb("HR RLS tenant isolation gate proof (HrEmployeeProfile, EmployeePas
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);
});
it("forces RLS on vault, entry and access rows for the restricted app role", async () => {
const { rows } = await admin.query(`
SELECT relname, relrowsecurity, relforcerowsecurity
FROM pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('EmployeePasswordSafeAccess', 'EmployeePasswordSafeEntry', 'EmployeePasswordSafeVault')
ORDER BY relname
`);
expect(rows).toHaveLength(3);
expect(rows.every((row) => row.relrowsecurity && row.relforcerowsecurity)).toBe(true);
});
it("isolates vault grants and blocks cross-tenant IDOR writes", async () => {
const visible = await underTenant("rls_tenantA", async () => {
const vaults = (await app.query(`SELECT id FROM "EmployeePasswordSafeVault" ORDER BY id`)).rows.map((row) => row.id);
const access = (await app.query(`SELECT id FROM "EmployeePasswordSafeAccess" ORDER BY id`)).rows.map((row) => row.id);
return { vaults, access };
});
expect(visible).toEqual({ vaults: ["rls_vaultA"], access: ["rls_accessA"] });
await expect(
underTenant("rls_tenantA", () =>
app.query(`INSERT INTO "EmployeePasswordSafeAccess"(id,"updatedAt","tenantId","vaultId","userId","permissionLevel","grantedByUserId")
VALUES ('rls_accessX',now(),'rls_tenantB','rls_vaultB','rls_userA','read','rls_userA')`)
)
).rejects.toThrow(/row-level security/i);
});
it("returns no vault, entry or access metadata without a bound tenant", async () => {
for (const table of ["EmployeePasswordSafeVault", "EmployeePasswordSafeEntry", "EmployeePasswordSafeAccess"]) {
const count = (await app.query(`SELECT count(*)::int AS c FROM "${table}"`)).rows[0].c;
expect(count, table).toBe(0);
}
});
it("forces RLS and returns no audience metadata without a bound tenant", async () => {
for (const table of ["HrAnnouncement", "HrSurvey"]) {
const count = (await app.query(`SELECT count(*)::int AS c FROM "${table}"`)).rows[0].c;
expect(count, table).toBe(0);
}
const { rows } = await admin.query(`
SELECT relname, relrowsecurity, relforcerowsecurity
FROM pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('HrAnnouncement', 'HrSurvey')
ORDER BY relname
`);
expect(rows).toHaveLength(2);
expect(rows.every((row) => row.relrowsecurity && row.relforcerowsecurity)).toBe(true);
});
});
@@ -53,6 +53,9 @@ describeIfDb("Task RLS tenant isolation gate proof (Task, TaskWatcher, EntityLin
// 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);
// Production credentials are intentionally not part of the rollout SQL.
// Set a disposable password only inside this throwaway integration database.
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
// 2) Task RLS block: ENABLE/FORCE + tenant_isolation policy + GRANTs on the
// three Task tables (the deferred P5 activation artifact, applied here).
const taskRlsSql = fs.readFileSync(path.join(REPO_ROOT, "prisma/rls/task-isolation.sql"), "utf8");
@@ -39,6 +39,9 @@ describeIfDb("RLS tenant isolation gate proof (TenantUser)", () => {
// 1) RLS-Mechanik + restricted Rolle + Policy aus dem committeten SQL anwenden (idempotent).
const rlsSql = fs.readFileSync(path.resolve(process.cwd(), "prisma/rls/tenant-isolation.sql"), "utf8");
await admin.query(rlsSql);
// Production credentials are intentionally not part of the rollout SQL.
// Set a disposable password only inside this throwaway integration database.
await admin.query(`ALTER ROLE ${APP_ROLE} PASSWORD '${APP_PASSWORD}'`);
await admin.query(`GRANT CONNECT ON DATABASE ${new URL(ADMIN_URL!).pathname.slice(1)} TO ${APP_ROLE}`);
// 2) Zwei Tenants + User + Memberships seeden (als Superuser -> bypasst RLS).
@@ -1,4 +1,5 @@
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
@@ -18,8 +19,10 @@ export async function withTenantRLS<T>(tenantId: string, callback: (tx: TenantRl
if (!tenantId) {
throw new Error("withTenantRLS requires a non-empty tenantId");
}
return db.$transaction(async (tx: TenantRlsClient) => {
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
return callback(tx);
});
return runWithRlsContext({ tenantId }, () =>
db.$transaction(async (tx: TenantRlsClient) => {
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
return callback(tx);
}),
);
}
@@ -1,33 +1,35 @@
import { adminGetAllLegacyTenantSummaries } from "@hivegrid/db/accounts.server";
import {
createLegacyApiKeyLog,
createLegacyApiKey,
countLegacyApiKeyLogsForKey,
deleteLegacyApiKey,
adminFindLegacyApiKeyById,
findFirstLegacyActiveApiKey,
findLegacyApiKeyByAlias,
findLegacyApiKeyById,
findLegacyApiKeyByKey,
getAllLegacyApiKeys,
findRedactedLegacyApiKeyByAlias,
findRedactedLegacyApiKeyById,
getRedactedLegacyApiKeysForTenant,
rotateLegacyApiKey,
getLegacyApiKeyLogsForKey,
getLegacyApiKeysForTenant,
type LegacyApiKeyLogWithDetails,
type LegacyRedactedApiKeyWithDetails,
type LegacyApiKeySimple,
type LegacyApiKeyWithDetails,
updateLegacyApiKey,
} from "@hivegrid/db/api-keys.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "../db.server";
import { getClientIPAddress } from "~/utils/server/IpUtils";
import { getTrustedClientIpOrNull } 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 "@hivegrid/config";
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
import { invalidateApiKeySnapshot, loadCachedApiKeySnapshot } from "../api/api-key-auth-cache.server";
export type ApiKeyWithDetails = LegacyApiKeyWithDetails;
export type RedactedApiKeyWithDetails = Omit<LegacyApiKeyWithDetails, "key">;
export type RedactedApiKeyWithDetails = LegacyRedactedApiKeyWithDetails;
export function redactApiKeyForDisplay(apiKey: LegacyApiKeyWithDetails): RedactedApiKeyWithDetails {
const redactedApiKey = { ...apiKey };
@@ -40,13 +42,11 @@ export function redactApiKeysForDisplay(apiKeys: LegacyApiKeyWithDetails[]): Red
}
export type ApiKeyLogWithDetails = LegacyApiKeyLogWithDetails;
export type ApiKeyLogSimple = { apiKeyId: string | null; status: number | null };
export type ApiKeySimple = LegacyApiKeySimple;
export async function getAllApiKeys(): Promise<RedactedApiKeyWithDetails[]> {
const apiKeys = await getAllLegacyApiKeys();
return redactApiKeysForDisplay(apiKeys);
const groups = await mapAdminTenants((tenantId) => getRedactedLegacyApiKeysForTenant(tenantId));
return groups.flat().sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
}
export async function getAllApiKeyLogs(
@@ -82,27 +82,6 @@ export async function getAllApiKeyLogs(
};
}
export async function getAllApiKeyLogsSimple(tenantId?: string): Promise<ApiKeyLogSimple[]> {
let where: any = {};
if (tenantId) {
where = {
apiKey: {
tenantId,
},
};
}
return await db.apiKeyLog.findMany({
where,
select: {
apiKeyId: true,
status: true,
},
orderBy: {
createdAt: "desc",
},
});
}
export async function getTenantApiKeyLogs(
tenantId: string,
pagination: { page: number; pageSize: number },
@@ -131,60 +110,40 @@ export async function getTenantApiKeyLogs(
}
export async function getApiKeys(tenantId: string): Promise<RedactedApiKeyWithDetails[]> {
const apiKeys = await getLegacyApiKeysForTenant(tenantId);
return redactApiKeysForDisplay(apiKeys);
return runWithRlsContext({ tenantId }, () => getRedactedLegacyApiKeysForTenant(tenantId));
}
export async function adminGetApiKeyById(id: string): Promise<RedactedApiKeyWithDetails | null> {
const apiKey = await adminFindLegacyApiKeyById(id);
return apiKey ? redactApiKeyForDisplay(apiKey) : null;
return findAdminApiKeyById(id);
}
export async function getTenantApiKeyById(id: string, tenantId: string): Promise<RedactedApiKeyWithDetails | null> {
const apiKey = await findLegacyApiKeyById({ id, tenantId });
return apiKey ? redactApiKeyForDisplay(apiKey) : null;
}
export async function adminGetApiKeyByIdWithSecret(id: string): Promise<ApiKeyWithDetails | null> {
return adminFindLegacyApiKeyById(id);
}
export async function getTenantApiKeyByIdWithSecret(id: string, tenantId: string): Promise<ApiKeyWithDetails | null> {
return findLegacyApiKeyById({ id, tenantId });
return runWithRlsContext({ tenantId }, () => findRedactedLegacyApiKeyById({ id, tenantId }));
}
export async function getApiKey(key: string): Promise<ApiKeySimple | null> {
return await cachified({
key: getApiKeyLookupCacheKey(key),
ttl: 1000 * 60 * 60,
getFreshValue: () => findLegacyApiKeyByKey(key),
});
return loadCachedApiKeySnapshot(getApiKeyLookupCacheKey(key), () => findLegacyApiKeyByKey(key));
}
export async function getApiKeyByAlias(tenantId: string, alias: string): Promise<ApiKeyWithDetails | null> {
return findLegacyApiKeyByAlias(tenantId, alias);
export async function getApiKeyByAlias(tenantId: string, alias: string): Promise<RedactedApiKeyWithDetails | null> {
return runWithRlsContext({ tenantId }, () => findRedactedLegacyApiKeyByAlias(tenantId, alias));
}
export async function getApiKeyLogs(id: string, tenantId: string): Promise<ApiKeyLogWithDetails[]> {
return getLegacyApiKeyLogsForKey({ id, tenantId });
return runWithRlsContext({ tenantId }, () => getLegacyApiKeyLogsForKey({ id, tenantId }));
}
export async function countApiKeyLogsForKey(id: string, tenantId: string): Promise<number> {
return countLegacyApiKeyLogsForKey({ id, tenantId });
return runWithRlsContext({ tenantId }, () => countLegacyApiKeyLogsForKey({ id, tenantId }));
}
export async function getFirstApiKey(tenantId: string | null) {
return findFirstLegacyActiveApiKey(tenantId);
if (!tenantId) return null;
return runWithRlsContext({ tenantId }, () => findFirstLegacyActiveApiKey(tenantId));
}
export async function createApiKey(data: {
tenantId: string;
createdByUserId: string;
alias: string;
expires: Date | null;
active: boolean;
}) {
return createLegacyApiKey(data, undefined, getApiKeyHashSecret());
export async function createApiKey(data: { tenantId: string; createdByUserId: string; alias: string; expires: Date | null; active: boolean }) {
return runWithRlsContext({ tenantId: data.tenantId }, () => createLegacyApiKey(data, undefined, getApiKeyHashSecret()));
}
export async function createApiKeyLog(
@@ -207,7 +166,7 @@ export async function createApiKeyLog(
status: data.status,
alias: data.alias,
tenantName: data.tenantName,
ip: getClientIPAddress(request.headers)?.toString() ?? "",
ip: getTrustedClientIpOrNull(request) ?? "",
method: request.method,
params: serializeApiLogSearchParams(request),
});
@@ -222,36 +181,73 @@ export async function updateApiKey(
active: boolean;
}
) {
const apiKey = await updateLegacyApiKey(id, data);
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
const apiKey = await runWithRlsContext({ tenantId: data.tenantId }, () => updateLegacyApiKey(id, data));
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(apiKey.key));
return apiKey;
}
export async function rotateApiKey(id: string, tenantId: string) {
const previousApiKey = await findLegacyApiKeyById({ id, tenantId });
const previousApiKey = await runWithRlsContext({ tenantId }, () => findLegacyApiKeyById({ id, tenantId }));
if (!previousApiKey) {
throw new Error(`API key ${id} not found`);
}
const apiKey = await rotateLegacyApiKey({ id, tenantId: previousApiKey.tenantId }, undefined, getApiKeyHashSecret());
const apiKey = await runWithRlsContext({ tenantId }, () => rotateLegacyApiKey({ id, tenantId: previousApiKey.tenantId }, undefined, getApiKeyHashSecret()));
if (previousApiKey?.key) {
clearCacheKey(getApiKeyLookupCacheKey(previousApiKey.key));
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(previousApiKey.key));
}
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(apiKey.key));
return apiKey;
}
export async function deleteApiKey(id: string, tenantId: string) {
const previousApiKey = await findLegacyApiKeyById({ id, tenantId });
const previousApiKey = await runWithRlsContext({ tenantId }, () => findLegacyApiKeyById({ id, tenantId }));
if (!previousApiKey) {
throw new Error(`API key ${id} not found`);
}
const apiKey = await deleteLegacyApiKey({ id, tenantId: previousApiKey.tenantId });
clearCacheKey(getApiKeyLookupCacheKey(apiKey.key));
const apiKey = await runWithRlsContext({ tenantId }, () => deleteLegacyApiKey({ id, tenantId: previousApiKey.tenantId }));
await invalidateApiKeySnapshot(getApiKeyLookupCacheKey(apiKey.key));
return apiKey;
}
function getApiKeyHashSecret() {
return loadRequiredWebConfig().jwtSecret;
}
async function findAdminApiKeyById(id: string): Promise<RedactedApiKeyWithDetails | null> {
const normalizedId = id.trim();
if (!normalizedId) return null;
const matches = (await mapAdminTenants((tenantId) => findRedactedLegacyApiKeyById({ id: normalizedId, tenantId }))).filter(
(item): item is RedactedApiKeyWithDetails => item !== null
);
if (matches.length > 1) {
throw new Error(`API key ${normalizedId} resolved to more than one tenant`);
}
return matches[0] ?? null;
}
async function mapAdminTenants<T>(operation: (tenantId: string) => Promise<T>): Promise<T[]> {
const context = getRlsExecutionContext();
if (!context?.userId || context.tenantId) {
throw new Error("Admin API key access requires an unscoped authenticated operator context");
}
const tenants = await adminGetAllLegacyTenantSummaries();
return mapWithConcurrency(tenants, 8, ({ id }) => runWithRlsContext({ tenantId: id }, () => operation(id)));
}
async function mapWithConcurrency<T, U>(items: readonly T[], concurrency: number, operation: (item: T) => Promise<U>): Promise<U[]> {
const results = new Array<U>(items.length);
let cursor = 0;
await Promise.all(
Array.from({ length: Math.min(concurrency, items.length) }, async () => {
while (cursor < items.length) {
const index = cursor++;
results[index] = await operation(items[index]!);
}
})
);
return results;
}
@@ -0,0 +1,101 @@
import type { AppConfiguration as AppConfigurationRow } from "@hivegrid/db/prisma-browser";
import { createTwoTierCache, type CacheSerializer, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { clearCacheKey } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("app-configuration-cache");
export const APP_CONFIGURATION_CACHE_TTL_SECONDS = 30;
const APP_CONFIGURATION_CACHE_KEY = "global";
type SerializedAppConfiguration = Omit<AppConfigurationRow, "updatedAt"> & { updatedAt: string };
const appConfigurationSerializer: CacheSerializer<AppConfigurationRow> = {
serialize(value) {
return JSON.stringify({ ...value, updatedAt: value.updatedAt.toISOString() } satisfies SerializedAppConfiguration);
},
deserialize(raw) {
const value = JSON.parse(raw) as SerializedAppConfiguration;
return { ...value, updatedAt: new Date(value.updatedAt) };
},
};
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
export function createAppConfigurationCache(store: SharedStore, options: { now?: () => number } = {}): TwoTierCache<AppConfigurationRow> {
return createTwoTierCache<AppConfigurationRow>({
store,
namespace: "app-configuration",
ttlSeconds: APP_CONFIGURATION_CACHE_TTL_SECONDS,
l1MaxEntries: 1,
l1Now: options.now,
serializer: appConfigurationSerializer,
pubsubEnabled: pubsubEnabledFromEnv(),
logger: {
warn: (obj, msg) => log.warn(obj, msg),
info: (obj, msg) => log.info(obj, msg),
error: (obj, msg) => log.error(obj, msg),
},
});
}
let cacheSingleton: TwoTierCache<AppConfigurationRow> | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
function getAppConfigurationCache(): TwoTierCache<AppConfigurationRow> {
cacheSingleton ??= createAppConfigurationCache(getSharedStore());
return cacheSingleton;
}
export async function loadCachedAppConfiguration(getFreshValue: () => Promise<AppConfigurationRow | null>): Promise<AppConfigurationRow | null> {
const cache = getAppConfigurationCache();
try {
const cached = await cache.get(APP_CONFIGURATION_CACHE_KEY);
if (cached !== null) return cached;
} catch (error) {
log.warn(
{ op: "app-configuration-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
"App configuration cache read failed; falling back to the database."
);
}
const fresh = await getFreshValue();
if (fresh !== null) {
try {
await cache.set(APP_CONFIGURATION_CACHE_KEY, fresh);
} catch (error) {
log.warn(
{ op: "app-configuration-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
"App configuration cache write failed; continuing with the database result."
);
}
}
return fresh;
}
/** Fail closed because this row controls auth policy and injected scripts. */
export async function invalidateAppConfigurationCache(): Promise<void> {
clearCacheKey("appConfiguration");
const cache = getAppConfigurationCache();
cache.deleteLocal(APP_CONFIGURATION_CACHE_KEY);
await cache.l2.invalidate(APP_CONFIGURATION_CACHE_KEY);
}
export async function subscribeAppConfigurationCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
subscribeDisposer = await getAppConfigurationCache().subscribe();
log.info({ namespace: "app-configuration" }, "App configuration cache subscriber started.");
return subscribeDisposer;
}
/** Test seam. */
export function __resetAppConfigurationCacheForTests(): void {
cacheSingleton = null;
subscribeDisposer = null;
}
@@ -28,4 +28,11 @@ describe("appConfiguration web config adoption", () => {
expect(source).toContain("simpleAnalytics: false");
expect(source).toContain("ipLookup: false");
});
test("fails safe to email verification for a fresh deployment while preserving persisted overrides", () => {
expect(source).toContain("auth: {\n // A deployment without a persisted AppConfiguration");
expect(source).toContain("requireEmailVerification: true");
expect(source).toContain("conf.auth.requireEmailVerification = appConfiguration?.authRequireEmailVerification");
expect(source).toContain("authRequireEmailVerification: conf.auth.requireEmailVerification");
});
});
@@ -3,12 +3,12 @@ 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";
import { db } from "../db.server";
import { defaultTheme } from "../theme/defaultThemes";
import { getBaseURL, getDomainName } from "../url.server";
import { PortalConfiguration, getAppPortalConfiguration } from "./appPortalConfiguration.db.server";
import { getWidgetsConfiguration, WidgetsConfiguration } from "./appWidgetsConfiguration.db.server";
import { invalidateAppConfigurationCache, loadCachedAppConfiguration } from "./app-configuration-cache.server";
export type AppConfiguration = {
app: {
@@ -19,7 +19,6 @@ export type AppConfiguration = {
company?: { name: string; address: string };
features: {
tenantHome: "/:tenant/" | "/";
tenantTypes: boolean;
tenantApiKeys?: boolean;
tenantEntityCustomization?: boolean;
crm: boolean;
@@ -126,7 +125,6 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
tenantApiKeys: true,
tenantEntityCustomization: false,
crm: false,
tenantTypes: false,
tenantWorkflows: false,
tenantEmailMarketing: false,
tenantFeedback: true,
@@ -134,7 +132,10 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
},
email: defaultEmailConfig,
auth: {
requireEmailVerification: false,
// A deployment without a persisted AppConfiguration must not silently
// skip ownership proof for a public email address. Explicitly configured
// rows still override this launch-safe default below.
requireEmailVerification: true,
requireOrganization: false,
requireName: false,
slug: { require: false, type: "username" },
@@ -202,11 +203,7 @@ export async function getAppConfiguration({ request }: { request: Request }): Pr
scripts: { head: null, body: null },
};
const appConfiguration = await cachified({
key: `appConfiguration`,
ttl: 1000 * 60 * 60 * 24, // 1 day
getFreshValue: async () => db.appConfiguration.findFirst(),
});
const appConfiguration = await loadCachedAppConfiguration(() => db.appConfiguration.findFirst());
if (!appConfiguration) {
return conf;
}
@@ -284,8 +281,8 @@ export async function getOrCreateAppConfiguration({ request }: { request: Reques
brandingFavicon: conf.branding.favicon,
},
})
.then((item) => {
clearCacheKey(`appConfiguration`);
.then(async (item) => {
await invalidateAppConfigurationCache();
return item;
});
}
@@ -308,15 +305,15 @@ export async function updateAppConfiguration(data: Prisma.AppConfigurationUpdate
.updateMany({
data,
})
.then((item) => {
clearCacheKey(`appConfiguration`);
.then(async (item) => {
await invalidateAppConfigurationCache();
return item;
});
}
export async function deleteAppConfiguration() {
return await db.appConfiguration.deleteMany({ where: {} }).then((item) => {
clearCacheKey(`appConfiguration`);
return await db.appConfiguration.deleteMany({ where: {} }).then(async (item) => {
await invalidateAppConfigurationCache();
return item;
});
}
@@ -8,12 +8,6 @@ export type PortalConfiguration = {
forTenants: boolean;
pricing: boolean;
analytics: boolean;
domains?: {
enabled: boolean;
provider: "fly";
portalAppId: string;
records?: { A: string; AAAA: string };
};
metadata: Array<JsonPropertyDto> | undefined;
pages: Array<PortalPageConfigDto>;
};
@@ -80,15 +74,6 @@ export function getAppPortalConfiguration({ t }: { t: TFunction }): PortalConfig
forTenants: true,
pricing: true,
analytics: true,
domains: {
enabled: true,
provider: "fly",
portalAppId: "app-portal",
records: {
A: "66.241.125.25",
AAAA: "2a09:8280:1::31:5dc2:0",
},
},
metadata: [],
pages: [
{
@@ -6,7 +6,7 @@ export type WidgetsConfiguration = {
metadata: Array<JsonPropertyDto> | undefined;
};
export function getWidgetsConfiguration({ t }: { t: TFunction }): WidgetsConfiguration {
export function getWidgetsConfiguration({ t: _t }: { t: TFunction }): WidgetsConfiguration {
const conf: WidgetsConfiguration = {
enabled: false,
metadata: [
@@ -0,0 +1,70 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@hivegrid/db/pretenant-security.server", () => ({
addBlacklistCapability: vi.fn(),
findBlacklistCapability: vi.fn(),
recordBlacklistAttemptCapability: vi.fn(),
}));
vi.mock("../db.server", () => ({
db: {
blacklist: {
create: vi.fn(),
findFirst: vi.fn(),
updateMany: vi.fn(),
},
},
}));
vi.mock("../logger.server", () => ({
createScopedLogger: vi.fn(() => ({ info: vi.fn() })),
}));
import { addBlacklistCapability, findBlacklistCapability, recordBlacklistAttemptCapability } from "@hivegrid/db/pretenant-security.server";
import { db } from "../db.server";
import { addBlacklistAttempt, addToBlacklist, findInBlacklist } from "./blacklist.db.server";
const blacklistItem = {
id: "blacklist_1",
createdAt: new Date("2026-01-01T00:00:00.000Z"),
type: "email",
value: "blocked@example.test",
active: true,
registerAttempts: 2,
};
const addCapabilityMock = vi.mocked(addBlacklistCapability);
const findCapabilityMock = vi.mocked(findBlacklistCapability);
const recordAttemptMock = vi.mocked(recordBlacklistAttemptCapability);
const directTableMock = vi.mocked(db.blacklist, true);
describe("blacklist db helpers", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("uses the exact-match capability instead of a direct table read", async () => {
findCapabilityMock.mockResolvedValueOnce(blacklistItem);
await expect(findInBlacklist("email", "blocked@example.test")).resolves.toEqual(blacklistItem);
expect(findCapabilityMock).toHaveBeenCalledWith("email", "blocked@example.test");
expect(directTableMock.findFirst).not.toHaveBeenCalled();
});
it("records attempts atomically through the capability", async () => {
recordAttemptMock.mockResolvedValueOnce({ ...blacklistItem, registerAttempts: 3 });
await expect(addBlacklistAttempt(blacklistItem)).resolves.toMatchObject({ registerAttempts: 3 });
expect(recordAttemptMock).toHaveBeenCalledWith(blacklistItem);
expect(directTableMock.updateMany).not.toHaveBeenCalled();
});
it("creates runtime blacklist entries through the capability", async () => {
addCapabilityMock.mockResolvedValueOnce(blacklistItem);
await expect(addToBlacklist({ type: "email", value: "blocked@example.test" })).resolves.toEqual(blacklistItem);
expect(addCapabilityMock).toHaveBeenCalledWith({ type: "email", value: "blocked@example.test" });
expect(directTableMock.create).not.toHaveBeenCalled();
});
});
@@ -1,4 +1,5 @@
import { Blacklist } from "@hivegrid/db/prisma-browser";
import { addBlacklistCapability, findBlacklistCapability, recordBlacklistAttemptCapability } from "@hivegrid/db/pretenant-security.server";
import type { 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";
@@ -30,34 +31,16 @@ export async function getBlacklist(
}
export async function findInBlacklist(type: string, value: string): Promise<Blacklist | null> {
return await db.blacklist.findFirst({
where: {
type,
value,
},
});
return await findBlacklistCapability(type, value);
}
export async function addBlacklistAttempt(item: Blacklist) {
blacklistLogger.info(
{ type: item.type, value: item.value, registerAttempts: item.registerAttempts + 1 },
`[BLACKLISTED ${item.type.toUpperCase()}]`
);
return await db.blacklist.updateMany({
where: {
type: item.type,
value: item.value,
},
data: {
registerAttempts: item.registerAttempts + 1,
},
});
blacklistLogger.info({ type: item.type, value: item.value, registerAttempts: item.registerAttempts + 1 }, `[BLACKLISTED ${item.type.toUpperCase()}]`);
return await recordBlacklistAttemptCapability(item);
}
export async function addToBlacklist(data: { type: string; value: string }) {
return await db.blacklist.create({
data,
});
return await addBlacklistCapability(data);
}
export async function deleteFromBlacklist(where: { type: string; value: string }) {
@@ -7,16 +7,19 @@ vi.mock("../db.server", () => {
log: {
groupBy: vi.fn(),
findMany: vi.fn(),
create: vi.fn(),
},
},
};
});
import { db } from "../db.server";
import { getLastUserLogsByUserIds } from "./logs.db.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { createLogLogin, getLastUserLogsByUserIds } from "./logs.db.server";
const groupBy = db.log.groupBy as unknown as ReturnType<typeof vi.fn>;
const findMany = db.log.findMany as unknown as ReturnType<typeof vi.fn>;
const create = db.log.create as unknown as ReturnType<typeof vi.fn>;
describe("getLastUserLogsByUserIds", () => {
beforeEach(() => {
@@ -55,6 +58,12 @@ describe("getLastUserLogsByUserIds", () => {
where: { userId: { in: userIds } },
_max: { createdAt: true },
});
expect(findMany).toHaveBeenCalledWith({
where: {
OR: Object.entries(newest).map(([userId, createdAt]) => ({ userId, createdAt })),
},
select: { id: true, userId: true, action: true, createdAt: true },
});
expect(result.get("u1")).toMatchObject({ id: "log-u1", userId: "u1" });
expect(result.get("u3")).toMatchObject({ id: "log-u3" });
expect(result.size).toBe(3);
@@ -70,3 +79,23 @@ describe("getLastUserLogsByUserIds", () => {
expect(result.size).toBe(0);
});
});
describe("identity-owned authentication logs", () => {
it("creates a pre-tenant login log inside the user's RLS context", async () => {
create.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user_1" });
return {};
});
await createLogLogin(new Request("https://app.example.test/login"), { id: "user_1" } as never);
expect(create).toHaveBeenCalledWith({
data: {
userId: "user_1",
url: "",
action: "Login",
details: "",
},
});
});
});
@@ -6,6 +6,7 @@ import { db } from "../db.server";
import RowFiltersHelper from "../helpers/RowFiltersHelper";
import { getUserInfo } from "../session.server";
import { UserWithoutPassword } from "./users.db.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
export type LogWithDetails = Log & {
user: UserWithoutPassword | null;
@@ -13,6 +14,8 @@ export type LogWithDetails = Log & {
tenant?: Tenant | null;
};
export type AdminUserLastActivity = Pick<Log, "id" | "userId" | "action" | "createdAt">;
const include = {
user: true,
tenant: true,
@@ -74,75 +77,87 @@ export async function getLogs(
export async function createLog(request: Request, tenantId: string | null, action: string, details: string) {
const userInfo = await getUserInfo(request);
await db.log.create({
data: {
tenantId,
userId: userInfo.userId,
url: new URL(request.url).pathname,
action,
details,
},
});
await withLogRlsContext(userInfo.userId, tenantId, () =>
db.log.create({
data: {
tenantId,
userId: userInfo.userId,
url: new URL(request.url).pathname,
action,
details,
},
}),
);
}
export async function createManualLog(userId: string, tenantId: string | null, pathname: string, action: string, details: string) {
await db.log.create({
data: {
tenantId,
userId,
url: pathname,
action,
details,
},
});
await withLogRlsContext(userId, tenantId, () =>
db.log.create({
data: {
tenantId,
userId,
url: pathname,
action,
details,
},
}),
);
}
export async function createLogLogin(request: Request, user: UserWithoutPassword) {
// eslint-disable-next-line no-console
// console.log({ clientIpAddress: getClientIPAddress(request.headers) });
await db.log.create({
data: {
userId: user.id,
url: "",
action: DefaultLogActions.Login,
details: "",
},
});
await withLogRlsContext(user.id, null, () =>
db.log.create({
data: {
userId: user.id,
url: "",
action: DefaultLogActions.Login,
details: "",
},
}),
);
}
export async function createLogLogout(request: Request, userId: string) {
await db.log.create({
data: {
userId,
url: "",
action: DefaultLogActions.Logout,
details: "",
},
});
await withLogRlsContext(userId, null, () =>
db.log.create({
data: {
userId,
url: "",
action: DefaultLogActions.Logout,
details: "",
},
}),
);
}
export async function createAdminLog(request: Request, action: string, details: string) {
const userInfo = await getUserInfo(request);
await db.log.create({
data: {
userId: userInfo.userId,
url: new URL(request.url).pathname,
action,
details,
},
});
await withLogRlsContext(userInfo.userId, null, () =>
db.log.create({
data: {
userId: userInfo.userId,
url: new URL(request.url).pathname,
action,
details,
},
}),
);
}
export async function getLastUserLog(userId: string): Promise<Log | null> {
return await db.log.findFirst({
where: {
userId,
},
orderBy: {
createdAt: "desc",
},
});
return await withLogRlsContext(userId, null, () =>
db.log.findFirst({
where: {
userId,
},
orderBy: {
createdAt: "desc",
},
}),
);
}
/**
@@ -150,7 +165,7 @@ export async function getLastUserLog(userId: string): Promise<Log | null> {
* constant number of queries (1 groupBy + 1 findMany), avoiding the N+1
* pattern of calling `getLastUserLog` per user.
*/
export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<string, Log>> {
export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<string, AdminUserLastActivity>> {
if (userIds.length === 0) {
return new Map();
}
@@ -167,8 +182,9 @@ export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<s
}
const logs = await db.log.findMany({
where: { OR: filters },
select: { id: true, userId: true, action: true, createdAt: true },
});
const byUserId = new Map<string, Log>();
const byUserId = new Map<string, AdminUserLastActivity>();
for (const log of logs) {
const existing = byUserId.get(log.userId ?? "");
if (!log.userId) continue;
@@ -178,3 +194,17 @@ export async function getLastUserLogsByUserIds(userIds: string[]): Promise<Map<s
}
return byUserId;
}
function withLogRlsContext<T>(userId: string | undefined, tenantId: string | null, operation: () => T): T {
const current = getRlsExecutionContext();
if (current?.userId || current?.tenantId) {
return operation();
}
return runWithRlsContext(
{
...(userId ? { userId } : {}),
...(tenantId ? { tenantId } : {}),
},
operation,
);
}
@@ -0,0 +1,196 @@
// @vitest-environment node
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
const { clearCacheKey, getSharedStore, logError, logInfo, logWarn } = vi.hoisted(() => ({
clearCacheKey: vi.fn(),
getSharedStore: vi.fn(),
logError: vi.fn(),
logInfo: vi.fn(),
logWarn: vi.fn(),
}));
vi.mock("~/shared-store.server", () => ({ getSharedStore }));
vi.mock("~/utils/cache.server", () => ({ clearCacheKey }));
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ error: logError, info: logInfo, warn: logWarn }),
}));
import {
__resetPermissionCacheForTests,
cachePermissionNames,
createPermissionCache,
getCachedPermissionNames,
getPermissionCache,
invalidateUserPermissionCache,
invalidateUserPermissionCacheScopes,
subscribePermissionCache,
} from "./permission-cache.server";
const disposers: Array<() => Promise<void>> = [];
const originalCacheInvalidationEnabled = process.env.CACHE_INVALIDATION_ENABLED;
beforeEach(() => {
vi.clearAllMocks();
__resetPermissionCacheForTests();
delete process.env.CACHE_INVALIDATION_ENABLED;
getSharedStore.mockReturnValue(createSharedStore({ namespace: "permission-singleton-test", adapter: new MemoryAdapter() }));
});
afterEach(async () => {
await Promise.all(disposers.splice(0).map((dispose) => dispose()));
__resetPermissionCacheForTests();
if (originalCacheInvalidationEnabled === undefined) delete process.env.CACHE_INVALIDATION_ENABLED;
else process.env.CACHE_INVALIDATION_ENABLED = originalCacheInvalidationEnabled;
});
describe("permission authorization cache", () => {
it("revokes a cached grant on a second replica through shared-store pub/sub", async () => {
const adapter = new MemoryAdapter();
const replicaA = createPermissionCache(createSharedStore({ namespace: "permission-replica-test", adapter }));
const replicaB = createPermissionCache(createSharedStore({ namespace: "permission-replica-test", adapter }));
disposers.push(await replicaA.subscribe(), await replicaB.subscribe());
const key = "user_1:tenant_1";
await replicaA.set(key, ["settings.members.delete"]);
expect(await replicaB.get(key)).toEqual(["settings.members.delete"]);
expect(replicaB.l1.get(key)).toEqual(["settings.members.delete"]);
replicaA.deleteLocal(key);
await replicaA.l2.invalidate(key);
expect(replicaB.l1.get(key)).toBeUndefined();
expect(await replicaB.get(key)).toBeNull();
});
it("memoizes the process cache and stores defensive permission snapshots", async () => {
const first = getPermissionCache();
expect(getPermissionCache()).toBe(first);
expect(getSharedStore).toHaveBeenCalledTimes(1);
const names = ["settings.members.read"];
await expect(cachePermissionNames("user_1", "tenant_1", names)).resolves.toBe(true);
names.push("settings.members.delete");
const cached = await getCachedPermissionNames("user_1", "tenant_1");
expect(cached).toEqual(["settings.members.read"]);
cached?.push("mutated.by.caller");
await expect(getCachedPermissionNames("user_1", "tenant_1")).resolves.toEqual(["settings.members.read"]);
await expect(getCachedPermissionNames("missing", null)).resolves.toBeNull();
});
it("falls back to the database when cache reads or writes fail", async () => {
const cache = getPermissionCache();
vi.spyOn(cache, "get").mockRejectedValueOnce(new TypeError("read unavailable")).mockRejectedValueOnce("unknown read failure");
vi.spyOn(cache, "set").mockRejectedValueOnce(new RangeError("write unavailable")).mockRejectedValueOnce("unknown write failure");
await expect(getCachedPermissionNames("user_1", "tenant_1")).resolves.toBeNull();
await expect(getCachedPermissionNames("user_1", null)).resolves.toBeNull();
await expect(cachePermissionNames("user_1", "tenant_1", ["projects.read"])).resolves.toBe(false);
await expect(cachePermissionNames("user_1", null, ["admin.read"])).resolves.toBe(false);
expect(logWarn).toHaveBeenCalledTimes(4);
expect(logWarn.mock.calls.map(([context]) => context)).toEqual([
expect.objectContaining({ op: "permission-cache.read", err: { name: "TypeError" } }),
expect.objectContaining({ op: "permission-cache.read", err: { name: "Error" } }),
expect.objectContaining({ op: "permission-cache.write", err: { name: "RangeError" } }),
expect.objectContaining({ op: "permission-cache.write", err: { name: "Error" } }),
]);
});
it("invalidates one scope locally, in L2, and through the legacy cache", async () => {
const cache = getPermissionCache();
await cache.set("user_1:tenant_1", ["projects.read"]);
const invalidate = vi.spyOn(cache.l2, "invalidate");
await invalidateUserPermissionCache("user_1", "tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
expect(cache.l1.get("user_1:tenant_1")).toBeUndefined();
expect(invalidate).toHaveBeenCalledWith("user_1:tenant_1");
});
it("propagates single-scope invalidation failures", async () => {
const cache = getPermissionCache();
vi.spyOn(cache.l2, "invalidate").mockRejectedValueOnce(new TypeError("publish unavailable")).mockRejectedValueOnce("publish secret");
await expect(invalidateUserPermissionCache("user_1", null)).rejects.toThrow("publish unavailable");
await expect(invalidateUserPermissionCache("user_1", null)).rejects.toBe("publish secret");
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
expect(logError.mock.calls.map(([context]) => context)).toEqual(
expect.arrayContaining([
expect.objectContaining({ op: "permission-cache.invalidate", err: { name: "TypeError" } }),
expect.objectContaining({ op: "permission-cache.invalidate", err: { name: "Error" } }),
])
);
});
it("deduplicates batch scopes, deletes L2 snapshots, and broadcasts one wildcard", async () => {
const cache = getPermissionCache();
await cache.set("user_1:tenant_1", ["projects.read"]);
await cache.set("user_2:__admin__", ["admin.read"]);
const remove = vi.spyOn(cache.l2, "delete");
const invalidate = vi.spyOn(cache.l2, "invalidate");
await invalidateUserPermissionCacheScopes([
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_2", tenantId: null },
]);
expect(remove).toHaveBeenCalledTimes(2);
expect(remove).toHaveBeenCalledWith("user_1:tenant_1");
expect(remove).toHaveBeenCalledWith("user_2:__admin__");
expect(invalidate).toHaveBeenCalledWith("*");
expect(clearCacheKey.mock.calls).toEqual(expect.arrayContaining([["userRoles:user_1:tenant_1"], ["userRoles:user_2:null"]]));
expect(cache.l1.get("user_1:tenant_1")).toBeUndefined();
expect(cache.l1.get("user_2:__admin__")).toBeUndefined();
});
it("handles empty and single-scope batches without wildcard invalidation", async () => {
const cache = getPermissionCache();
const invalidate = vi.spyOn(cache.l2, "invalidate");
await invalidateUserPermissionCacheScopes([]);
expect(invalidate).not.toHaveBeenCalled();
await invalidateUserPermissionCacheScopes([{ userId: "user_1", tenantId: null }]);
expect(invalidate).toHaveBeenCalledWith("user_1:__admin__");
expect(invalidate).not.toHaveBeenCalledWith("*");
});
it("propagates batch invalidation failures without hiding stale-peer risk", async () => {
const cache = getPermissionCache();
const remove = vi.spyOn(cache.l2, "delete").mockRejectedValueOnce("delete unavailable");
const scopes = [
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_2", tenantId: "tenant_1" },
];
await expect(invalidateUserPermissionCacheScopes(scopes)).rejects.toBe("delete unavailable");
remove.mockRejectedValueOnce(new TypeError("delete failed"));
await expect(invalidateUserPermissionCacheScopes(scopes)).rejects.toThrow("delete failed");
expect(logError.mock.calls.map(([context]) => context)).toEqual(
expect.arrayContaining([
expect.objectContaining({ op: "permission-cache.invalidate-many", err: { name: "Error" } }),
expect.objectContaining({ op: "permission-cache.invalidate-many", err: { name: "TypeError" } }),
])
);
});
it("reuses the singleton subscriber and honours explicit pubsub disable values", async () => {
process.env.CACHE_INVALIDATION_ENABLED = "false";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-false", adapter: new MemoryAdapter() }));
process.env.CACHE_INVALIDATION_ENABLED = "0";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-zero", adapter: new MemoryAdapter() }));
process.env.CACHE_INVALIDATION_ENABLED = "TRUE";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-true", adapter: new MemoryAdapter() }));
process.env.CACHE_INVALIDATION_ENABLED = "";
createPermissionCache(createSharedStore({ namespace: "permission-pubsub-default", adapter: new MemoryAdapter() }));
const cache = getPermissionCache();
const subscribe = vi.spyOn(cache, "subscribe");
const first = await subscribePermissionCache();
disposers.push(first);
await expect(subscribePermissionCache()).resolves.toBe(first);
expect(subscribe).toHaveBeenCalledTimes(1);
expect(logInfo).toHaveBeenCalledWith({ namespace: "user-permissions" }, "Permission cache subscriber started.");
});
});
@@ -0,0 +1,142 @@
import { createTwoTierCache, type SharedStore, type TwoTierCache } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { clearCacheKey } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
const log = createScopedLogger("permission-cache");
// Pub/sub is the primary revocation path. The short TTL is the safety net for
// a replica that was disconnected while an invalidation was published.
const AUTHORIZATION_CACHE_TTL_SECONDS = 30;
const ADMIN_SCOPE_KEY = "__admin__";
export type PermissionCache = TwoTierCache<string[]>;
let cacheSingleton: PermissionCache | null = null;
let subscribeDisposer: (() => Promise<void>) | null = null;
function permissionCacheKey(userId: string, tenantId: string | null): string {
return `${userId}:${tenantId ?? ADMIN_SCOPE_KEY}`;
}
function legacyPermissionCacheKey(userId: string, tenantId: string | null): string {
return `userRoles:${userId}:${tenantId}`;
}
function pubsubEnabledFromEnv(): boolean {
const raw = process.env.CACHE_INVALIDATION_ENABLED;
if (raw === undefined || raw === null || raw === "") return true;
return raw.toLowerCase() !== "false" && raw !== "0";
}
export function createPermissionCache(store: SharedStore): PermissionCache {
return createTwoTierCache<string[]>({
store,
namespace: "user-permissions",
ttlSeconds: AUTHORIZATION_CACHE_TTL_SECONDS,
pubsubEnabled: pubsubEnabledFromEnv(),
logger: {
warn: (obj, msg) => log.warn(obj, msg),
info: (obj, msg) => log.info(obj, msg),
error: (obj, msg) => log.error(obj, msg),
},
});
}
export function getPermissionCache(): PermissionCache {
if (!cacheSingleton) {
cacheSingleton = createPermissionCache(getSharedStore());
}
return cacheSingleton;
}
export async function getCachedPermissionNames(userId: string, tenantId: string | null): Promise<string[] | null> {
try {
const cached = await getPermissionCache().get(permissionCacheKey(userId, tenantId));
return cached === null ? null : [...cached];
} catch (error) {
// Cache availability must not become an authorization availability
// dependency. The caller falls back to the authoritative database.
log.warn(
{ op: "permission-cache.read", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache read failed; falling back to the database."
);
return null;
}
}
export async function cachePermissionNames(userId: string, tenantId: string | null, permissionNames: readonly string[]): Promise<boolean> {
try {
await getPermissionCache().set(permissionCacheKey(userId, tenantId), [...permissionNames]);
return true;
} catch (error) {
log.warn(
{ op: "permission-cache.write", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache write failed; continuing with the database result."
);
return false;
}
}
/**
* Invalidates one authorization scope locally, in shared L2, and on every
* subscribed web replica. Publish errors propagate: callers changing roles
* must not report success while peer replicas could still hold a stale grant.
*/
export async function invalidateUserPermissionCache(userId: string, tenantId: string | null): Promise<void> {
const key = permissionCacheKey(userId, tenantId);
clearCacheKey(legacyPermissionCacheKey(userId, tenantId));
const cache = getPermissionCache();
cache.deleteLocal(key);
try {
await cache.l2.invalidate(key);
} catch (error) {
log.error(
{ op: "permission-cache.invalidate", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache invalidation could not be published."
);
throw error;
}
}
export async function invalidateUserPermissionCacheScopes(scopes: readonly { userId: string; tenantId: string | null }[]): Promise<void> {
const unique = [...new Map(scopes.map((scope) => [permissionCacheKey(scope.userId, scope.tenantId), scope])).values()];
if (unique.length === 0) return;
if (unique.length === 1) {
const scope = unique[0]!;
await invalidateUserPermissionCache(scope.userId, scope.tenantId);
return;
}
const cache = getPermissionCache();
const keys = unique.map((scope) => permissionCacheKey(scope.userId, scope.tenantId));
unique.forEach((scope) => {
clearCacheKey(legacyPermissionCacheKey(scope.userId, scope.tenantId));
cache.deleteLocal(permissionCacheKey(scope.userId, scope.tenantId));
});
try {
// Delete every affected shared snapshot, then use one wildcard broadcast
// to flush peer L1s. This avoids one PUBLISH per user on large roles.
await Promise.all(keys.map((key) => cache.l2.delete(key)));
await cache.l2.invalidate("*");
} catch (error) {
log.error(
{ op: "permission-cache.invalidate-many", err: { name: error instanceof Error ? error.name : "Error" } },
"Permission cache invalidation batch could not be published."
);
throw error;
}
}
export async function subscribePermissionCache(): Promise<() => Promise<void>> {
if (subscribeDisposer) return subscribeDisposer;
subscribeDisposer = await getPermissionCache().subscribe();
log.info({ namespace: "user-permissions" }, "Permission cache subscriber started.");
return subscribeDisposer;
}
/** Test seam. */
export function __resetPermissionCacheForTests(): void {
cacheSingleton = null;
subscribeDisposer = null;
}
@@ -12,17 +12,24 @@ vi.mock("../../db.server", () => ({
create: vi.fn(),
update: vi.fn(),
},
rolePermission: {
findMany: vi.fn(),
},
},
}));
vi.mock("./roles.db.server", () => ({ getAllRolesNames: vi.fn(), getRoleByName: vi.fn() }));
vi.mock("./rolePermissions.db.server", () => ({ createRolePermission: vi.fn(), getAllRolePermissions: vi.fn() }));
vi.mock("./rolePermissions.db.server", () => ({
createRolePermission: vi.fn(),
getAllRolePermissions: vi.fn(),
invalidateRoleAssignmentScopes: vi.fn(),
}));
vi.mock("~/utils/cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: { getFiltersCondition: vi.fn() } }));
import { cachified, clearCacheKey } from "~/utils/cache.server";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import { db } from "../../db.server";
import { createRolePermission, getAllRolePermissions } from "./rolePermissions.db.server";
import { createRolePermission, getAllRolePermissions, invalidateRoleAssignmentScopes } from "./rolePermissions.db.server";
import { getRoleByName } from "./roles.db.server";
import {
createPermissions,
@@ -40,8 +47,9 @@ import {
describe("permission persistence", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) =>
options.getFreshValue()) as never);
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
vi.mocked(db.rolePermission.findMany).mockResolvedValue([] as never);
vi.mocked(invalidateRoleAssignmentScopes).mockResolvedValue();
});
it("lists permissions with filters, role filters, and type constraints", async () => {
@@ -75,19 +83,10 @@ describe("permission persistence", () => {
select: { id: true, name: true },
orderBy: { name: "asc" },
});
expect(db.permission.findUnique).toHaveBeenNthCalledWith(
1,
expect.objectContaining({ where: { id: "permission_1" } })
);
expect(db.permission.findUnique).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ where: { name: "admin.users.view" } })
);
expect(db.permission.findUnique).toHaveBeenNthCalledWith(1, expect.objectContaining({ where: { id: "permission_1" } }));
expect(db.permission.findUnique).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { name: "admin.users.view" } }));
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "permission:admin.users.view" }));
expect(db.permission.findMany).toHaveBeenNthCalledWith(
2,
expect.objectContaining({ where: { name: { in: ["admin.users.view", "admin.users.edit"] } } })
);
expect(db.permission.findMany).toHaveBeenNthCalledWith(2, expect.objectContaining({ where: { name: { in: ["admin.users.view", "admin.users.edit"] } } }));
});
it("calculates the next permission order with and without a type filter", async () => {
@@ -158,12 +157,15 @@ describe("permission persistence", () => {
vi.mocked(getAllRolePermissions).mockResolvedValue([]);
vi.mocked(getRoleByName).mockResolvedValue(null);
await expect(
createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["Missing"] }])
).rejects.toThrow("Role required: Missing");
await expect(createPermissions([{ name: "admin.users.view", description: "View users", type: "admin", inRoles: ["Missing"] }])).rejects.toThrow(
"Role required: Missing"
);
});
it("updates and deletes permissions while clearing the permission cache", async () => {
vi.mocked(db.rolePermission.findMany)
.mockResolvedValueOnce([{ roleId: "role_admin" }] as never)
.mockResolvedValueOnce([{ roleId: "role_member" }] as never);
vi.mocked(db.permission.update).mockResolvedValueOnce({ id: "permission_1", name: "admin.users.view" } as never);
vi.mocked(db.permission.delete).mockResolvedValueOnce({ id: "permission_1", name: "admin.users.delete" } as never);
@@ -172,5 +174,7 @@ describe("permission persistence", () => {
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.view");
expect(clearCacheKey).toHaveBeenCalledWith("permission:admin.users.delete");
expect(invalidateRoleAssignmentScopes).toHaveBeenNthCalledWith(1, ["role_admin"]);
expect(invalidateRoleAssignmentScopes).toHaveBeenNthCalledWith(2, ["role_member"]);
});
});
@@ -1,7 +1,7 @@
import { db } from "../../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 { createRolePermission, getAllRolePermissions, invalidateRoleAssignmentScopes } from "./rolePermissions.db.server";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import { FiltersDto } from "~/application/dtos/data/FiltersDto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
@@ -131,10 +131,7 @@ export async function getNextPermissionsOrder(type?: string): Promise<number> {
);
}
export async function createPermissions(
permissions: { inRoles: string[]; name: string; description: string; type: string }[],
fromOrder: number = 0
) {
export async function createPermissions(permissions: { inRoles: string[]; name: string; description: string; type: string }[], fromOrder: number = 0) {
const allRolePermissions = await getAllRolePermissions();
const allPermissions = await getAllPermissions();
const permissionByName = new Map<string, { id: string; name: string }>(allPermissions.map((permission) => [permission.name, permission]));
@@ -196,24 +193,17 @@ export async function updatePermission(
order?: number;
}
) {
return await db.permission
.update({
where: { id },
data,
})
.then((item) => {
clearCacheKey(`permission:${item.name}`);
return item;
});
const links = await db.rolePermission.findMany({ where: { permissionId: id }, select: { roleId: true } });
const item = await db.permission.update({ where: { id }, data });
clearCacheKey(`permission:${item.name}`);
await invalidateRoleAssignmentScopes(links.map((link) => link.roleId));
return item;
}
export async function deletePermission(id: string) {
return await db.permission
.delete({
where: { id },
})
.then((item) => {
clearCacheKey(`permission:${item.name}`);
return item;
});
const links = await db.rolePermission.findMany({ where: { permissionId: id }, select: { roleId: true } });
const item = await db.permission.delete({ where: { id } });
clearCacheKey(`permission:${item.name}`);
await invalidateRoleAssignmentScopes(links.map((link) => link.roleId));
return item;
}
@@ -16,18 +16,20 @@ vi.mock("../../db.server", () => ({
delete: vi.fn(),
deleteMany: vi.fn(),
findFirst: vi.fn(),
findUnique: vi.fn(),
findMany: vi.fn(),
},
userRole: {
findMany: vi.fn(),
},
$transaction: vi.fn(),
},
}));
vi.mock("~/utils/cache.server", () => ({ clearCacheKey: vi.fn() }));
vi.mock("../tenants.db.server", () => ({ adminGetAllTenants: vi.fn() }));
vi.mock("../users.db.server", () => ({ adminGetAllUsersNames: vi.fn() }));
vi.mock("./permission-cache.server", () => ({ invalidateUserPermissionCacheScopes: vi.fn() }));
import { clearCacheKey } from "~/utils/cache.server";
import { adminGetAllTenants } from "../tenants.db.server";
import { adminGetAllUsersNames } from "../users.db.server";
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
import { db } from "../../db.server";
import {
createRolePermission,
@@ -47,8 +49,9 @@ describe("role permission persistence", () => {
beforeEach(() => {
vi.clearAllMocks();
dbMock.$transaction.mockImplementation(async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock));
vi.mocked(adminGetAllTenants).mockResolvedValue([]);
vi.mocked(adminGetAllUsersNames).mockResolvedValue([]);
dbMock.userRole.findMany.mockResolvedValue([] as never);
dbMock.rolePermission.findMany.mockResolvedValue([] as never);
vi.mocked(invalidateUserPermissionCacheScopes).mockResolvedValue();
});
it("sets role permissions inside one awaited transaction before clearing caches", async () => {
@@ -74,9 +77,7 @@ describe("role permission persistence", () => {
it("reads and creates role-permission links without duplicating existing links", async () => {
dbMock.rolePermission.findMany.mockResolvedValueOnce([{ id: "rp_1" }] as never);
dbMock.rolePermission.findFirst
.mockResolvedValueOnce({ id: "rp_existing" } as never)
.mockResolvedValueOnce(null);
dbMock.rolePermission.findFirst.mockResolvedValueOnce({ id: "rp_existing" } as never).mockResolvedValueOnce(null);
dbMock.rolePermission.create.mockResolvedValueOnce({ id: "rp_created" } as never);
await expect(getAllRolePermissions()).resolves.toEqual([{ id: "rp_1" }]);
@@ -96,24 +97,24 @@ describe("role permission persistence", () => {
expect(dbMock.$transaction).not.toHaveBeenCalled();
});
it("clears app role user caches across tenants and user-role lookup caches", async () => {
it("invalidates exactly the assigned users across replicas after an app-role permission change", async () => {
findRoleByIdMock.mockResolvedValue({ id: "role_1", name: "Member", type: "app" } as never);
findPermissionsMock.mockResolvedValue([]);
vi.mocked(adminGetAllTenants).mockResolvedValue([
{ id: "tenant_1", users: [{ userId: "user_1" }, { userId: "user_2" }] },
{ id: "tenant_2", users: [{ userId: "user_3" }] },
dbMock.userRole.findMany.mockResolvedValue([
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_2", tenantId: "tenant_1" },
{ userId: "user_3", tenantId: "tenant_2" },
] as never);
vi.mocked(adminGetAllUsersNames).mockResolvedValue([{ id: "user_1" }, { id: "user_4" }] as never);
await setRolePermissions("role_1", []);
expect(dbMock.rolePermission.createMany).not.toHaveBeenCalled();
expect(clearCacheKey).toHaveBeenCalledWith("roles:app");
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_2:tenant_1");
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_3:tenant_2");
expect(clearCacheKey).toHaveBeenCalledWith("userRole:user_1:Member");
expect(clearCacheKey).toHaveBeenCalledWith("userRole:user_4:Member");
expect(invalidateUserPermissionCacheScopes).toHaveBeenCalledWith([
{ userId: "user_1", tenantId: "tenant_1" },
{ userId: "user_2", tenantId: "tenant_1" },
{ userId: "user_3", tenantId: "tenant_2" },
]);
});
it("sets permission roles inside one awaited transaction", async () => {
@@ -146,6 +147,7 @@ describe("role permission persistence", () => {
it("deletes role-permission links by composite keys or id", async () => {
dbMock.rolePermission.deleteMany.mockResolvedValueOnce({ count: 1 } as never);
dbMock.rolePermission.findUnique.mockResolvedValueOnce({ roleId: "role_2" } as never);
dbMock.rolePermission.delete.mockResolvedValueOnce({ id: "rp_1" } as never);
await expect(deleteRolePermission("role_1", "permission_1")).resolves.toEqual({ count: 1 });
@@ -153,5 +155,13 @@ describe("role permission persistence", () => {
expect(dbMock.rolePermission.deleteMany).toHaveBeenCalledWith({ where: { roleId: "role_1", permissionId: "permission_1" } });
expect(dbMock.rolePermission.delete).toHaveBeenCalledWith({ where: { id: "rp_1" } });
expect(dbMock.userRole.findMany).toHaveBeenCalledWith({
where: { roleId: { in: ["role_1"] } },
select: { userId: true, tenantId: true },
});
expect(dbMock.userRole.findMany).toHaveBeenCalledWith({
where: { roleId: { in: ["role_2"] } },
select: { userId: true, tenantId: true },
});
});
});
@@ -1,10 +1,15 @@
import { clearCacheKey } from "~/utils/cache.server";
import { createScopedLogger } from "~/utils/logger.server";
import { db } from "../../db.server";
import { adminGetAllTenants } from "../tenants.db.server";
import { adminGetAllUsersNames } from "../users.db.server";
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
const rolePermissionsLogger = createScopedLogger("db.rolePermissions");
export async function invalidateRoleAssignmentScopes(roleIds: readonly string[]): Promise<void> {
if (roleIds.length === 0) return;
const assignments = await db.userRole.findMany({
where: { roleId: { in: [...new Set(roleIds)] } },
select: { userId: true, tenantId: true },
});
await invalidateUserPermissionCacheScopes(assignments);
}
export async function getAllRolePermissions() {
return await db.rolePermission.findMany({
@@ -24,9 +29,11 @@ export async function createRolePermission(data: { roleId: string; permissionId:
if (existing) {
return existing;
}
return await db.rolePermission.create({
const created = await db.rolePermission.create({
data,
});
await invalidateRoleAssignmentScopes([data.roleId]);
return created;
}
export async function setRolePermissions(roleId: string, permissionNames: string[]) {
@@ -59,20 +66,7 @@ export async function setRolePermissions(roleId: string, permissionNames: string
});
clearCacheKey(`roles:${role.type}`);
if (role.type === "app") {
const allTenants = await adminGetAllTenants();
rolePermissionsLogger.info({ tenantCount: allTenants.length }, "Clearing user roles cache");
for (const tenant of allTenants) {
for (const user of tenant.users) {
clearCacheKey(`userRoles:${user.userId}:${tenant.id}`);
}
}
}
const allUsers = await adminGetAllUsersNames();
for (const user of allUsers) {
clearCacheKey(`userRole:${user.id}:${role.name}`);
}
await invalidateRoleAssignmentScopes([roleId]);
}
export async function setPermissionRoles(permissionId: string, roleNames: string[]) {
@@ -83,6 +77,10 @@ export async function setPermissionRoles(permissionId: string, roleNames: string
select: { id: true },
})
: [];
const previousLinks = await db.rolePermission.findMany({
where: { permissionId },
select: { roleId: true },
});
await db.$transaction(async (tx) => {
await tx.rolePermission.deleteMany({
@@ -98,16 +96,24 @@ export async function setPermissionRoles(permissionId: string, roleNames: string
});
}
});
await invalidateRoleAssignmentScopes([...previousLinks.map((link) => link.roleId), ...roles.map((role) => role.id)]);
}
export async function deleteRolePermission(roleId: string, permissionId: string) {
return await db.rolePermission.deleteMany({
const result = await db.rolePermission.deleteMany({
where: { roleId, permissionId },
});
await invalidateRoleAssignmentScopes([roleId]);
return result;
}
export async function deleteRolePermissionById(id: string) {
return await db.rolePermission.delete({
const existing = await db.rolePermission.findUnique({ where: { id }, select: { roleId: true } });
const result = await db.rolePermission.delete({
where: { id },
});
if (existing) {
await invalidateRoleAssignmentScopes([existing.roleId]);
}
return result;
}
@@ -12,14 +12,19 @@ vi.mock("../../db.server", () => ({
findUnique: vi.fn(),
update: vi.fn(),
},
userRole: {
findMany: vi.fn(),
},
},
}));
vi.mock("~/utils/cache.server", () => ({ cachified: vi.fn(), clearCacheKey: vi.fn() }));
vi.mock("./permission-cache.server", () => ({ invalidateUserPermissionCacheScopes: vi.fn() }));
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: { getFiltersCondition: vi.fn() } }));
import { cachified, clearCacheKey } from "~/utils/cache.server";
import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import { db } from "../../db.server";
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
import {
createRole,
deleteRole,
@@ -34,6 +39,7 @@ import {
getRolesByName,
getTenantAppRoleByName,
getTenantAssignableAppRole,
getTenantAssignableAppRoles,
getTenantMutableAppRole,
updateRole,
} from "./roles.db.server";
@@ -43,8 +49,9 @@ const dbMock = vi.mocked(db);
describe("role persistence", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) =>
options.getFreshValue()) as never);
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
vi.mocked(dbMock.userRole.findMany).mockResolvedValue([] as never);
vi.mocked(invalidateUserPermissionCacheScopes).mockResolvedValue();
});
it("lists global roles with permissions and supports type filtering", async () => {
@@ -94,11 +101,7 @@ describe("role persistence", () => {
vi.mocked(RowFiltersHelper.getFiltersCondition).mockReturnValue({ name: { contains: "editor" } } as never);
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([] as never);
await getAllRolesWithUsers(
"app",
{ properties: [{ name: "permissionId", value: "permission_1" }] } as never,
"tenant_1"
);
await getAllRolesWithUsers("app", { properties: [{ name: "permissionId", value: "permission_1" }] } as never, "tenant_1");
expect(dbMock.role.findMany).toHaveBeenCalledWith(
expect.objectContaining({
@@ -178,6 +181,20 @@ describe("role persistence", () => {
expect(dbMock.role.findFirst).toHaveBeenNthCalledWith(4, expect.objectContaining({ where: { name: "Support", tenantId: "tenant_1", type: "app" } }));
});
it("lists shared defaults and tenant-owned roles that the tenant may assign", async () => {
vi.mocked(dbMock.role.findMany).mockResolvedValueOnce([{ id: "role_1" }] as never);
await expect(getTenantAssignableAppRoles("tenant_1")).resolves.toEqual([{ id: "role_1" }]);
expect(dbMock.role.findMany).toHaveBeenCalledWith({
where: {
type: "app",
OR: [{ isDefault: true, tenantId: null }, { tenantId: "tenant_1" }],
},
orderBy: [{ type: "asc" }, { order: "asc" }],
});
});
it("calculates next role order for global and tenant-scoped roles", async () => {
vi.mocked(dbMock.role.aggregate)
.mockResolvedValueOnce({ _max: { order: 4 } } as never)
@@ -202,6 +219,7 @@ describe("role persistence", () => {
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);
vi.mocked(dbMock.role.delete).mockResolvedValueOnce({ id: "role_1", type: "app" } as never);
vi.mocked(dbMock.userRole.findMany).mockResolvedValueOnce([{ userId: "user_1", tenantId: "tenant_1" }] as never);
await createRole({
order: 1,
@@ -234,5 +252,6 @@ describe("role persistence", () => {
expect(clearCacheKey).toHaveBeenNthCalledWith(1, "roles:app");
expect(clearCacheKey).toHaveBeenNthCalledWith(2, "roles:admin");
expect(clearCacheKey).toHaveBeenNthCalledWith(3, "roles:app");
expect(invalidateUserPermissionCacheScopes).toHaveBeenCalledWith([{ userId: "user_1", tenantId: "tenant_1" }]);
});
});
@@ -5,6 +5,7 @@ import RowFiltersHelper from "~/utils/helpers/RowFiltersHelper";
import { UserSimple } from "../users.db.server";
import UserModelHelper from "~/utils/helpers/models/UserModelHelper";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { invalidateUserPermissionCacheScopes } from "./permission-cache.server";
export type RoleWithPermissions = Role & {
permissions: (RolePermission & { permission: Permission })[];
@@ -318,12 +319,12 @@ export async function updateRole(id: string, data: { name: string; description:
}
export async function deleteRole(id: string) {
return await db.role
.delete({
where: { id },
})
.then((item) => {
clearCacheKey(`roles:${item.type}`);
return item;
});
const assignments = await db.userRole.findMany({
where: { roleId: id },
select: { userId: true, tenantId: true },
});
const item = await db.role.delete({ where: { id } });
clearCacheKey(`roles:${item.type}`);
await invalidateUserPermissionCacheScopes(assignments);
return item;
}
@@ -0,0 +1,110 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../../db.server", () => ({
db: {
userRole: {
findMany: vi.fn(),
},
tenantUser: {
findUnique: vi.fn(),
findMany: vi.fn(),
},
},
}));
import { db } from "../../db.server";
import { getTenantSeatCounts, getUserEffectiveSeatType } from "./seatType.db.server";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
const dbMock = vi.mocked(db, true);
describe("getUserEffectiveSeatType", () => {
beforeEach(() => {
vi.clearAllMocks();
dbMock.tenantUser.findUnique.mockResolvedValue(null as never);
});
it("derives office when the user holds at least one office role", async () => {
dbMock.userRole.findMany.mockResolvedValue([{ role: { seatCategory: "field" } }, { role: { seatCategory: "office" } }] as never);
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("office");
expect(dbMock.userRole.findMany).toHaveBeenCalledWith({
where: { userId: "user-1", tenantId: "tenant-1" },
select: { role: { select: { seatCategory: true } } },
});
});
it("derives field when every role is a field role", async () => {
dbMock.userRole.findMany.mockResolvedValue([{ role: { seatCategory: "field" } }] as never);
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("field");
});
it("derives field when the user holds no roles in the tenant", async () => {
dbMock.userRole.findMany.mockResolvedValue([] as never);
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("field");
});
it("prefers the TenantUser.seatType admin override over the role-derived seat", async () => {
dbMock.userRole.findMany.mockResolvedValue([{ role: { seatCategory: "office" } }] as never);
dbMock.tenantUser.findUnique.mockResolvedValue({ seatType: "field" } as never);
await expect(getUserEffectiveSeatType("user-1", "tenant-1")).resolves.toBe("field");
expect(dbMock.tenantUser.findUnique).toHaveBeenCalledWith({
where: { tenantId_userId: { tenantId: "tenant-1", userId: "user-1" } },
select: { seatType: true },
});
});
});
describe("getTenantSeatCounts", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("queries only ACTIVE members with their tenant roles (no N+1)", async () => {
dbMock.tenantUser.findMany.mockResolvedValue([] as never);
await getTenantSeatCounts("tenant-1");
expect(dbMock.tenantUser.findMany).toHaveBeenCalledTimes(1);
expect(dbMock.tenantUser.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant-1", status: TenantUserStatus.ACTIVE },
select: {
seatType: true,
user: { select: { roles: { where: { tenantId: "tenant-1" }, select: { role: { select: { seatCategory: true } } } } } },
},
});
});
it("buckets members by effective seat type: any office role => office, else field", async () => {
dbMock.tenantUser.findMany.mockResolvedValue([
// office (has an office role)
{ seatType: null, user: { roles: [{ role: { seatCategory: "office" } }, { role: { seatCategory: "field" } }] } },
// field (only field roles)
{ seatType: null, user: { roles: [{ role: { seatCategory: "field" } }] } },
// field (no roles at all)
{ seatType: null, user: { roles: [] } },
] as never);
await expect(getTenantSeatCounts("tenant-1")).resolves.toEqual({ office: 1, field: 2 });
});
it("honours the TenantUser.seatType admin override over the role-derived seat", async () => {
dbMock.tenantUser.findMany.mockResolvedValue([
// office role but overridden to field
{ seatType: "field", user: { roles: [{ role: { seatCategory: "office" } }] } },
// field role but overridden to office
{ seatType: "office", user: { roles: [{ role: { seatCategory: "field" } }] } },
] as never);
await expect(getTenantSeatCounts("tenant-1")).resolves.toEqual({ office: 1, field: 1 });
});
it("returns zero counts when the tenant has no active members", async () => {
dbMock.tenantUser.findMany.mockResolvedValue([] as never);
await expect(getTenantSeatCounts("tenant-1")).resolves.toEqual({ office: 0, field: 0 });
});
});
@@ -0,0 +1,70 @@
import type { SeatType } from "@hivegrid/db/prisma-browser";
import { deriveSeatType } from "@hivegrid/entitlements";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { db } from "../../db.server";
/**
* Effective seat type of a single member in a tenant (Fundament C).
*
* Loads the tenant roles the user holds via the UserRole -> Role path (reading
* `Role.seatCategory`) plus the `TenantUser.seatType` admin override, then applies
* the shared `deriveSeatType` rule. Two batched queries, run in parallel — no N+1.
*/
export async function getUserEffectiveSeatType(userId: string, tenantId: string): Promise<SeatType> {
const [userRoles, tenantUser] = await Promise.all([
db.userRole.findMany({
where: { userId, tenantId },
select: { role: { select: { seatCategory: true } } },
}),
db.tenantUser.findUnique({
where: { tenantId_userId: { tenantId, userId } },
select: { seatType: true },
}),
]);
return deriveSeatType({
roleSeatCategories: userRoles.map((userRole) => userRole.role.seatCategory),
override: tenantUser?.seatType ?? null,
});
}
/** Count of the tenant's active seats per effective seat category (Fundament E). */
export interface TenantSeatCounts {
readonly office: number;
readonly field: number;
}
/**
* Counts the ACTIVE members of a tenant by their effective seat type (Fundament E).
*
* One batched `findMany` loads every active member together with the roles they
* hold in the tenant (for `Role.seatCategory`) plus the `TenantUser.seatType`
* admin override, then the shared `deriveSeatType` rule buckets each member —
* no N+1. Only `TenantUserStatus.ACTIVE` members count toward billed seats.
*/
export async function getTenantSeatCounts(tenantId: string): Promise<TenantSeatCounts> {
const members = await db.tenantUser.findMany({
where: { tenantId, status: TenantUserStatus.ACTIVE },
select: {
seatType: true,
user: {
select: {
roles: {
where: { tenantId },
select: { role: { select: { seatCategory: true } } },
},
},
},
},
});
const counts = { office: 0, field: 0 };
for (const member of members) {
const seat = deriveSeatType({
roleSeatCategories: member.user.roles.map((userRole) => userRole.role.seatCategory),
override: member.seatType,
});
counts[seat] += 1;
}
return counts;
}
@@ -1,47 +1,98 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
syncGroupChats: vi.fn(),
syncProjectChats: vi.fn(),
lockGroups: vi.fn(),
logActivity: vi.fn(),
publishAudit: vi.fn(),
withTenantRLS: vi.fn(),
}));
vi.mock("../../db.server", () => ({
db: {
group: { findFirst: vi.fn(), create: vi.fn(), deleteMany: vi.fn() },
tenantUser: { findMany: vi.fn() },
groupUser: {
create: vi.fn(),
createMany: vi.fn(),
deleteMany: vi.fn(),
},
teamChatGroupSource: { deleteMany: vi.fn() },
projektMitglied: { findMany: vi.fn(), updateMany: vi.fn() },
$transaction: vi.fn(),
},
}));
vi.mock("@hivegrid/chat/group-sync.server", () => ({
syncPermissionGroupChatsIfEnabledWithTx: (...args: unknown[]) => mocks.syncGroupChats(...args),
}));
vi.mock("@hivegrid/chat/project-sync.server", () => ({
syncProjectChannelsForPermissionGroupWithTx: (...args: unknown[]) => mocks.syncProjectChats(...args),
}));
vi.mock("@hivegrid/chat/sync-locks.server", () => ({
lockPermissionGroupsWithTx: (...args: unknown[]) => mocks.lockGroups(...args),
}));
vi.mock("@hivegrid/activity", () => ({
logActivity: (...args: unknown[]) => mocks.logActivity(...args),
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAudit(...args),
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: (...args: unknown[]) => mocks.withTenantRLS(...args),
}));
import { db } from "../../db.server";
import { createUserGroup, createUserGroups, deleteGroupUsers, deleteUserGroup, replaceGroupUsers } from "./userGroups.db.server";
import {
addGroupUsersAndSync,
createPermissionGroupWithUsers,
deletePermissionGroupAndSync,
removeGroupUsersAndSync,
replaceGroupUsers,
} from "./userGroups.db.server";
const dbMock = vi.mocked(db);
const syncContext = { actorUserId: "user_actor", requestId: "request_group_change" } as const;
describe("user group persistence", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(dbMock.$transaction).mockImplementation((async (callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock)) as never);
vi.mocked(dbMock.group.findFirst).mockResolvedValue({ id: "group_1", name: "Dispatch" } as never);
vi.mocked(dbMock.tenantUser.findMany).mockImplementation(
(async (args: { where: { userId: { in: string[] } } }) => args.where.userId.in.map((userId) => ({ userId }))) as never
);
mocks.withTenantRLS.mockImplementation((_tenantId: string, callback: (tx: typeof dbMock) => Promise<unknown>) => callback(dbMock));
mocks.syncGroupChats.mockResolvedValue({ changedChatIds: [], addedUserIds: [], removedUserIds: [] });
mocks.syncProjectChats.mockResolvedValue([]);
mocks.lockGroups.mockResolvedValue(["group_1"]);
mocks.logActivity.mockResolvedValue(undefined);
mocks.publishAudit.mockResolvedValue(undefined);
});
it("creates and deletes single group memberships", async () => {
vi.mocked(dbMock.groupUser.create).mockResolvedValueOnce({ id: "group_user_1" } as never);
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
await expect(createUserGroup("user_1", "group_1")).resolves.toEqual({ id: "group_user_1" });
await expect(deleteUserGroup("user_1", "group_1")).resolves.toEqual({ count: 1 });
await expect(deleteGroupUsers("group_1", "tenant_1")).resolves.toEqual({ count: 2 });
expect(dbMock.groupUser.create).toHaveBeenCalledWith({ data: { userId: "user_1", groupId: "group_1" } });
expect(dbMock.groupUser.deleteMany).toHaveBeenNthCalledWith(1, { where: { userId: "user_1", groupId: "group_1" } });
expect(dbMock.groupUser.deleteMany).toHaveBeenNthCalledWith(2, { where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
});
it("bulk-creates deduplicated group memberships with database duplicate protection", async () => {
it("creates a permission group and deduplicated memberships inside tenant RLS", async () => {
vi.mocked(dbMock.group.create).mockResolvedValueOnce({ id: "group_1" } as never);
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
await expect(createUserGroups("group_1", ["user_1", "user_2", "user_1"])).resolves.toEqual({ count: 2 });
await expect(
createPermissionGroupWithUsers(
"tenant_1",
{ createdByUserId: "user_actor", name: "Dispatch", description: "Dispatch team", color: 2 },
["user_1", "user_2", "user_1"]
)
).resolves.toEqual({ id: "group_1" });
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
expect(dbMock.group.create).toHaveBeenCalledWith({
data: { tenantId: "tenant_1", createdByUserId: "user_actor", name: "Dispatch", description: "Dispatch team", color: 2 },
});
expect(dbMock.groupUser.createMany).toHaveBeenCalledWith({
data: [
{ userId: "user_1", groupId: "group_1" },
@@ -51,19 +102,75 @@ describe("user group persistence", () => {
});
});
it("skips bulk membership writes when no users are selected", async () => {
await expect(createUserGroups("group_1", [])).resolves.toEqual({ count: 0 });
it("creates a permission group without a membership write when no users are selected", async () => {
vi.mocked(dbMock.group.create).mockResolvedValueOnce({ id: "group_1" } as never);
await expect(
createPermissionGroupWithUsers(
"tenant_1",
{ createdByUserId: "user_actor", name: "Empty", description: "", color: 0 },
[]
)
).resolves.toEqual({ id: "group_1" });
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
});
it("revokes group-derived chat access and archives project history before deleting the group", async () => {
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 2 } as never);
vi.mocked(dbMock.teamChatGroupSource.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
vi.mocked(dbMock.projektMitglied.findMany).mockResolvedValueOnce([
{ id: "membership_1", projektId: "project_1", rolle: "monteur" },
{ id: "membership_2", projektId: "project_1", rolle: "beobachter" },
] as never);
vi.mocked(dbMock.projektMitglied.updateMany).mockResolvedValueOnce({ count: 2 } as never);
vi.mocked(dbMock.group.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
await expect(deletePermissionGroupAndSync("group_1", "tenant_1", syncContext)).resolves.toEqual({ count: 1 });
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
expect(mocks.syncGroupChats).toHaveBeenCalledWith(
dbMock,
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
);
expect(mocks.syncProjectChats).toHaveBeenCalledWith(
dbMock,
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
);
expect(dbMock.teamChatGroupSource.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", groupId: "group_1" } });
expect(dbMock.projektMitglied.updateMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", groupId: "group_1", archivedAt: null },
data: { archivedAt: expect.any(Date) },
});
expect(mocks.logActivity).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
actorUserId: "user_actor",
activityType: "project_member_removed",
subjectId: "project_1",
summaryText: "activity.runtime.permissions.groupProjectMembershipArchived",
metadata: expect.objectContaining({ groupId: "group_1", membershipIds: ["membership_1", "membership_2"] }),
}),
{ client: dbMock }
);
expect(mocks.publishAudit).toHaveBeenCalledWith(
dbMock,
expect.objectContaining({
tenantId: "tenant_1",
actorId: "user_actor",
action: "permissions.group.deleted",
targetId: "group_1",
})
);
expect(dbMock.group.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", id: "group_1" } });
});
it("replaces group memberships inside one transaction", async () => {
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
await expect(replaceGroupUsers("group_1", "tenant_1", ["user_1", "user_2", "user_1"])).resolves.toEqual({ count: 2 });
await expect(replaceGroupUsers("group_1", "tenant_1", ["user_1", "user_2", "user_1"], syncContext)).resolves.toEqual({ count: 2 });
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
expect(dbMock.groupUser.createMany).toHaveBeenCalledWith({
data: [
@@ -72,15 +179,70 @@ describe("user group persistence", () => {
],
skipDuplicates: true,
});
expect(mocks.syncGroupChats).toHaveBeenCalledWith(
dbMock,
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
);
expect(mocks.syncProjectChats).toHaveBeenCalledWith(
dbMock,
expect.objectContaining({ tenantId: "tenant_1", groupId: "group_1", actorUserId: "user_actor" })
);
});
it("fails closed before replacing a group with a user outside the active tenant membership", async () => {
vi.mocked(dbMock.tenantUser.findMany).mockResolvedValueOnce([{ userId: "user_1" }] as never);
await expect(replaceGroupUsers("group_1", "tenant_1", ["user_1", "foreign_user"], syncContext)).rejects.toThrow(
"outside the active tenant membership"
);
expect(dbMock.groupUser.deleteMany).not.toHaveBeenCalled();
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
expect(mocks.syncGroupChats).not.toHaveBeenCalled();
expect(mocks.syncProjectChats).not.toHaveBeenCalled();
});
it("replaces group memberships with an empty set without bulk insert", async () => {
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 3 } as never);
await expect(replaceGroupUsers("group_1", "tenant_1", [])).resolves.toEqual({ count: 0 });
await expect(replaceGroupUsers("group_1", "tenant_1", [], syncContext)).resolves.toEqual({ count: 0 });
expect(dbMock.$transaction).toHaveBeenCalledTimes(1);
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant_1", expect.any(Function));
expect(dbMock.groupUser.deleteMany).toHaveBeenCalledWith({ where: { groupId: "group_1", group: { tenantId: "tenant_1" } } });
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
expect(mocks.syncGroupChats).toHaveBeenCalledOnce();
expect(mocks.syncProjectChats).toHaveBeenCalledOnce();
});
it("syncs dependent group and project chats after additive and subtractive membership changes", async () => {
vi.mocked(dbMock.groupUser.createMany).mockResolvedValueOnce({ count: 2 } as never);
vi.mocked(dbMock.groupUser.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
await expect(addGroupUsersAndSync("group_1", "tenant_1", ["user_1", "user_2"], syncContext)).resolves.toEqual({ count: 2 });
await expect(removeGroupUsersAndSync("group_1", "tenant_1", ["user_2"], syncContext)).resolves.toEqual({ count: 1 });
expect(mocks.syncGroupChats).toHaveBeenCalledTimes(2);
expect(mocks.syncProjectChats).toHaveBeenCalledTimes(2);
expect(mocks.lockGroups).toHaveBeenCalledTimes(2);
});
it("returns without opening an RLS transaction when additive or subtractive inputs are empty", async () => {
await expect(addGroupUsersAndSync("group_1", "tenant_1", [], syncContext)).resolves.toEqual({ count: 0 });
await expect(removeGroupUsersAndSync("group_1", "tenant_1", [], syncContext)).resolves.toEqual({ count: 0 });
expect(mocks.withTenantRLS).not.toHaveBeenCalled();
expect(mocks.lockGroups).not.toHaveBeenCalled();
});
it("fails closed when the permission group does not belong to the tenant", async () => {
vi.mocked(dbMock.group.findFirst).mockResolvedValueOnce(null);
await expect(addGroupUsersAndSync("foreign_group", "tenant_1", ["user_1"], syncContext)).rejects.toThrow(
"Permission group is not available in the tenant"
);
expect(dbMock.groupUser.createMany).not.toHaveBeenCalled();
expect(mocks.syncGroupChats).not.toHaveBeenCalled();
expect(mocks.syncProjectChats).not.toHaveBeenCalled();
});
});
@@ -1,64 +1,245 @@
import { db } from "~/utils/db.server";
import { logActivity } from "@hivegrid/activity";
import { syncPermissionGroupChatsIfEnabledWithTx } from "@hivegrid/chat/group-sync.server";
import { syncProjectChannelsForPermissionGroupWithTx } from "@hivegrid/chat/project-sync.server";
import { lockPermissionGroupsWithTx } from "@hivegrid/chat/sync-locks.server";
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { DbTransactionClient } from "@hivegrid/db/transactions.server";
import { withTenantScope } from "@hivegrid/foundation";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
export async function createUserGroup(userId: string, groupId: string) {
return await db.groupUser.create({
data: {
userId,
groupId,
},
export type GroupMembershipSyncContext = Readonly<{
actorUserId: string;
requestId: string;
}>;
export type PermissionGroupCreateInput = Readonly<{
createdByUserId: string;
name: string;
description: string;
color: number;
}>;
async function syncGroupMembershipDependents(
tx: DbTransactionClient,
tenantId: string,
groupId: string,
context: GroupMembershipSyncContext
): Promise<void> {
await syncPermissionGroupChatsIfEnabledWithTx(tx, {
tenantId,
groupId,
actorUserId: context.actorUserId,
requestId: `${context.requestId}:group-chats`,
});
await syncProjectChannelsForPermissionGroupWithTx(tx, {
tenantId,
groupId,
actorUserId: context.actorUserId,
requestId: `${context.requestId}:project-chats`,
});
}
export async function createUserGroups(groupId: string, userIds: string[]) {
const uniqueUserIds = [...new Set(userIds)];
if (uniqueUserIds.length === 0) {
return { count: 0 };
async function requireTenantGroup(
tx: DbTransactionClient,
tenantId: string,
groupId: string
): Promise<Readonly<{ id: string; name: string }>> {
const group = await tx.group.findFirst({
where: withTenantScope(tenantId, { id: groupId }),
select: { id: true, name: true },
});
if (!group) throw new Error("Permission group is not available in the tenant");
return group;
}
async function requireActiveTenantUsers(tx: DbTransactionClient, tenantId: string, userIds: readonly string[]): Promise<void> {
if (userIds.length === 0) return;
const expectedUserIds = [...userIds].sort();
const memberships = await tx.tenantUser.findMany({
where: withTenantScope(tenantId, {
userId: { in: expectedUserIds },
status: 2,
user: { active: true, pendingDeletion: false, pseudonymized: false },
}),
select: { userId: true },
orderBy: { userId: "asc" },
});
const activeUserIds = memberships.map((membership) => membership.userId).sort();
if (activeUserIds.length !== expectedUserIds.length || activeUserIds.some((userId, index) => userId !== expectedUserIds[index])) {
throw new Error("Permission group contains a user outside the active tenant membership");
}
return await db.groupUser.createMany({
data: uniqueUserIds.map((userId) => ({
userId,
groupId,
})),
skipDuplicates: true,
});
}
export async function deleteUserGroup(userId: string, groupId: string) {
return await db.groupUser.deleteMany({
where: {
userId,
groupId,
},
});
}
export async function replaceGroupUsers(groupId: string, tenantId: string, userIds: string[]) {
export async function createPermissionGroupWithUsers(
tenantId: string,
input: PermissionGroupCreateInput,
userIds: string[]
) {
const uniqueUserIds = [...new Set(userIds)];
return await db.$transaction(async (tx) => {
return withTenantRLS(tenantId, async (tx) => {
await requireActiveTenantUsers(tx, tenantId, uniqueUserIds);
const group = await tx.group.create({
data: withTenantScope(tenantId, input),
});
if (uniqueUserIds.length > 0) {
await tx.groupUser.createMany({
data: uniqueUserIds.map((userId) => ({ userId, groupId: group.id })),
skipDuplicates: true,
});
}
return group;
});
}
export async function addGroupUsersAndSync(
groupId: string,
tenantId: string,
userIds: string[],
context: GroupMembershipSyncContext
) {
const uniqueUserIds = [...new Set(userIds)];
if (uniqueUserIds.length === 0) return { count: 0 };
return withTenantRLS(tenantId, async (tx) => {
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
await requireTenantGroup(tx, tenantId, groupId);
await requireActiveTenantUsers(tx, tenantId, uniqueUserIds);
const result = await tx.groupUser.createMany({
data: uniqueUserIds.map((userId) => ({ userId, groupId })),
skipDuplicates: true,
});
if (result.count > 0) await syncGroupMembershipDependents(tx, tenantId, groupId, context);
return result;
});
}
export async function removeGroupUsersAndSync(
groupId: string,
tenantId: string,
userIds: string[],
context: GroupMembershipSyncContext
) {
const uniqueUserIds = [...new Set(userIds)];
if (uniqueUserIds.length === 0) return { count: 0 };
return withTenantRLS(tenantId, async (tx) => {
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
await requireTenantGroup(tx, tenantId, groupId);
const result = await tx.groupUser.deleteMany({ where: { groupId, userId: { in: uniqueUserIds } } });
if (result.count > 0) await syncGroupMembershipDependents(tx, tenantId, groupId, context);
return result;
});
}
export async function replaceGroupUsers(
groupId: string,
tenantId: string,
userIds: string[],
context: GroupMembershipSyncContext
) {
const uniqueUserIds = [...new Set(userIds)];
return withTenantRLS(tenantId, async (tx) => {
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
await requireTenantGroup(tx, tenantId, groupId);
await requireActiveTenantUsers(tx, tenantId, uniqueUserIds);
await tx.groupUser.deleteMany({
where: {
groupId,
group: { tenantId },
},
});
if (uniqueUserIds.length === 0) {
return { count: 0 };
}
return await tx.groupUser.createMany({
data: uniqueUserIds.map((userId) => ({
userId,
groupId,
})),
skipDuplicates: true,
});
const result =
uniqueUserIds.length === 0
? { count: 0 }
: await tx.groupUser.createMany({
data: uniqueUserIds.map((userId) => ({ userId, groupId })),
skipDuplicates: true,
});
await syncGroupMembershipDependents(tx, tenantId, groupId, context);
return result;
});
}
export async function deleteGroupUsers(groupId: string, tenantId: string) {
return await db.groupUser.deleteMany({
where: {
groupId,
group: { tenantId },
},
export async function deletePermissionGroupAndSync(
groupId: string,
tenantId: string,
context: GroupMembershipSyncContext
) {
return withTenantRLS(tenantId, async (tx) => {
await lockPermissionGroupsWithTx(tx, tenantId, [groupId]);
const group = await requireTenantGroup(tx, tenantId, groupId);
const projectMemberships = await tx.projektMitglied.findMany({
where: withTenantScope(tenantId, { groupId, archivedAt: null }),
select: { id: true, projektId: true, rolle: true },
orderBy: [{ projektId: "asc" }, { id: "asc" }],
});
// Empty the source first so both chat reconcilers revoke group-derived
// access while the Group row is still available to their tenant checks.
await tx.groupUser.deleteMany({ where: { groupId, group: { tenantId } } });
await syncGroupMembershipDependents(tx, tenantId, groupId, context);
// Chat source rows describe live configuration and become invalid with the
// group. Project-member rows are business history, so archive rather than
// hard-delete them and retain the bare group id as the historical source.
await tx.teamChatGroupSource.deleteMany({ where: withTenantScope(tenantId, { groupId }) });
const archivedAt = new Date();
if (projectMemberships.length > 0) {
await tx.projektMitglied.updateMany({
where: withTenantScope(tenantId, { groupId, archivedAt: null }),
data: { archivedAt },
});
for (const [projectId, memberships] of groupProjectMemberships(projectMemberships)) {
await logActivity(
{
tenantId,
actorUserId: context.actorUserId,
actorKind: "user",
activityType: "project_member_removed",
subjectType: "project",
subjectId: projectId,
summaryText: "activity.runtime.permissions.groupProjectMembershipArchived",
metadata: {
groupId,
groupName: group.name,
membershipIds: memberships.map(({ id }) => id),
roles: [...new Set(memberships.map(({ rolle }) => rolle))].sort(),
archivedAt: archivedAt.toISOString(),
reason: "permission_group_deleted",
},
},
{ client: tx }
);
}
}
await publishAuditEventViaOutbox(tx as unknown as OutboxPublisherTransaction, {
tenantId,
actorId: context.actorUserId,
actorType: "user",
action: "permissions.group.deleted",
targetType: "Group",
targetId: groupId,
requestId: context.requestId,
sourceModule: "permissions",
dataSensitivity: "internal",
metadata: {
groupName: group.name,
archivedProjectMembershipIds: projectMemberships.map(({ id }) => id),
affectedProjectIds: [...new Set(projectMemberships.map(({ projektId }) => projektId))].sort(),
},
summaryText: "Eine Berechtigungsgruppe wurde gelöscht; Projektzuordnungen bleiben archiviert erhalten.",
});
return tx.group.deleteMany({ where: withTenantScope(tenantId, { id: groupId }) });
});
}
function groupProjectMemberships<T extends Readonly<{ projektId: string }>>(rows: readonly T[]): ReadonlyMap<string, readonly T[]> {
const grouped = new Map<string, T[]>();
for (const row of rows) {
const memberships = grouped.get(row.projektId) ?? [];
memberships.push(row);
grouped.set(row.projektId, memberships);
}
return grouped;
}
@@ -0,0 +1,181 @@
// @vitest-environment node
import { createDbClient, getWriteDbClient } from "@hivegrid/db/client.server";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
addGroupUsersAndSync,
deletePermissionGroupAndSync,
removeGroupUsersAndSync,
} from "./userGroups.db.server";
const ADMIN_URL = process.env.RLS_TEST_DATABASE_URL;
const describeIfDatabase = ADMIN_URL ? describe : describe.skip;
const TENANT_A = "chat_group_sync_rls_tenant_a";
const TENANT_B = "chat_group_sync_rls_tenant_b";
const ACTOR_A = "chat_group_sync_rls_actor_a";
const MEMBER_A = "chat_group_sync_rls_member_a";
const ACTOR_B = "chat_group_sync_rls_actor_b";
const MEMBER_B = "chat_group_sync_rls_member_b";
const GROUP_A = "chat_group_sync_rls_group_a";
const GROUP_B = "chat_group_sync_rls_group_b";
const CHAT_A = "chat_group_sync_rls_chat_a";
const CHAT_B = "chat_group_sync_rls_chat_b";
const PROJECT_A = "chat_group_sync_rls_project_a";
const PROJECT_B = "chat_group_sync_rls_project_b";
describeIfDatabase("permission-group chat sync with the restricted app role", () => {
const admin = createDbClient({ connectionString: ADMIN_URL });
const app = getWriteDbClient();
beforeAll(async () => {
await cleanupFixtures(admin);
await admin.user.createMany({
data: [
{ id: ACTOR_A, email: "chat-group-sync-actor-a@example.test", firstName: "Actor", lastName: "A", active: true },
{ id: MEMBER_A, email: "chat-group-sync-member-a@example.test", firstName: "Member", lastName: "A", active: true },
{ id: ACTOR_B, email: "chat-group-sync-actor-b@example.test", firstName: "Actor", lastName: "B", active: true },
{ id: MEMBER_B, email: "chat-group-sync-member-b@example.test", firstName: "Member", lastName: "B", active: true },
],
});
await admin.tenant.createMany({
data: [
{ id: TENANT_A, slug: TENANT_A, name: "Group sync RLS tenant A", active: true },
{ id: TENANT_B, slug: TENANT_B, name: "Group sync RLS tenant B", active: true },
],
});
await admin.tenantUser.createMany({
data: [
{ id: `${TENANT_A}_actor`, tenantId: TENANT_A, userId: ACTOR_A, type: 0, joined: 1, status: 2 },
{ id: `${TENANT_A}_member`, tenantId: TENANT_A, userId: MEMBER_A, type: 0, joined: 1, status: 2 },
{ id: `${TENANT_B}_actor`, tenantId: TENANT_B, userId: ACTOR_B, type: 0, joined: 1, status: 2 },
{ id: `${TENANT_B}_member`, tenantId: TENANT_B, userId: MEMBER_B, type: 0, joined: 1, status: 2 },
],
});
await admin.group.createMany({
data: [
{ id: GROUP_A, tenantId: TENANT_A, createdByUserId: ACTOR_A, name: "Tenant A Dispatch", description: "A", color: 1 },
{ id: GROUP_B, tenantId: TENANT_B, createdByUserId: ACTOR_B, name: "Tenant B Dispatch", description: "B", color: 2 },
],
});
await admin.groupUser.create({ data: { id: `${GROUP_B}_member`, groupId: GROUP_B, userId: MEMBER_B } });
await admin.teamChat.createMany({
data: [
{ id: CHAT_A, tenantId: TENANT_A, createdByUserId: ACTOR_A, kind: "group", name: "A", isPrivate: true, eventStreamId: `${CHAT_A}_stream` },
{ id: CHAT_B, tenantId: TENANT_B, createdByUserId: ACTOR_B, kind: "group", name: "B", isPrivate: true, eventStreamId: `${CHAT_B}_stream` },
],
});
await admin.teamChatGroupSource.createMany({
data: [
{ id: `${CHAT_A}_source`, tenantId: TENANT_A, chatId: CHAT_A, groupId: GROUP_A, syncEnabled: true },
{ id: `${CHAT_B}_source`, tenantId: TENANT_B, chatId: CHAT_B, groupId: GROUP_B, syncEnabled: true },
],
});
await admin.teamChatMember.createMany({
data: [
{ id: `${CHAT_A}_actor`, tenantId: TENANT_A, chatId: CHAT_A, userId: ACTOR_A, roleInChat: "admin", notificationPref: "all_messages", isManualMember: true, manualRoleInChat: "admin" },
{ id: `${CHAT_B}_actor`, tenantId: TENANT_B, chatId: CHAT_B, userId: ACTOR_B, roleInChat: "admin", notificationPref: "all_messages", isManualMember: true, manualRoleInChat: "admin" },
{ id: `${CHAT_B}_member`, tenantId: TENANT_B, chatId: CHAT_B, userId: MEMBER_B, notificationPref: "all_messages", isManualMember: false, isGroupManaged: true },
],
});
await createProjectFixtures(admin);
});
afterAll(async () => {
await cleanupFixtures(admin);
await Promise.all([admin.$disconnect(), app.$disconnect()]);
});
it("adds, removes, and deletes only tenant-A group sources while preserving project history", async () => {
const currentRole = await app.$queryRaw<Array<{ currentUser: string }>>`SELECT current_user AS "currentUser"`;
expect(currentRole).toEqual([{ currentUser: "hivegrid_app" }]);
const rlsState = await app.$queryRaw<Array<{ tableName: string; enabled: boolean; forced: boolean }>>`
SELECT relname AS "tableName", relrowsecurity AS enabled, relforcerowsecurity AS forced
FROM pg_catalog.pg_class
WHERE relnamespace = 'public'::regnamespace
AND relname IN ('Group', 'GroupUser', 'ProjektMitglied', 'TeamChat', 'TeamChatGroupSource', 'TeamChatMember')
ORDER BY relname ASC
`;
expect(rlsState).toHaveLength(6);
expect(rlsState.every((table) => table.enabled && table.forced)).toBe(true);
await expect(app.group.findMany({ where: { id: GROUP_A }, select: { id: true } })).resolves.toEqual([]);
await addGroupUsersAndSync(GROUP_A, TENANT_A, [MEMBER_A], { actorUserId: ACTOR_A, requestId: "group-rls-add-a" });
await expect(admin.teamChatMember.findUnique({ where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } } })).resolves.toMatchObject({
isGroupManaged: true,
leftAt: null,
});
await removeGroupUsersAndSync(GROUP_A, TENANT_A, [MEMBER_A], { actorUserId: ACTOR_A, requestId: "group-rls-remove-a" });
await expect(admin.teamChatMember.findUnique({ where: { chatId_userId: { chatId: CHAT_A, userId: MEMBER_A } } })).resolves.toMatchObject({
isGroupManaged: false,
leftAt: expect.any(Date),
});
await addGroupUsersAndSync(GROUP_A, TENANT_A, [MEMBER_A], { actorUserId: ACTOR_A, requestId: "group-rls-readd-a" });
await deletePermissionGroupAndSync(GROUP_A, TENANT_A, { actorUserId: ACTOR_A, requestId: "group-rls-delete-a" });
await expect(admin.group.findUnique({ where: { id: GROUP_A } })).resolves.toBeNull();
await expect(admin.teamChatGroupSource.count({ where: { tenantId: TENANT_A, groupId: GROUP_A } })).resolves.toBe(0);
await expect(admin.projektMitglied.findUnique({ where: { id: `${PROJECT_A}_group_member` } })).resolves.toMatchObject({
groupId: GROUP_A,
archivedAt: expect.any(Date),
});
await expect(admin.activity.count({ where: { tenantId: TENANT_A, subjectType: "project", subjectId: PROJECT_A, activityType: "project_member_removed" } })).resolves.toBeGreaterThan(0);
await expect(admin.outboxEvent.count({ where: { tenantId: TENANT_A } })).resolves.toBeGreaterThan(0);
await expect(admin.group.findUnique({ where: { id: GROUP_B } })).resolves.toMatchObject({ tenantId: TENANT_B });
await expect(admin.groupUser.findUnique({ where: { group_user_membership_key: { groupId: GROUP_B, userId: MEMBER_B } } })).resolves.not.toBeNull();
await expect(admin.teamChatGroupSource.findUnique({ where: { chatId_groupId: { chatId: CHAT_B, groupId: GROUP_B } } })).resolves.toMatchObject({ tenantId: TENANT_B, syncEnabled: true });
await expect(admin.teamChatMember.findUnique({ where: { chatId_userId: { chatId: CHAT_B, userId: MEMBER_B } } })).resolves.toMatchObject({ isGroupManaged: true, leftAt: null });
await expect(admin.projektMitglied.findUnique({ where: { id: `${PROJECT_B}_group_member` } })).resolves.toMatchObject({ archivedAt: null });
});
});
async function createProjectFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
await admin.pipeline.createMany({
data: [
{ id: `${PROJECT_A}_pipeline`, tenantId: TENANT_A, createdByUserId: ACTOR_A, name: "A Pipeline", typHint: "auftrag" },
{ id: `${PROJECT_B}_pipeline`, tenantId: TENANT_B, createdByUserId: ACTOR_B, name: "B Pipeline", typHint: "auftrag" },
],
});
await admin.pipelineStage.createMany({
data: [
{ id: `${PROJECT_A}_stage`, tenantId: TENANT_A, pipelineId: `${PROJECT_A}_pipeline`, name: "A Active", stageKind: "offen" },
{ id: `${PROJECT_B}_stage`, tenantId: TENANT_B, pipelineId: `${PROJECT_B}_pipeline`, name: "B Active", stageKind: "offen" },
],
});
await admin.projekt.createMany({
data: [
{ id: PROJECT_A, tenantId: TENANT_A, createdByUserId: ACTOR_A, projektNummer: "RLS-A", projektname: "RLS A", pipelineId: `${PROJECT_A}_pipeline`, stageId: `${PROJECT_A}_stage` },
{ id: PROJECT_B, tenantId: TENANT_B, createdByUserId: ACTOR_B, projektNummer: "RLS-B", projektname: "RLS B", pipelineId: `${PROJECT_B}_pipeline`, stageId: `${PROJECT_B}_stage` },
],
});
await admin.projektMitglied.createMany({
data: [
{ id: `${PROJECT_A}_group_member`, tenantId: TENANT_A, projektId: PROJECT_A, groupId: GROUP_A, rolle: "monteur", createdByUserId: ACTOR_A },
{ id: `${PROJECT_B}_group_member`, tenantId: TENANT_B, projektId: PROJECT_B, groupId: GROUP_B, rolle: "monteur", createdByUserId: ACTOR_B },
],
});
}
async function cleanupFixtures(admin: ReturnType<typeof createDbClient>): Promise<void> {
const tenantIds = [TENANT_A, TENANT_B];
await admin.teamChatMember.updateMany({ where: { tenantId: { in: tenantIds } }, data: { lastReadMessageId: null, lastReadAt: null } });
await admin.teamChatEvent.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.teamChatMessage.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.teamChatMember.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.teamChatGroupSource.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.teamChat.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.activity.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.outboxEvent.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.projektMitglied.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.projekt.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.pipelineStage.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.pipeline.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.groupUser.deleteMany({ where: { groupId: { in: [GROUP_A, GROUP_B] } } });
await admin.group.deleteMany({ where: { id: { in: [GROUP_A, GROUP_B] } } });
await admin.tenantUser.deleteMany({ where: { tenantId: { in: tenantIds } } });
await admin.tenant.deleteMany({ where: { id: { in: tenantIds } } });
await admin.user.deleteMany({ where: { id: { in: [ACTOR_A, MEMBER_A, ACTOR_B, MEMBER_B] } } });
}
@@ -2,6 +2,13 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
const permissionCacheMock = vi.hoisted(() => ({
get: vi.fn(),
set: vi.fn(),
invalidate: vi.fn(),
invalidateScopes: vi.fn(),
}));
vi.mock("../../db.server", () => ({
db: {
permission: {
@@ -22,11 +29,25 @@ vi.mock("../../db.server", () => ({
},
}));
vi.mock("~/utils/cache.server", () => ({
cachified: vi.fn((options: { getFreshValue: () => unknown }) => options.getFreshValue()),
clearCacheKey: vi.fn(),
}));
vi.mock("./permission-cache.server", async () => {
const { clearCacheKey } = await import("~/utils/cache.server");
permissionCacheMock.invalidate.mockImplementation(async (userId: string, tenantId: string | null) => {
clearCacheKey(`userRoles:${userId}:${tenantId}`);
});
permissionCacheMock.invalidateScopes.mockImplementation(async (scopes: Array<{ userId: string; tenantId: string | null }>) => {
for (const scope of scopes) await permissionCacheMock.invalidate(scope.userId, scope.tenantId);
});
return {
getCachedPermissionNames: permissionCacheMock.get,
cachePermissionNames: permissionCacheMock.set,
invalidateUserPermissionCache: permissionCacheMock.invalidate,
invalidateUserPermissionCacheScopes: permissionCacheMock.invalidateScopes,
};
});
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { clearCacheKey } from "~/utils/cache.server";
import { db } from "../../db.server";
import {
countUserPermission,
@@ -44,6 +65,7 @@ import {
getUserRoleInTenant,
getUserRoles,
getUsersRolesInTenant,
reconcileAdminUserRoleByName,
userHasPermission,
} from "./userRoles.db.server";
@@ -52,7 +74,8 @@ const dbMock = vi.mocked(db);
describe("user role persistence", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(cachified).mockImplementation((async (options: { getFreshValue: () => unknown }) => options.getFreshValue()) as never);
permissionCacheMock.get.mockResolvedValue(null);
permissionCacheMock.set.mockResolvedValue(false);
});
it("queries user-role relationships with tenant and admin scope", async () => {
@@ -71,7 +94,7 @@ describe("user role persistence", () => {
where: { userId: "user_1", role: { name: "Admin" }, tenantId: "tenant_1" },
});
expect(dbMock.userRole.findFirst).toHaveBeenNthCalledWith(3, {
where: { userId: "user_1", role: { name: "SuperAdmin" }, tenantId: null },
where: { userId: "user_1", role: { name: "SuperAdmin", type: "admin" }, tenantId: null },
});
expect(dbMock.userRole.findMany).toHaveBeenCalledWith(
expect.objectContaining({
@@ -99,12 +122,8 @@ describe("user role persistence", () => {
await expect(getPermissionsByUser("user_1", "tenant_1")).resolves.toEqual(["members.read", "settings.update"]);
expect(cachified).toHaveBeenCalledWith(
expect.objectContaining({
key: "userRoles:user_1:tenant_1",
ttl: 1000 * 60 * 60 * 24,
})
);
expect(permissionCacheMock.get).toHaveBeenCalledWith("user_1", "tenant_1");
expect(permissionCacheMock.set).toHaveBeenCalledWith("user_1", "tenant_1", ["members.read", "settings.update"]);
});
it("checks permission membership through the cached user-role expansion", async () => {
@@ -129,10 +148,29 @@ describe("user role persistence", () => {
await expect(userHasPermission("user_1", "tenant_1", "members.read")).resolves.toBe(true);
await expect(userHasPermission("user_1", "tenant_1", "settings.update")).resolves.toBe(false);
expect(cachified).toHaveBeenCalledWith(expect.objectContaining({ key: "userRoles:user_1:tenant_1" }));
expect(permissionCacheMock.get).toHaveBeenCalledWith("user_1", "tenant_1");
expect(dbMock.permission.count).not.toHaveBeenCalled();
});
it("does not repopulate a stale grant when revocation races a cache miss", async () => {
permissionCacheMock.set.mockResolvedValue(true);
vi.mocked(dbMock.userRole.findMany)
.mockResolvedValueOnce([
{
role: {
name: "Admin",
permissions: [{ permission: { name: "members.delete" } }],
},
},
] as never)
.mockResolvedValueOnce([] as never);
await expect(getPermissionsByUser("user_1", "tenant_1")).resolves.toEqual([]);
expect(permissionCacheMock.invalidate).toHaveBeenCalledWith("user_1", "tenant_1");
expect(permissionCacheMock.set).toHaveBeenLastCalledWith("user_1", "tenant_1", []);
});
it("returns the first matching permission name or null", async () => {
vi.mocked(dbMock.userRole.findMany)
.mockResolvedValueOnce([
@@ -273,7 +311,9 @@ describe("user role persistence", () => {
});
it("returns the concurrently-created user role when the unique assignment index wins the race", async () => {
vi.mocked(dbMock.userRole.findFirst).mockResolvedValueOnce(null).mockResolvedValueOnce({ id: "ur_concurrent" } as never);
vi.mocked(dbMock.userRole.findFirst)
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "ur_concurrent" } as never);
vi.mocked(dbMock.userRole.create).mockRejectedValueOnce(Object.assign(new Error("Unique constraint failed"), { code: "P2002" }) as never);
await expect(createUserRole("user_1", "role_admin", null)).resolves.toEqual({ id: "ur_concurrent" });
@@ -301,22 +341,22 @@ 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 () => {
it("fails closed when a required admin role is not configured", async () => {
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce(null);
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).rejects.toThrow("Required admin role is not configured");
expect(dbMock.role.findFirst).toHaveBeenCalledWith({
where: { name: "SuperAdmin", type: "admin" },
select: { id: true },
});
expect(dbMock.userRole.create).not.toHaveBeenCalled();
expect(clearCacheKey).not.toHaveBeenCalled();
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
});
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.findFirst).mockResolvedValue(null);
vi.mocked(dbMock.userRole.create).mockResolvedValueOnce({ id: "ur_admin" } as never);
await expect(ensureAdminUserRoleByName("user_1", "SuperAdmin")).resolves.toBeUndefined();
@@ -327,6 +367,27 @@ describe("user role persistence", () => {
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
});
it("revokes SuperAdmin on an SSO staff downgrade and invalidates the role cache", async () => {
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce({ id: "role_super_admin" } as never);
vi.mocked(dbMock.userRole.deleteMany).mockResolvedValueOnce({ count: 1 } as never);
await expect(reconcileAdminUserRoleByName("user_1", "SuperAdmin", false)).resolves.toBe("revoked");
expect(dbMock.userRole.deleteMany).toHaveBeenCalledWith({
where: { userId: "user_1", roleId: "role_super_admin", tenantId: null },
});
expect(clearCacheKey).toHaveBeenCalledWith("userRoles:user_1:null");
});
it("keeps staff reconciliation safe when the SuperAdmin role is not configured", async () => {
vi.mocked(dbMock.role.findFirst).mockResolvedValueOnce(null);
await expect(reconcileAdminUserRoleByName("user_1", "SuperAdmin", false)).resolves.toBe("unchanged");
expect(dbMock.userRole.deleteMany).not.toHaveBeenCalled();
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,7 +1,7 @@
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";
import { cachePermissionNames, getCachedPermissionNames, invalidateUserPermissionCache, invalidateUserPermissionCacheScopes } from "./permission-cache.server";
export type UserRoleWithPermission = UserRole & {
role: Role & { permissions: (RolePermission & { permission: Permission })[] };
@@ -21,8 +21,8 @@ function getUserRoleAssignmentKey(assignment: UserRoleAssignment): string {
return `${assignment.userId}:${assignment.roleId}:${normalizeTenantId(assignment.tenantId)}`;
}
function clearUserRoleCache(userId: string, tenantId: string | null): void {
clearCacheKey(`userRoles:${userId}:${tenantId}`);
async function clearUserRoleCache(userId: string, tenantId: string | null): Promise<void> {
await invalidateUserPermissionCache(userId, tenantId);
}
function isUniqueConstraintError(error: unknown): boolean {
@@ -57,6 +57,7 @@ export async function getUserRoleInAdmin(userId: string, roleName: string) {
userId,
role: {
name: roleName,
type: "admin",
},
tenantId: null,
},
@@ -89,33 +90,42 @@ export async function getUserRoles(userId: string, tenantId?: string | null): Pr
}
export async function getPermissionsByUser(userId: string, tenantId: string | null): Promise<string[]> {
const userRoles = await cachified({
key: `userRoles:${userId}:${tenantId}`,
ttl: 1000 * 60 * 60 * 24,
getFreshValue: () =>
db.userRole.findMany({
where: { userId, tenantId },
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
}),
});
const roles: string[] = [];
const names: string[] = [];
userRoles.forEach((userRoles) => {
if (!roles.includes(userRoles.role.name)) {
roles.push(userRoles.role.name);
}
userRoles.role.permissions.forEach((permission) => {
if (!names.includes(permission.permission.name)) {
names.push(permission.permission.name);
}
const cached = await getCachedPermissionNames(userId, tenantId);
if (cached !== null) {
return cached;
}
const readPermissionNames = async (): Promise<string[]> => {
const userRoles = await db.userRole.findMany({
where: { userId, tenantId },
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
});
});
// console.log({
// userId,
// tenantId,
// roles,
// permissions: names,
// });
const names: string[] = [];
userRoles.forEach((userRole) => {
userRole.role.permissions.forEach((permission) => {
if (!names.includes(permission.permission.name)) {
names.push(permission.permission.name);
}
});
});
return names;
};
const names = await readPermissionNames();
const cachedSuccessfully = await cachePermissionNames(userId, tenantId, names);
if (!cachedSuccessfully) {
return names;
}
// Close the cache-aside race: a revocation can commit and publish between
// the database read and cache write. Re-read after populating; a later
// revocation necessarily publishes after our write and purges it normally.
const confirmedNames = await readPermissionNames();
if (confirmedNames.length !== names.length || confirmedNames.some((name) => !names.includes(name))) {
await invalidateUserPermissionCache(userId, tenantId);
await cachePermissionNames(userId, tenantId, confirmedNames);
return confirmedNames;
}
return names;
}
@@ -235,7 +245,7 @@ export async function ensureTenantUserAppRoles({
missingRoles.map((role) => ({ id: role.id, tenantId }))
);
} else {
clearCacheKey(`userRoles:${userId}:${tenantId}`);
await clearUserRoleCache(userId, tenantId);
}
return { created: missingRoles.length, roleCount: roles.length };
@@ -254,7 +264,7 @@ export async function createUserRole(userId: string, roleId: string, tenantId: s
tenantId,
},
});
clearCacheKey(`userRoles:${userId}:${tenantId}`);
await clearUserRoleCache(userId, tenantId);
return item;
} catch (error) {
if (!isUniqueConstraintError(error)) {
@@ -272,18 +282,44 @@ export async function createUserRole(userId: string, roleId: string, tenantId: s
* Grants an admin-scoped RBAC role (e.g. "SuperAdmin") to a user by role name,
* idempotently. Used by the Admin-SSO callback to wire the JIT-provisioned
* `super_admin` identity to its concrete permission set. `createUserRole`
* invalidates the `userRoles:<userId>:null` cache, so the granted permissions
* are visible on the very next request — independent of the cache TTL.
* publishes through the shared permission cache, so every replica observes
* the grant or revocation on the next request.
*/
export async function ensureAdminUserRoleByName(userId: string, roleName: string): Promise<void> {
await reconcileAdminUserRoleByName(userId, roleName, true);
}
export type AdminRoleReconciliationResult = "granted" | "revoked" | "unchanged";
export async function reconcileAdminUserRoleByName(userId: string, roleName: string, shouldHaveRole: boolean): Promise<AdminRoleReconciliationResult> {
const role = await db.role.findFirst({
where: { name: roleName, type: "admin" },
select: { id: true },
});
if (!role) {
return;
await clearUserRoleCache(userId, null);
if (shouldHaveRole) {
throw new Error(`Required admin role is not configured: ${roleName}`);
}
return "unchanged";
}
await createUserRole(userId, role.id, null);
if (shouldHaveRole) {
const existing = await getUserRole(userId, role.id, null);
if (existing) {
await clearUserRoleCache(userId, null);
return "unchanged";
}
await createUserRole(userId, role.id, null);
await clearUserRoleCache(userId, null);
return "granted";
}
const revoked = await db.userRole.deleteMany({
where: { userId, roleId: role.id, tenantId: null },
});
await clearUserRoleCache(userId, null);
return revoked.count > 0 ? "revoked" : "unchanged";
}
export async function createUserRoles(userId: string, roles: { id: string; tenantId: string | null }[]) {
@@ -336,29 +372,28 @@ export async function createUserRoleAssignments(assignments: UserRoleAssignment[
})
: { count: 0 };
cacheScopes.forEach((scope) => {
clearUserRoleCache(scope.userId, scope.tenantId);
});
await invalidateUserPermissionCacheScopes(cacheScopes.map((scope) => ({ userId: scope.userId, tenantId: scope.tenantId })));
return result;
}
export async function deleteUserRole(userId: string, roleId: string, tenantId: string | null = null) {
return await db.userRole
.deleteMany({
where: {
userId,
roleId,
tenantId,
},
})
.then((item) => {
clearCacheKey(`userRoles:${userId}:${tenantId}`);
return item;
});
const item = await db.userRole.deleteMany({
where: {
userId,
roleId,
tenantId,
},
});
await clearUserRoleCache(userId, tenantId);
return item;
}
export async function deleteAllUserRoles(userId: string, type: string) {
return await db.userRole.deleteMany({
const assignments = await db.userRole.findMany({
where: { userId, role: { type } },
select: { tenantId: true },
});
const result = await db.userRole.deleteMany({
where: {
userId,
role: {
@@ -366,4 +401,6 @@ export async function deleteAllUserRoles(userId: string, type: string) {
},
},
});
await invalidateUserPermissionCacheScopes(assignments.map((assignment) => ({ userId, tenantId: assignment.tenantId })));
return result;
}
@@ -1,40 +1,174 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("../db.server", () => ({
db: {
registration: {
create: vi.fn(),
update: vi.fn(),
findFirst: vi.fn(),
findUnique: vi.fn(),
},
},
vi.mock("@hivegrid/db/pretenant-security.server", () => ({
createRegistrationCapability: vi.fn(),
findRegistrationBillingPreferenceCapability: vi.fn(),
findRegistrationByTokenCapability: vi.fn(),
findRegistrationSummaryByEmail: vi.fn(),
rotateRegistrationVerificationCapability: vi.fn(),
updateRegistrationCapability: vi.fn(),
}));
import { db } from "../db.server";
import { createRegistration, getRegistrationByEmail, getRegistrationByToken, updateRegistration } from "./registration.db.server";
import {
createRegistrationCapability,
findRegistrationBillingPreferenceCapability,
findRegistrationByTokenCapability,
findRegistrationSummaryByEmail,
rotateRegistrationVerificationCapability,
updateRegistrationCapability,
} from "@hivegrid/db/pretenant-security.server";
import {
createRegistration,
getRegistrationBillingPreference,
getRegistrationByEmail,
getRegistrationByToken,
getRegistrationVerificationStateByToken,
getRegistrationVerificationViewByToken,
REGISTRATION_VERIFICATION_TTL_MS,
rotateRegistrationVerification,
updateRegistration,
} from "./registration.db.server";
const registrationMock = vi.mocked(db.registration, true);
const createCapabilityMock = vi.mocked(createRegistrationCapability);
const findBillingPreferenceMock = vi.mocked(findRegistrationBillingPreferenceCapability);
const findByEmailMock = vi.mocked(findRegistrationSummaryByEmail);
const findByTokenMock = vi.mocked(findRegistrationByTokenCapability);
const updateCapabilityMock = vi.mocked(updateRegistrationCapability);
const rotateCapabilityMock = vi.mocked(rotateRegistrationVerificationCapability);
describe("registration db helpers", () => {
const createdAt = new Date("2026-07-15T08:00:00.000Z");
const verificationToken = "0123456789abcdef0123456789abcdef01234567";
beforeEach(() => {
vi.clearAllMocks();
});
it("looks up pending registrations by email and token", async () => {
registrationMock.findFirst.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof getRegistrationByEmail>>);
registrationMock.findUnique.mockResolvedValueOnce({ id: "registration_2" } as Awaited<ReturnType<typeof getRegistrationByToken>>);
it("uses narrow pre-tenant capabilities for email and token lookups", async () => {
findByEmailMock.mockResolvedValueOnce({ id: "registration_1", createdTenantId: null });
findByTokenMock.mockResolvedValueOnce({ id: "registration_2", createdAt } as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
await expect(getRegistrationByEmail("ada@example.test")).resolves.toMatchObject({ id: "registration_1" });
await expect(getRegistrationByToken("token_1")).resolves.toMatchObject({ id: "registration_2" });
await expect(getRegistrationByEmail("ada@example.test")).resolves.toEqual({
id: "registration_1",
createdTenantId: null,
});
await expect(getRegistrationByToken(verificationToken, new Date(createdAt.getTime() + 1))).resolves.toMatchObject({ id: "registration_2" });
expect(registrationMock.findFirst).toHaveBeenCalledWith({ where: { email: "ada@example.test" } });
expect(registrationMock.findUnique).toHaveBeenCalledWith({ where: { token: "token_1" } });
expect(findByEmailMock).toHaveBeenCalledWith("ada@example.test");
expect(findByTokenMock).toHaveBeenCalledWith(verificationToken);
});
it("persists lead conversion context on new registrations", async () => {
registrationMock.create.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
it("delegates the consumed registration preference to the tenant-member capability", async () => {
findBillingPreferenceMock.mockResolvedValueOnce({
selectedSubscriptionPriceId: "price_swarm",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
});
await expect(getRegistrationBillingPreference("tenant_1", "user_1")).resolves.toEqual({
selectedSubscriptionPriceId: "price_swarm",
selectedOfficeSeatQuantity: 5,
selectedFieldSeatQuantity: 15,
});
expect(findBillingPreferenceMock).toHaveBeenCalledWith("tenant_1", "user_1");
});
it("projects only verification-page fields from the token capability", async () => {
findByTokenMock.mockResolvedValueOnce({
email: "ada@example.test",
createdTenantId: null,
firstName: "Ada",
id: "registration_1",
createdAt,
} as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
await expect(getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + 1))).resolves.toEqual({
status: "pending",
email: "ada@example.test",
creationRequestKey: expect.stringMatching(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),
});
expect(findByTokenMock).toHaveBeenCalledWith(verificationToken);
});
it("keeps the projected bootstrap key stable when a resend rotates the token", async () => {
const rotatedToken = "f".repeat(40);
findByTokenMock.mockResolvedValue({
email: "ada@example.test",
createdTenantId: null,
firstName: "Ada",
id: "registration_1",
createdAt,
} as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
const beforeResend = await getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + 1));
const afterResend = await getRegistrationVerificationViewByToken(rotatedToken, new Date(createdAt.getTime() + 2));
expect(beforeResend).toMatchObject({ status: "pending" });
expect(afterResend).toMatchObject({ status: "pending" });
if (beforeResend.status !== "pending" || afterResend.status !== "pending") throw new Error("Expected pending registration views");
expect(afterResend.creationRequestKey).toBe(beforeResend.creationRequestKey);
expect(findByTokenMock).toHaveBeenNthCalledWith(1, verificationToken);
expect(findByTokenMock).toHaveBeenNthCalledWith(2, rotatedToken);
});
it.each([
["39 characters", "a".repeat(39)],
["41 characters", "a".repeat(41)],
["non-hex", `${"a".repeat(39)}g`],
["oversized", "a".repeat(2048)],
])("rejects %s before the SECURITY-DEFINER token lookup", async (_label, invalidToken) => {
await expect(getRegistrationByToken(invalidToken)).resolves.toBeNull();
expect(findByTokenMock).not.toHaveBeenCalled();
});
it.each([verificationToken, "ABCDEF0123456789ABCDEF0123456789ABCDEF01"])("accepts a valid legacy/new 40-hex token: %s", async (validToken) => {
findByTokenMock.mockResolvedValueOnce({ id: "registration_2", createdAt } as Awaited<ReturnType<typeof findRegistrationByTokenCapability>>);
await expect(getRegistrationByToken(validToken, new Date(createdAt.getTime() + 1))).resolves.toMatchObject({ id: "registration_2" });
expect(findByTokenMock).toHaveBeenCalledWith(validToken);
});
it("accepts verification at 23:59:59.999 and rejects it exactly at the 24h boundary for loader and action helpers", async () => {
const registration = { id: "registration_1", email: "ada@example.test", createdAt, createdTenantId: null } as Awaited<
ReturnType<typeof findRegistrationByTokenCapability>
>;
findByTokenMock.mockResolvedValue(registration);
await expect(getRegistrationByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS - 1))).resolves.toMatchObject({
id: "registration_1",
});
await expect(getRegistrationByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS))).resolves.toBeNull();
await expect(
getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS - 1))
).resolves.toMatchObject({ email: "ada@example.test" });
await expect(getRegistrationVerificationViewByToken(verificationToken, new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS))).resolves.toEqual({
status: "expired",
});
});
it("distinguishes expired, consumed, and invalid links without exposing registration PII", async () => {
findByTokenMock
.mockResolvedValueOnce({ id: "registration_expired", email: "expired@example.test", createdAt, createdTenantId: null } as Awaited<
ReturnType<typeof findRegistrationByTokenCapability>
>)
.mockResolvedValueOnce({ id: "registration_used", email: "used@example.test", createdAt, createdTenantId: "tenant_1" } as Awaited<
ReturnType<typeof findRegistrationByTokenCapability>
>)
.mockResolvedValueOnce(null);
const afterTtl = new Date(createdAt.getTime() + REGISTRATION_VERIFICATION_TTL_MS);
const expired = await getRegistrationVerificationStateByToken(verificationToken, afterTtl);
const used = await getRegistrationVerificationStateByToken(verificationToken, afterTtl);
const invalidView = await getRegistrationVerificationViewByToken(verificationToken, afterTtl);
expect(expired.status).toBe("expired");
expect(used.status).toBe("used");
expect(invalidView).toEqual({ status: "invalid" });
expect(JSON.stringify(invalidView)).not.toContain("example.test");
});
it("persists lead conversion context through the create capability", async () => {
createCapabilityMock.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
await createRegistration({
email: "ada@example.test",
@@ -43,6 +177,8 @@ describe("registration db helpers", () => {
token: "registration-token",
company: "Analytical Engines",
selectedSubscriptionPriceId: "price_1",
selectedOfficeSeatQuantity: 4,
selectedFieldSeatQuantity: 8,
leadConversionLeadId: "lead_1",
leadConversionToken: "signed-lead-token",
leadConversionPlanId: "plan_pro",
@@ -50,25 +186,25 @@ describe("registration db helpers", () => {
slug: "ada",
});
expect(registrationMock.create).toHaveBeenCalledWith({
data: {
email: "ada@example.test",
firstName: "Ada",
lastName: "Lovelace",
token: "registration-token",
company: "Analytical Engines",
selectedSubscriptionPriceId: "price_1",
leadConversionLeadId: "lead_1",
leadConversionToken: "signed-lead-token",
leadConversionPlanId: "plan_pro",
ipAddress: "127.0.0.1",
slug: "ada",
},
expect(createCapabilityMock).toHaveBeenCalledWith({
email: "ada@example.test",
firstName: "Ada",
lastName: "Lovelace",
token: "registration-token",
company: "Analytical Engines",
selectedSubscriptionPriceId: "price_1",
selectedOfficeSeatQuantity: 4,
selectedFieldSeatQuantity: 8,
leadConversionLeadId: "lead_1",
leadConversionToken: "signed-lead-token",
leadConversionPlanId: "plan_pro",
ipAddress: "127.0.0.1",
slug: "ada",
});
});
it("clears missing lead conversion fields to null when creating registrations", async () => {
registrationMock.create.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
createCapabilityMock.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof createRegistration>>);
await createRegistration({
email: "ada@example.test",
@@ -77,47 +213,41 @@ describe("registration db helpers", () => {
token: "registration-token",
company: null,
selectedSubscriptionPriceId: null,
selectedOfficeSeatQuantity: null,
selectedFieldSeatQuantity: null,
ipAddress: null,
slug: null,
});
expect(registrationMock.create).toHaveBeenCalledWith(
expect(createCapabilityMock).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
leadConversionLeadId: null,
leadConversionToken: null,
leadConversionPlanId: null,
}),
leadConversionLeadId: null,
leadConversionToken: null,
leadConversionPlanId: null,
})
);
});
it("updates lead conversion context and created tenant id together", async () => {
registrationMock.update.mockResolvedValueOnce({ id: "registration_1" } as Awaited<ReturnType<typeof updateRegistration>>);
it("binds tenant consumption to the expected token and rejects stale capabilities", async () => {
updateCapabilityMock.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
await updateRegistration("registration_1", {
firstName: "Ada",
lastName: "Lovelace",
company: "Analytical Engines",
createdTenantId: "tenant_1",
token: "new-token",
leadConversionLeadId: "lead_1",
leadConversionToken: "signed-lead-token",
leadConversionPlanId: "plan_pro",
});
await expect(updateRegistration("registration_1", { expectedToken: "token_1" }, { createdTenantId: "tenant_1" })).resolves.toBe(true);
await expect(updateRegistration("registration_1", { expectedToken: "stale-token" }, { createdTenantId: "tenant_1" })).rejects.toThrow(
"Registration update capability was rejected"
);
});
expect(registrationMock.update).toHaveBeenCalledWith({
where: { id: "registration_1" },
data: {
firstName: "Ada",
lastName: "Lovelace",
company: "Analytical Engines",
createdTenantId: "tenant_1",
token: "new-token",
leadConversionLeadId: "lead_1",
leadConversionToken: "signed-lead-token",
leadConversionPlanId: "plan_pro",
},
it("rotates a resend only through the previous-token capability", async () => {
rotateCapabilityMock.mockResolvedValueOnce(true).mockResolvedValueOnce(false);
await expect(rotateRegistrationVerification("registration_1", "old-token", verificationToken)).resolves.toBe(true);
await expect(rotateRegistrationVerification("registration_1", "stale-token", verificationToken)).rejects.toThrow(
"Registration verification rotation capability was rejected"
);
expect(rotateCapabilityMock).toHaveBeenNthCalledWith(1, {
id: "registration_1",
expectedToken: "old-token",
token: verificationToken,
});
});
});
@@ -1,19 +1,67 @@
import { db } from "../db.server";
import {
createRegistrationCapability,
findRegistrationBillingPreferenceCapability,
findRegistrationByTokenCapability,
findRegistrationSummaryByEmail,
rotateRegistrationVerificationCapability,
updateRegistrationCapability,
} from "@hivegrid/db/pretenant-security.server";
import { deriveVerificationCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
export async function getRegistrationByEmail(email: string) {
return await db.registration.findFirst({
where: {
email,
},
});
export const REGISTRATION_VERIFICATION_TTL_MS = 24 * 60 * 60 * 1000;
const REGISTRATION_VERIFICATION_TOKEN_PATTERN = /^[a-f0-9]{40}$/iu;
type RegistrationRecord = NonNullable<Awaited<ReturnType<typeof findRegistrationByTokenCapability>>>;
export type RegistrationVerificationState =
| { status: "invalid" }
| { status: "expired"; registration: RegistrationRecord }
| { status: "used"; registration: RegistrationRecord }
| { status: "pending"; registration: RegistrationRecord };
export class RegistrationVerificationRotationConflictError extends Error {
constructor() {
super("Registration verification rotation capability was rejected");
this.name = "RegistrationVerificationRotationConflictError";
}
}
export async function getRegistrationByToken(token: string) {
return await db.registration.findUnique({
where: {
token,
},
});
export async function getRegistrationByEmail(email: string) {
return await findRegistrationSummaryByEmail(email);
}
export async function getRegistrationBillingPreference(tenantId: string, userId: string) {
return await findRegistrationBillingPreferenceCapability(tenantId, userId);
}
export async function getRegistrationByToken(token: string, now = new Date()) {
const state = await getRegistrationVerificationStateByToken(token, now);
return state.status === "pending" || state.status === "used" ? state.registration : null;
}
export async function getRegistrationVerificationStateByToken(token: string, now = new Date()): Promise<RegistrationVerificationState> {
if (!REGISTRATION_VERIFICATION_TOKEN_PATTERN.test(token)) return { status: "invalid" };
const registration = await findRegistrationByTokenCapability(token);
if (!registration) return { status: "invalid" };
if (registration.createdTenantId) return { status: "used", registration };
if (!isRegistrationVerificationFresh(registration.createdAt, now)) return { status: "expired", registration };
return { status: "pending", registration };
}
/** Minimal projection for the public verification page. */
export async function getRegistrationVerificationViewByToken(token: string, now = new Date()) {
const state = await getRegistrationVerificationStateByToken(token, now);
if (state.status !== "pending") return { status: state.status } as const;
return {
status: "pending" as const,
email: state.registration.email,
creationRequestKey: deriveVerificationCreationRequestKey(state.registration.id),
};
}
export function isRegistrationVerificationFresh(createdAt: Date | string, now = new Date()): boolean {
const createdAtMs = new Date(createdAt).getTime();
const nowMs = now.getTime();
return Number.isFinite(createdAtMs) && nowMs >= createdAtMs && nowMs - createdAtMs < REGISTRATION_VERIFICATION_TTL_MS;
}
export async function createRegistration(data: {
@@ -23,53 +71,43 @@ export async function createRegistration(data: {
token: string;
company: string | null;
selectedSubscriptionPriceId: string | null;
selectedOfficeSeatQuantity: number | null;
selectedFieldSeatQuantity: number | null;
leadConversionLeadId?: string | null;
leadConversionToken?: string | null;
leadConversionPlanId?: string | null;
ipAddress: string | null;
slug: string | null;
}) {
return await db.registration.create({
data: {
email: data.email,
firstName: data.firstName,
lastName: data.lastName,
token: data.token,
company: data.company,
selectedSubscriptionPriceId: data.selectedSubscriptionPriceId,
leadConversionLeadId: data.leadConversionLeadId ?? null,
leadConversionToken: data.leadConversionToken ?? null,
leadConversionPlanId: data.leadConversionPlanId ?? null,
ipAddress: data.ipAddress,
slug: data.slug,
},
return await createRegistrationCapability({
email: data.email,
firstName: data.firstName,
lastName: data.lastName,
token: data.token,
company: data.company,
selectedSubscriptionPriceId: data.selectedSubscriptionPriceId,
selectedOfficeSeatQuantity: data.selectedOfficeSeatQuantity,
selectedFieldSeatQuantity: data.selectedFieldSeatQuantity,
leadConversionLeadId: data.leadConversionLeadId ?? null,
leadConversionToken: data.leadConversionToken ?? null,
leadConversionPlanId: data.leadConversionPlanId ?? null,
ipAddress: data.ipAddress,
slug: data.slug,
});
}
export async function updateRegistration(
id: string,
data: {
firstName?: string;
lastName?: string;
company?: string | null;
createdTenantId?: string | null;
token?: string;
leadConversionLeadId?: string | null;
leadConversionToken?: string | null;
leadConversionPlanId?: string | null;
export async function rotateRegistrationVerification(id: string, expectedToken: string, token: string) {
const updated = await rotateRegistrationVerificationCapability({ id, expectedToken, token });
if (!updated) {
throw new RegistrationVerificationRotationConflictError();
}
) {
return await db.registration.update({
where: { id },
data: {
firstName: data.firstName,
lastName: data.lastName,
company: data.company,
createdTenantId: data.createdTenantId,
token: data.token,
leadConversionLeadId: data.leadConversionLeadId,
leadConversionToken: data.leadConversionToken,
leadConversionPlanId: data.leadConversionPlanId,
},
});
return true;
}
export async function updateRegistration(id: string, capability: { expectedToken: string }, data: { createdTenantId: string }) {
const updated = await updateRegistrationCapability({ id, expectedToken: capability.expectedToken, patch: data });
if (!updated) {
throw new Error("Registration update capability was rejected");
}
return updated;
}
@@ -0,0 +1,162 @@
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
import { describe, expect, it } from "vitest";
import { createApiKeyAuthCache, API_KEY_AUTH_CACHE_TTL_SECONDS } from "~/utils/api/api-key-auth-cache.server";
import { createAppConfigurationCache } from "./app-configuration-cache.server";
import { createTenantSecurityCache, TENANT_SNAPSHOT_SAFETY_TTL_SECONDS } from "./tenant-cache.server";
import { createUserSnapshotCache, USER_SNAPSHOT_CACHE_TTL_SECONDS } from "./user-snapshot-cache.server";
import type { UserWithoutPassword } from "./users.db.server";
const tick = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
function stores(now: () => number = () => Date.now()) {
const adapter = new MemoryAdapter({ now });
return {
first: createSharedStore({ namespace: "security-cache-test", adapter }),
second: createSharedStore({ namespace: "security-cache-test", adapter }),
};
}
function apiKeySnapshot(): LegacyApiKeySimple {
return {
id: "api-key-1",
alias: "Automation",
expires: new Date("2030-01-01T00:00:00.000Z"),
tenantId: "tenant-1",
createdByUserId: "user-1",
active: true,
scopes: ["workflow:read"],
tenant: { id: "tenant-1", name: "Acme", slug: "acme", deactivatedReason: null },
};
}
function userSnapshot(isAdmin = true): UserWithoutPassword {
return {
id: "user-1",
email: "admin@example.test",
firstName: "Ada",
lastName: "Admin",
avatar: null,
phone: null,
admin: isAdmin
? {
userId: "user-1",
ssoProvider: "authentik",
ssoSubjectId: "subject-1",
ssoGroups: ["hivegrid-admin"],
lastSsoLoginAt: new Date("2026-07-12T10:00:00.000Z"),
}
: null,
defaultTenantId: "tenant-1",
createdAt: new Date("2026-01-01T00:00:00.000Z"),
locale: "de",
lightOrDarkMode: "light",
};
}
describe("cross-replica security snapshot caches", () => {
it("never stores a plaintext API key and invalidates a peer replica immediately", async () => {
const { first, second } = stores();
const firstCache = createApiKeyAuthCache(first);
const secondCache = createApiKeyAuthCache(second);
const disposeSecond = await secondCache.subscribe();
const rawApiKey = "hg_live_this_is_the_plaintext_credential";
const lookupKey = `apiKeyHash:${"a".repeat(64)}`;
await firstCache.set(lookupKey, apiKeySnapshot());
expect((await secondCache.get(lookupKey))?.expires).toEqual(new Date("2030-01-01T00:00:00.000Z"));
const stored = await first.get(`cache:api-key-auth:${lookupKey}`);
expect(stored).not.toContain(rawApiKey);
expect(stored).not.toContain("hg_live_");
firstCache.deleteLocal(lookupKey);
await firstCache.l2.invalidate(lookupKey);
await tick();
expect(secondCache.l1.get(lookupKey)).toBeUndefined();
expect(await secondCache.get(lookupKey)).toBeNull();
await disposeSecond();
});
it("expires an API-key L1 snapshot after a missed invalidation", async () => {
let now = 1_000;
const { first, second } = stores(() => now);
const firstCache = createApiKeyAuthCache(first, { now: () => now });
const disconnectedReplica = createApiKeyAuthCache(second, { now: () => now });
const lookupKey = `apiKeyHash:${"b".repeat(64)}`;
await firstCache.set(lookupKey, apiKeySnapshot());
expect(await disconnectedReplica.get(lookupKey)).not.toBeNull();
await firstCache.l2.delete(lookupKey);
now += API_KEY_AUTH_CACHE_TTL_SECONDS * 1_000 + 1;
expect(await disconnectedReplica.get(lookupKey)).toBeNull();
});
it("revokes a cached admin snapshot on a peer and bounds missed events", async () => {
let now = 10_000;
const { first, second } = stores(() => now);
const firstCache = createUserSnapshotCache(first, { now: () => now });
const secondCache = createUserSnapshotCache(second, { now: () => now });
const disposeSecond = await secondCache.subscribe();
await firstCache.set("user-1", userSnapshot());
expect((await secondCache.get("user-1"))?.admin).not.toBeNull();
await firstCache.l2.invalidate("user-1");
await tick();
expect(secondCache.l1.get("user-1")).toBeUndefined();
await firstCache.set("user-1", userSnapshot());
expect(await secondCache.get("user-1")).not.toBeNull();
await disposeSecond();
await firstCache.l2.delete("user-1");
now += USER_SNAPSHOT_CACHE_TTL_SECONDS * 1_000 + 1;
expect(await secondCache.get("user-1")).toBeNull();
});
it("invalidates tenant deactivation snapshots across replicas with a short fallback TTL", async () => {
let now = 20_000;
const { first, second } = stores(() => now);
const firstCache = createTenantSecurityCache(first, { now: () => now });
const secondCache = createTenantSecurityCache(second, { now: () => now });
const disposeSecond = await secondCache.subscribe();
const snapshot = { id: "tenant-1", name: "Acme", slug: "acme", deactivatedReason: null };
await firstCache.set("tenant-1", snapshot);
expect(await secondCache.get("tenant-1")).toEqual(snapshot);
await firstCache.l2.invalidate("tenant-1");
await tick();
expect(secondCache.l1.get("tenant-1")).toBeUndefined();
await firstCache.set("tenant-1", snapshot);
expect(await secondCache.get("tenant-1")).toEqual(snapshot);
await disposeSecond();
await firstCache.l2.delete("tenant-1");
now += TENANT_SNAPSHOT_SAFETY_TTL_SECONDS * 1_000 + 1;
expect(await secondCache.get("tenant-1")).toBeNull();
});
it("invalidates auth policy and custom-script configuration across replicas", async () => {
const { first, second } = stores();
const firstCache = createAppConfigurationCache(first);
const secondCache = createAppConfigurationCache(second);
const disposeSecond = await secondCache.subscribe();
const snapshot = {
id: "configuration-1",
updatedAt: new Date("2026-07-12T10:00:00.000Z"),
authRequireEmailVerification: true,
headScripts: null,
bodyScripts: null,
} as never;
await firstCache.set("global", snapshot);
expect((await secondCache.get("global"))?.updatedAt).toEqual(new Date("2026-07-12T10:00:00.000Z"));
await firstCache.l2.invalidate("global");
await tick();
expect(secondCache.l1.get("global")).toBeUndefined();
await disposeSecond();
});
});
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff. Show more