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,70 @@
import { describe, expect, it, vi } from "vitest";
import { ADMIN_PERMISSIONS } from "@hivegrid/db/admin-permissions";
import { AdminSidebar } from "~/application/sidebar/AdminSidebar";
import { getSidebarCommandActions } from "~/services/command-registry/commandRegistry";
import { readRepoFile } from "~/utils/testing/repoPaths";
import {
ADMIN_AREA_ACCESS,
ADMIN_ROUTE_ACCESS,
adminAreaAllows,
} from "./admin-access-contract";
const t = vi.fn((key: string) => key) as never;
describe("admin access contract", () => {
it("uses catalog permissions and exposes one breadcrumb contract per route", () => {
const catalog = new Set<string>(ADMIN_PERMISSIONS);
expect(new Set(ADMIN_ROUTE_ACCESS.map((entry) => entry.path)).size).toBe(
ADMIN_ROUTE_ACCESS.length
);
for (const route of ADMIN_ROUTE_ACCESS) {
expect(catalog.has(route.permission)).toBe(true);
expect(route.breadcrumbKey).toMatch(/^[a-z]/);
}
});
it("keeps sidebar and command-search source routes on the same permission", () => {
const commands = getSidebarCommandActions(
AdminSidebar({
t,
appConfiguration: {
app: { features: { tenantApiKeys: true } },
} as never,
}),
"admin"
);
for (const route of ADMIN_ROUTE_ACCESS) {
const command = commands.find((candidate) => candidate.id === route.path);
expect(command?.scope.permission, route.path).toBe(route.permission);
}
});
it("uses the contract constants in sensitive direct route guards", () => {
const directRouteContracts = {
dashboard:
"apps/web/app/utils/data/.server/adminDashboardRouteData.ts",
support: "apps/web/app/routes/admin/support.tsx",
health: "apps/web/app/routes/admin/system/index.tsx",
jobs: "apps/web/app/routes/admin/system/jobs.tsx",
system: "apps/web/app/routes/admin/system/health.tsx",
deploys: "apps/web/app/routes/admin/system/deploys.tsx",
} as const;
for (const [area, path] of Object.entries(directRouteContracts)) {
expect(readRepoFile(path)).toContain(`ADMIN_AREA_ACCESS.${area}`);
}
});
it("unions array requirements and denies unrelated roles", () => {
expect(
adminAreaAllows(["admin_sales.phone.call"], "salesCommunication")
).toBe(true);
expect(adminAreaAllows(["admin.dashboard.view"], "support")).toBe(false);
expect(
adminAreaAllows(
[ADMIN_AREA_ACCESS.support],
"support"
)
).toBe(true);
});
});
@@ -0,0 +1,91 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
/**
* One permission vocabulary for admin navigation, command search, breadcrumbs
* and direct route guards. A route must not invent a second, weaker gate.
*/
export const ADMIN_AREA_ACCESS = {
dashboard: "admin.dashboard.view",
employees: "admin_identity.users.read",
roles: "admin_identity.roles.read",
security: "admin_identity.sessions.read",
support: "admin_identity.impersonation.start",
health: "admin.metrics.view",
jobs: "admin.metrics.view",
system: "admin.metrics.view",
deploys: "admin.metrics.view",
featureFlags: "admin.featureFlags.view",
sales: "admin_sales.crm.read",
salesCommunication: [
"admin_sales.email.send",
"admin_sales.phone.call",
"admin_sales.booking.manage",
],
salesReporting: "admin_sales.reporting.read",
} as const satisfies Record<
string,
AdminPermissionName | readonly AdminPermissionName[]
>;
export type AdminAreaKey = keyof typeof ADMIN_AREA_ACCESS;
export const ADMIN_ROUTE_ACCESS = [
{
area: "dashboard",
path: "/dashboard",
breadcrumbKey: "app.sidebar.dashboard",
permission: ADMIN_AREA_ACCESS.dashboard,
},
{
area: "employees",
path: "/settings/admin-users",
breadcrumbKey: "admin.sales.adminUsers.title",
permission: ADMIN_AREA_ACCESS.employees,
},
{
area: "roles",
path: "/settings/admin-roles",
breadcrumbKey: "admin.sales.adminRoles.title",
permission: ADMIN_AREA_ACCESS.roles,
},
{
area: "support",
path: "/support",
breadcrumbKey: "admin.supportInbox.title",
permission: ADMIN_AREA_ACCESS.support,
},
{
area: "health",
path: "/system",
breadcrumbKey: "admin.health.title",
permission: ADMIN_AREA_ACCESS.health,
},
{
area: "jobs",
path: "/system/jobs",
breadcrumbKey: "admin.jobs.title",
permission: ADMIN_AREA_ACCESS.jobs,
},
{
area: "system",
path: "/system/health",
breadcrumbKey: "admin.system.title",
permission: ADMIN_AREA_ACCESS.system,
},
{
area: "deploys",
path: "/system/deploys",
breadcrumbKey: "admin.deploys.title",
permission: ADMIN_AREA_ACCESS.deploys,
},
] as const;
export function adminAreaAllows(
permissions: readonly string[],
area: AdminAreaKey
): boolean {
const requirement = ADMIN_AREA_ACCESS[area];
return typeof requirement === "string"
? permissions.includes(requirement)
: requirement.some((permission) => permissions.includes(permission));
}
@@ -93,7 +93,11 @@ describe("buildAdminActionAuditInput", () => {
it("extracts client ip + user-agent from a request when present", () => {
const request = new Request("https://admin.hivegrid.de/tenants/9", {
headers: { "x-forwarded-for": "203.0.113.7, 10.0.0.1", "user-agent": "ops-browser/1.0" },
headers: {
"cf-connecting-ip": "203.0.113.7",
"x-forwarded-for": "198.51.100.250, 173.245.48.10",
"user-agent": "ops-browser/1.0",
},
});
const input = buildAdminActionAuditInput({
action: "impersonation.started",
@@ -17,8 +17,15 @@
* The validation + payload-shaping below are pure functions so they unit
* test without a database; only `recordAdminAction` touches the writer.
*/
import { createAuditEvent, type AuditEventInput, type AuditOutcome } from "@hivegrid/db/audit-events.server";
import {
createAuditEvent,
createAuditEventInExistingTransaction,
type AuditEventInput,
type AuditEventWriterClient,
type AuditOutcome,
} from "@hivegrid/db/audit-events.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
/**
* Closed taxonomy of audited platform-operator actions. Closed union so a
@@ -38,10 +45,24 @@ export const ADMIN_OPERATOR_ACTIONS = [
"queue.paused",
"queue.resumed",
"queue.jobRetried",
"webhook.replayRequested",
"support.replied",
"support.noteAdded",
"support.statusChanged",
"support.assigned",
// AK-P21 — reading a customer-uploaded feedback attachment. A read, not a
// mutation, but it exposes material the customer uploaded, so it is audited
// like the mutating operator actions.
"support.attachmentDownloaded",
"security.sessionRevoked",
"security.trustedDeviceForgotten",
"security.adminUserPrepared",
"security.adminUserDisabled",
"security.adminRolesChanged",
"security.adminRolePermissionsChanged",
"featureFlag.bulkOverride",
"portalDomain.killSwitchEnabled",
"portalDomain.killSwitchDisabled",
] as const;
export type AdminOperatorAction = (typeof ADMIN_OPERATOR_ACTIONS)[number];
@@ -127,8 +148,7 @@ export type AdminActionAuditContext = {
function clientMeta(request: Request | undefined): { ip: string | null; userAgent: string | null } {
if (!request) return { ip: null, userAgent: null };
const fwd = request.headers.get("x-forwarded-for") ?? "";
const ip = fwd.split(",")[0]?.trim() || request.headers.get("x-real-ip") || null;
const ip = getTrustedClientIpOrNull(request);
const userAgent = request.headers.get("user-agent") || null;
return { ip, userAgent };
}
@@ -168,6 +188,11 @@ export function buildAdminActionAuditInput(context: AdminActionAuditContext): Au
* propagate (unlike the best-effort SSO logger): a sensitive operator
* action that cannot be audited should surface, not silently succeed.
*/
export async function recordAdminAction(context: AdminActionAuditContext): Promise<void> {
await createAuditEvent(buildAdminActionAuditInput(context));
export async function recordAdminAction(context: AdminActionAuditContext, client?: AuditEventWriterClient): Promise<void> {
const input = buildAdminActionAuditInput(context);
if (client) {
await createAuditEventInExistingTransaction(input, client);
return;
}
await createAuditEvent(input);
}
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import {
hashAdminBookingManageNonce,
issueAdminBookingManageToken,
verifyAdminBookingManageToken,
} from "./admin-booking-manage-token.server.js";
const secret = "test-secret-with-at-least-thirty-two-characters";
const now = new Date("2026-07-25T12:00:00.000Z");
const nonce = "abcdefghijklmnopqrstuvwxyz_123456";
describe("admin booking manage tokens", () => {
it("round-trips bounded signed claims", () => {
const token = issueAdminBookingManageToken({
bookingId: "booking_1",
adminUserId: "admin_1",
version: 2,
expiresAt: new Date("2026-08-01T12:00:00.000Z"),
secret,
now,
nonce,
});
expect(
verifyAdminBookingManageToken({ token, secret, now })
).toEqual({
bookingId: "booking_1",
adminUserId: "admin_1",
version: 2,
expiresAt: new Date("2026-08-01T12:00:00.000Z"),
nonce,
});
});
it("rejects tampering, expiry and an unbounded lifetime", () => {
const token = issueAdminBookingManageToken({
bookingId: "booking_1",
adminUserId: "admin_1",
version: 1,
expiresAt: new Date("2026-08-01T12:00:00.000Z"),
secret,
now,
nonce,
});
expect(() =>
verifyAdminBookingManageToken({
token: `${token.slice(0, -1)}x`,
secret,
now,
})
).toThrow("invalid_token");
expect(() =>
verifyAdminBookingManageToken({
token,
secret,
now: new Date("2026-08-02T12:00:00.000Z"),
})
).toThrow("expired_token");
expect(() =>
issueAdminBookingManageToken({
bookingId: "booking_1",
adminUserId: "admin_1",
version: 1,
expiresAt: new Date("2027-08-01T12:00:00.000Z"),
secret,
now,
nonce,
})
).toThrow("invalid_expiry");
});
it("derives a stable storage-safe replay marker", () => {
expect(hashAdminBookingManageNonce(nonce)).toMatch(/^[a-f0-9]{64}$/u);
expect(hashAdminBookingManageNonce(nonce)).toBe(
hashAdminBookingManageNonce(nonce)
);
});
});
@@ -0,0 +1,172 @@
import {
createHmac,
randomBytes,
timingSafeEqual,
} from "node:crypto";
const TOKEN_CONTEXT = "admin-sales:booking-manage:v1";
const MAX_TOKEN_LENGTH = 2_048;
const MAX_LIFETIME_SECONDS = 90 * 86_400;
export type AdminBookingManageClaims = {
readonly bookingId: string;
readonly adminUserId: string;
readonly version: number;
readonly expiresAt: Date;
readonly nonce: string;
};
type SerializedClaims = {
readonly b: string;
readonly a: string;
readonly v: number;
readonly exp: number;
readonly n: string;
};
export function issueAdminBookingManageToken(input: {
readonly bookingId: string;
readonly adminUserId: string;
readonly version: number;
readonly expiresAt: Date;
readonly secret: string;
readonly now?: Date;
readonly nonce?: string;
}): string {
const now = input.now ?? new Date();
const claims = normalizeClaims({
bookingId: input.bookingId,
adminUserId: input.adminUserId,
version: input.version,
expiresAt: input.expiresAt,
nonce: input.nonce ?? randomBytes(24).toString("base64url"),
});
assertSecret(input.secret);
const lifetime = Math.ceil(
(claims.expiresAt.getTime() - now.getTime()) / 1_000
);
if (lifetime <= 0 || lifetime > MAX_LIFETIME_SECONDS) {
throw new AdminBookingManageTokenError("invalid_expiry");
}
const payload = Buffer.from(
JSON.stringify(serialize(claims)),
"utf8"
).toString("base64url");
return `${payload}.${sign(payload, input.secret)}`;
}
export function verifyAdminBookingManageToken(input: {
readonly token: string;
readonly secret: string;
readonly now?: Date;
}): AdminBookingManageClaims {
assertSecret(input.secret);
if (!input.token || input.token.length > MAX_TOKEN_LENGTH) {
throw new AdminBookingManageTokenError("invalid_token");
}
const [payload, signature, ...extra] = input.token.split(".");
if (!payload || !signature || extra.length > 0) {
throw new AdminBookingManageTokenError("invalid_token");
}
const expected = Buffer.from(sign(payload, input.secret), "base64url");
const actual = Buffer.from(signature, "base64url");
if (
expected.length !== actual.length ||
!timingSafeEqual(expected, actual)
) {
throw new AdminBookingManageTokenError("invalid_token");
}
let serialized: unknown;
try {
serialized = JSON.parse(
Buffer.from(payload, "base64url").toString("utf8")
);
} catch {
throw new AdminBookingManageTokenError("invalid_token");
}
const claims = deserialize(serialized);
if (claims.expiresAt.getTime() <= (input.now ?? new Date()).getTime()) {
throw new AdminBookingManageTokenError("expired_token");
}
return claims;
}
export function hashAdminBookingManageNonce(nonce: string): string {
if (!/^[A-Za-z0-9_-]{32,128}$/u.test(nonce)) {
throw new AdminBookingManageTokenError("invalid_nonce");
}
return createHmac("sha256", TOKEN_CONTEXT)
.update(nonce, "utf8")
.digest("hex");
}
function serialize(claims: AdminBookingManageClaims): SerializedClaims {
return {
b: claims.bookingId,
a: claims.adminUserId,
v: claims.version,
exp: Math.floor(claims.expiresAt.getTime() / 1_000),
n: claims.nonce,
};
}
function deserialize(value: unknown): AdminBookingManageClaims {
if (!value || typeof value !== "object" || Array.isArray(value)) {
throw new AdminBookingManageTokenError("invalid_token");
}
const record = value as Record<string, unknown>;
if (
Object.keys(record).sort().join(",") !== "a,b,exp,n,v" ||
typeof record.b !== "string" ||
typeof record.a !== "string" ||
typeof record.v !== "number" ||
typeof record.exp !== "number" ||
typeof record.n !== "string"
) {
throw new AdminBookingManageTokenError("invalid_token");
}
return normalizeClaims({
bookingId: record.b,
adminUserId: record.a,
version: record.v,
expiresAt: new Date(record.exp * 1_000),
nonce: record.n,
});
}
function normalizeClaims(
claims: AdminBookingManageClaims
): AdminBookingManageClaims {
if (
!/^[A-Za-z0-9][A-Za-z0-9_:-]{0,190}$/u.test(claims.bookingId) ||
!/^[A-Za-z0-9][A-Za-z0-9_:-]{0,190}$/u.test(claims.adminUserId) ||
!Number.isSafeInteger(claims.version) ||
claims.version < 1 ||
!Number.isFinite(claims.expiresAt.getTime()) ||
!/^[A-Za-z0-9_-]{32,128}$/u.test(claims.nonce)
) {
throw new AdminBookingManageTokenError("invalid_claims");
}
return claims;
}
function sign(payload: string, secret: string): string {
return createHmac("sha256", secret)
.update(TOKEN_CONTEXT)
.update("\0")
.update(payload)
.digest("base64url");
}
function assertSecret(secret: string): void {
if (secret.length < 32) {
throw new AdminBookingManageTokenError("secret_unavailable");
}
}
export class AdminBookingManageTokenError extends Error {
constructor(readonly code: string) {
super(code);
this.name = "AdminBookingManageTokenError";
}
}
@@ -0,0 +1,109 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import {
createAdminBookingSettingsService,
createPrismaAdminBookingSettingsRepository,
} from "@hivegrid/db/admin-booking-settings.server";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export async function runAsAdminBookingSettingsOperator<T>(
request: Request,
operation: (context: {
readonly adminUserId: string;
readonly settings: ReturnType<typeof createAdminBookingSettingsService>;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
}) => Promise<T>
) {
return runAsAdminIdentity(
request,
"admin_sales.booking.manage",
async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true },
});
if (!admin) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const authorize = async (permission: AdminPermissionName) => {
if (!(await adminHasPermission(admin.id, permission, db))) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
};
const actorBase = {
adminUserId: admin.id,
email: admin.email,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
return operation({
adminUserId: admin.id,
settings: createAdminBookingSettingsService({
repository: createPrismaAdminBookingSettingsRepository(db),
authorize,
}),
actor: (reason) => ({ ...actorBase, reason }),
});
}
);
}
export async function readAdminBookingSettings(adminUserId: string) {
const [meetingTypes, pages, rules, overrides, hosts] =
await Promise.all([
db.adminMeetingType.findMany({
where: { archivedAt: null },
orderBy: [{ name: "asc" }, { id: "asc" }],
}),
db.adminBookingPage.findMany({
where: { archivedAt: null },
orderBy: [{ title: "asc" }, { id: "asc" }],
}),
db.adminAvailabilityRule.findMany({
where: { adminUserId, archivedAt: null },
orderBy: [{ dayOfWeek: "asc" }, { startMinutes: "asc" }],
}),
db.adminAvailabilityOverride.findMany({
where: { adminUserId, archivedAt: null },
orderBy: [{ date: "asc" }, { startMinutes: "asc" }],
}),
db.adminUser.findMany({
where: {
status: "active",
roles: {
some: {
role: {
active: true,
permissions: {
some: {
permission: {
name: "admin_sales.booking.manage",
},
},
},
},
},
},
},
orderBy: [{ firstName: "asc" }, { lastName: "asc" }, { email: "asc" }],
select: { id: true, firstName: true, lastName: true, email: true },
}),
]);
return { meetingTypes, pages, rules, overrides, hosts };
}
@@ -0,0 +1,70 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
meetingTypes: vi.fn(),
pages: vi.fn(),
bookings: vi.fn(),
calendars: vi.fn(),
audit: vi.fn(),
}));
vi.mock("@hivegrid/db/admin-sales-core.server", () => ({
writeAdminSalesAudit: mocks.audit,
}));
vi.mock("~/utils/db.server", () => ({
db: {
adminMeetingType: { findMany: mocks.meetingTypes },
adminBookingPage: { findMany: mocks.pages },
adminBooking: { findMany: mocks.bookings },
adminCalendarConnection: { count: mocks.calendars },
},
}));
import { readAdminBookingWorkspace } from "./admin-booking-workspace.server";
describe("admin booking team scope", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.meetingTypes.mockResolvedValue([]);
mocks.pages.mockResolvedValue([]);
mocks.bookings.mockResolvedValue([
{ id: "booking-b", adminUserId: "sales-b" },
]);
mocks.calendars.mockResolvedValue(0);
});
it("loads team bookings and records a summarized foreign-access audit", async () => {
await readAdminBookingWorkspace({
adminUserId: "manager",
canReadAllCommunication: true,
actor: (reason) => ({
adminUserId: "manager",
email: "manager@example.test",
reason,
requestId: null,
ip: null,
userAgent: null,
}),
});
expect(mocks.bookings).toHaveBeenCalledWith(
expect.objectContaining({ where: {} })
);
expect(mocks.audit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "admin.sales.booking.foreignBookings.read",
targetId: "booking-b",
after: {
foreignTargets: [
{
targetId: "booking-b",
dataOwnerAdminUserId: "sales-b",
},
],
accessKind: "read",
},
})
);
});
});
@@ -0,0 +1,154 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import { writeAdminSalesAudit } from "@hivegrid/db/admin-sales-core.server";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export async function runAsAdminBookingOperator<T>(
request: Request,
permission:
| Extract<
AdminPermissionName,
| "admin_sales.booking.manage"
| "admin_sales.communication.read_all"
>
| readonly Extract<
AdminPermissionName,
| "admin_sales.booking.manage"
| "admin_sales.communication.read_all"
>[],
operation: (context: {
readonly adminUserId: string;
readonly email: string;
readonly canReadAllCommunication: boolean;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
}) => Promise<T>
): Promise<T> {
return runAsAdminIdentity(request, permission, async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true },
});
if (!admin) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const canReadAllCommunication = await adminHasPermission(
admin.id,
"admin_sales.communication.read_all",
db
);
const actorBase = {
adminUserId: admin.id,
email: admin.email,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
return operation({
adminUserId: admin.id,
email: admin.email,
canReadAllCommunication,
actor: (reason) => ({ ...actorBase, reason }),
});
});
}
export async function readAdminBookingWorkspace(context: {
readonly adminUserId: string;
readonly canReadAllCommunication: boolean;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
}) {
const bookingWhere = context.canReadAllCommunication
? {}
: {
OR: [
{ adminUserId: context.adminUserId },
{
meetingType: {
hostAdminUserIds: { has: context.adminUserId },
},
},
],
};
const [meetingTypes, pages, bookings, connectedCalendars] =
await Promise.all([
db.adminMeetingType.findMany({
where: { archivedAt: null },
orderBy: [{ active: "desc" }, { name: "asc" }, { id: "asc" }],
}),
db.adminBookingPage.findMany({
where: { archivedAt: null },
orderBy: [
{ published: "desc" },
{ title: "asc" },
{ id: "asc" },
],
include: { meetingType: { select: { name: true } } },
}),
db.adminBooking.findMany({
where: bookingWhere,
orderBy: [{ startsAt: "asc" }, { id: "asc" }],
take: 200,
include: {
contact: {
select: { firstName: true, lastName: true },
},
meetingType: { select: { name: true } },
},
}),
db.adminCalendarConnection.count({
where: {
adminUserId: context.adminUserId,
archivedAt: null,
status: "active",
},
}),
]);
const foreignBookings = bookings.filter(
(booking) => booking.adminUserId !== context.adminUserId
);
if (foreignBookings.length > 0) {
await writeAdminSalesAudit(db, {
actor: context.actor("Fremde Team-Buchungen geöffnet"),
action: "admin.sales.booking.foreignBookings.read",
targetType: "AdminBooking",
targetId: foreignBookings[0]!.id,
after: {
foreignTargets: foreignBookings.map((booking) => ({
targetId: booking.id,
dataOwnerAdminUserId: booking.adminUserId,
})),
accessKind: "read",
},
});
}
return { meetingTypes, pages, bookings, connectedCalendars };
}
export function adminBookingOrigin(request: Request): string {
const configured = process.env.ADMIN_BOOKING_PUBLIC_ORIGIN?.trim();
if (configured) return configured.replace(/\/$/u, "");
const url = new URL(request.url);
return `${url.protocol}//meet.localhost:3000`;
}
@@ -0,0 +1,157 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import {
createAdminCalendarService,
createPrismaAdminCalendarRepository,
} from "@hivegrid/db/admin-calendar.server";
import {
createAdminConnectionsService,
createPrismaAdminConnectionsRepository,
} from "@hivegrid/db/admin-connections.server";
import type { AdminCalendarProviderName } from "@hivegrid/integrations/admin-calendar-provider";
import { createAdminCalendarOAuthGateway } from "@hivegrid/integrations/admin-calendar-oauth.server";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export type AdminCalendarOperatorContext = {
readonly adminUserId: string;
readonly connections: ReturnType<typeof createAdminConnectionsService>;
readonly calendars: ReturnType<typeof createAdminCalendarService>;
readonly providers: ReturnType<typeof createAdminCalendarOAuthGateway>;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
};
export async function runAsAdminCalendarOperator<T>(
request: Request,
operation: (context: AdminCalendarOperatorContext) => Promise<T>
) {
return runAsAdminIdentity(
request,
"admin_sales.booking.manage",
async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true },
});
if (!admin) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const authorize = async (permission: AdminPermissionName) => {
if (!(await adminHasPermission(admin.id, permission, db))) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
};
const actorBase = {
adminUserId: admin.id,
email: admin.email,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
return operation({
adminUserId: admin.id,
connections: createAdminConnectionsService({
repository: createPrismaAdminConnectionsRepository(db),
authorize,
permission: "admin_sales.booking.manage",
}),
calendars: createAdminCalendarService({
repository: createPrismaAdminCalendarRepository(db),
authorize,
}),
providers: createAdminCalendarOAuthGateway(),
actor: (reason) => ({ ...actorBase, reason }),
});
}
);
}
export async function completeAdminCalendarConnection(input: {
readonly context: AdminCalendarOperatorContext;
readonly provider: AdminCalendarProviderName;
readonly code: string;
}) {
const grant = await input.context.providers.exchange(
input.provider,
input.code
);
const actor = input.context.actor("Persönlichen Kalender verbinden");
const connection = await input.context.connections.connect({
adminUserId: input.context.adminUserId,
provider: input.provider,
capability: "calendar",
label: grant.account.displayName,
externalAccountId: grant.account.externalAccountId,
externalAccountEmail: grant.account.emailAddress,
scopes: grant.credentials.scopes,
tokenExpiresAt: new Date(grant.credentials.expiresAt),
credentials: grant.credentials,
actor,
});
const calendar = await input.context.calendars.activate({
adminUserId: input.context.adminUserId,
dataConnectionId: connection.id,
externalCalendarId: grant.calendar.externalCalendarId,
externalCalendarLabel: grant.calendar.label,
timeZone: grant.calendar.timeZone,
actor,
});
return { connectionId: connection.id, calendarConnectionId: calendar.id };
}
export async function listAdminCalendarConnectionSettings(
context: AdminCalendarOperatorContext
) {
return db.adminCalendarConnection.findMany({
where: { adminUserId: context.adminUserId, archivedAt: null },
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
select: {
id: true,
dataConnectionId: true,
externalCalendarLabel: true,
timeZone: true,
status: true,
lastSyncAt: true,
healthMessageKey: true,
dataConnection: {
select: {
provider: true,
externalAccountEmail: true,
},
},
},
});
}
export async function disconnectAdminCalendarConnection(input: {
readonly context: AdminCalendarOperatorContext;
readonly calendarConnectionId: string;
readonly dataConnectionId: string;
}) {
const actor = input.context.actor("Persönlichen Kalender trennen");
await input.context.calendars.disconnect({
adminUserId: input.context.adminUserId,
calendarConnectionId: input.calendarConnectionId,
actor,
});
return input.context.connections.disconnect({
adminUserId: input.context.adminUserId,
connectionId: input.dataConnectionId,
actor,
revokeProviderCredentials: async () => undefined,
});
}
@@ -0,0 +1,79 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { config } = vi.hoisted(() => ({
config: {
nodeEnv: "test",
sessionSecret: "admin-calendar-oauth-state-secret-aaaaa",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https" as const,
},
},
}));
vi.mock("@hivegrid/config", async () => ({
...(await vi.importActual<typeof import("@hivegrid/config")>(
"@hivegrid/config"
)),
loadRequiredWebConfig: () => config,
}));
import {
consumeAdminCalendarOAuthState,
createAdminCalendarOAuthState,
} from "./admin-calendar-oauth-state.server.js";
function requestWith(cookie: string) {
return new Request("https://admin.example.test/callback", {
headers: { cookie: cookie.split(";")[0] ?? "" },
});
}
beforeEach(() => {
config.nodeEnv = "test";
});
describe("admin calendar OAuth state", () => {
it("round-trips only for the bound admin and provider", () => {
const created = createAdminCalendarOAuthState({
adminUserId: "admin-1",
provider: "google_calendar",
now: () => 1_000,
});
expect(
consumeAdminCalendarOAuthState(requestWith(created.cookie), {
expectedState: created.state,
expectedProvider: "google_calendar",
expectedAdminUserId: "admin-1",
now: () => 2_000,
})
).toMatchObject({ ok: true });
expect(
consumeAdminCalendarOAuthState(requestWith(created.cookie), {
expectedState: created.state,
expectedProvider: "microsoft_calendar",
expectedAdminUserId: "admin-1",
now: () => 2_000,
})
).toMatchObject({ ok: false, reason: "mismatch" });
});
it("rejects expired state", () => {
const created = createAdminCalendarOAuthState({
adminUserId: "admin-1",
provider: "google_calendar",
now: () => 1_000,
});
expect(
consumeAdminCalendarOAuthState(requestWith(created.cookie), {
expectedState: created.state,
expectedProvider: "google_calendar",
expectedAdminUserId: "admin-1",
now: () => 11 * 60 * 1_000,
})
).toMatchObject({ ok: false, reason: "expired" });
});
});
@@ -0,0 +1,149 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import {
loadRequiredWebConfig,
resolveHostOnlyCookiePolicy,
} from "@hivegrid/config";
import type { AdminCalendarProviderName } from "@hivegrid/integrations/admin-calendar-provider";
const SECURE_COOKIE = "__Host-hivegrid_admin_calendar_oauth";
const LOCAL_COOKIE = "hivegrid_admin_calendar_oauth";
const TTL_MS = 10 * 60 * 1_000;
type StatePayload = {
readonly state: string;
readonly adminUserId: string;
readonly provider: AdminCalendarProviderName;
readonly createdAt: number;
};
export function createAdminCalendarOAuthState(input: {
readonly adminUserId: string;
readonly provider: AdminCalendarProviderName;
readonly now?: () => number;
readonly secret?: string;
}) {
const payload: StatePayload = {
state: randomBytes(32).toString("hex"),
adminUserId: required(input.adminUserId),
provider: input.provider,
createdAt: input.now?.() ?? Date.now(),
};
const encoded = Buffer.from(JSON.stringify(payload)).toString("base64url");
const policy = cookiePolicy();
return {
state: payload.state,
cookie: [
`${policy.name}=${encoded}.${sign(encoded, resolveSecret(input.secret))}`,
`Path=${policy.path}`,
"HttpOnly",
"SameSite=Lax",
`Max-Age=${TTL_MS / 1_000}`,
...(policy.secure ? ["Secure"] : []),
].join("; "),
};
}
export function consumeAdminCalendarOAuthState(
request: Request,
input: {
readonly expectedState: string;
readonly expectedProvider: AdminCalendarProviderName;
readonly expectedAdminUserId: string;
readonly now?: () => number;
readonly secret?: string;
}
):
| { readonly ok: true; readonly clearCookie: string }
| {
readonly ok: false;
readonly reason:
| "missing"
| "malformed"
| "invalid_signature"
| "expired"
| "mismatch";
readonly clearCookie: string;
} {
const policy = cookiePolicy();
const clearCookie = [
`${policy.name}=`,
`Path=${policy.path}`,
"HttpOnly",
"SameSite=Lax",
"Max-Age=0",
...(policy.secure ? ["Secure"] : []),
].join("; ");
const value = readCookie(request, policy.name);
if (!value) return { ok: false, reason: "missing", clearCookie };
const [encoded, signature, ...rest] = value.split(".");
if (!encoded || !signature || rest.length) {
return { ok: false, reason: "malformed", clearCookie };
}
const expected = sign(encoded, resolveSecret(input.secret));
const left = Buffer.from(signature);
const right = Buffer.from(expected);
if (left.length !== right.length || !timingSafeEqual(left, right)) {
return { ok: false, reason: "invalid_signature", clearCookie };
}
let payload: StatePayload;
try {
payload = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
} catch {
return { ok: false, reason: "malformed", clearCookie };
}
const now = input.now?.() ?? Date.now();
if (
!Number.isFinite(payload.createdAt) ||
payload.createdAt > now + 60_000 ||
now - payload.createdAt > TTL_MS
) {
return { ok: false, reason: "expired", clearCookie };
}
if (
payload.state !== input.expectedState ||
payload.provider !== input.expectedProvider ||
payload.adminUserId !== input.expectedAdminUserId
) {
return { ok: false, reason: "mismatch", clearCookie };
}
return { ok: true, clearCookie };
}
function cookiePolicy() {
const config = loadRequiredWebConfig();
return resolveHostOnlyCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
secureName: SECURE_COOKIE,
localName: LOCAL_COOKIE,
maxAge: TTL_MS / 1_000,
});
}
function resolveSecret(override?: string) {
const secret = override ?? loadRequiredWebConfig().sessionSecret;
if (!secret || Buffer.byteLength(secret) < 32) {
throw new Error("SESSION_SECRET is required for admin calendar OAuth state.");
}
return secret;
}
function sign(value: string, secret: string) {
return createHmac("sha256", secret).update(value).digest("base64url");
}
function readCookie(request: Request, name: string) {
for (const segment of request.headers.get("cookie")?.split(/;\s*/) ?? []) {
const separator = segment.indexOf("=");
if (separator > 0 && segment.slice(0, separator) === name) {
return segment.slice(separator + 1);
}
}
return null;
}
function required(value: string) {
const normalized = value.trim();
if (!normalized) throw new Error("adminUserId is required");
return normalized;
}
@@ -0,0 +1,30 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
describe("admin dashboard locale formatting", () => {
it("threads the request locale into every dashboard data source", () => {
const serviceSource = readFileSync(
path.resolve(
process.cwd(),
"apps/web/app/services/admin/admin-dashboard-personalization.server.ts",
),
"utf8",
);
const routeSource = readFileSync(
path.resolve(
process.cwd(),
"apps/web/app/utils/data/.server/adminDashboardRouteData.ts",
),
"utf8",
);
expect(routeSource).toContain("const { t, locale }");
expect(routeSource).toContain("permissions: permissions as AdminPermissionName[],\n locale,");
expect(serviceSource).toContain("sources[sourceName]({ adminUserId: input.adminUserId, now, locale })");
expect(serviceSource).toContain("new Intl.NumberFormat(locale,");
expect(serviceSource.match(/formatEuroCents\(pipeline\._sum\.amountCents \?\? 0, locale\)/gu)).toHaveLength(2);
expect(serviceSource).not.toContain('new Intl.NumberFormat("de-DE"');
});
});
@@ -0,0 +1,135 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AdminDashboardDataSources } from "./admin-dashboard-personalization.server";
import {
loadPersonalizedAdminDashboard,
selectAdminDashboardWidgetIds,
} from "./admin-dashboard-personalization.server";
const sources = {
salesOwn: vi.fn(async () => [
{ id: "sales_today" as const, value: "2", href: "/sales/tasks/today" },
{ id: "sales_own_pipeline" as const, value: "10 €", href: "/sales/deals" },
{ id: "sales_appointments" as const, value: "1", href: "/sales/bookings" },
{ id: "sales_followups" as const, value: "3", href: "/sales/tasks/today" },
]),
salesTeam: vi.fn(async () => [
{ id: "sales_team_pipeline" as const, value: "20 €", href: "/sales/deals" },
{ id: "sales_unassigned_leads" as const, value: "4", href: "/leads" },
{ id: "sales_team_activity" as const, value: "5", href: "/sales/tasks/today" },
]),
support: vi.fn(async () => [
{ id: "support_inbox" as const, value: "6", href: "/support" },
{ id: "support_customer_events" as const, value: "7", href: "/audit" },
]),
engineering: vi.fn(async () => [
{ id: "engineering_health" as const, value: "OK", href: "/system" },
{ id: "engineering_queues" as const, value: "0", href: "/system/jobs" },
{ id: "engineering_errors" as const, value: "0", href: "/events" },
{ id: "engineering_deploy" as const, value: "abc123", href: "/system/deploys" },
]),
executive: vi.fn(async () => [
{ id: "executive_forecast" as const, value: "1 €", href: "/sales/deals" },
{ id: "executive_revenue" as const, value: "2 €", href: "/sales/deals" },
{ id: "executive_mrr" as const, value: "3 €", href: "/dashboard" },
{ id: "executive_arr" as const, value: "36 €", href: "/dashboard" },
{ id: "executive_churn" as const, value: "0 %", href: "/dashboard" },
]),
} satisfies AdminDashboardDataSources;
describe("admin dashboard personalization", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("unions combined role widgets without duplicates", () => {
const ids = selectAdminDashboardWidgetIds({
roleKeys: ["sales", "sales_manager", "sales"],
permissions: [
"admin_sales.crm.read",
"admin_sales.crm.read_all",
"admin_sales.booking.manage",
"admin_sales.reporting.read_all",
],
});
expect(ids).toEqual([
"sales_own_pipeline",
"sales_today",
"sales_appointments",
"sales_followups",
"sales_team_pipeline",
"sales_unassigned_leads",
"sales_team_activity",
]);
});
it("loads only the data sources selected by roles and effective permissions", async () => {
const vm = await loadPersonalizedAdminDashboard(
{
adminUserId: "admin_sales",
roleKeys: ["sales"],
permissions: [
"admin.dashboard.view",
"admin_sales.crm.read",
"admin_sales.booking.manage",
],
now: new Date("2026-07-26T08:00:00.000Z"),
locale: "en",
},
sources
);
expect(sources.salesOwn).toHaveBeenCalledOnce();
expect(sources.salesOwn).toHaveBeenCalledWith(
expect.objectContaining({ locale: "en" })
);
expect(sources.salesTeam).not.toHaveBeenCalled();
expect(sources.support).not.toHaveBeenCalled();
expect(sources.engineering).not.toHaveBeenCalled();
expect(sources.executive).not.toHaveBeenCalled();
expect(vm.widgets.map((entry) => entry.id)).toEqual([
"sales_own_pipeline",
"sales_today",
"sales_appointments",
"sales_followups",
]);
});
it("does not query a role source after its effective permission is removed", async () => {
const vm = await loadPersonalizedAdminDashboard(
{
adminUserId: "admin_support",
roleKeys: ["support"],
permissions: ["admin.dashboard.view"],
},
sources
);
expect(sources.support).not.toHaveBeenCalled();
expect(vm.widgets).toEqual([]);
});
it("loads combined role sources once each", async () => {
const vm = await loadPersonalizedAdminDashboard(
{
adminUserId: "admin_combined",
roleKeys: ["support", "engineering"],
permissions: [
"admin.dashboard.view",
"admin_identity.impersonation.start",
"admin.metrics.view",
"admin.events.view",
],
},
sources
);
expect(sources.support).toHaveBeenCalledOnce();
expect(sources.engineering).toHaveBeenCalledOnce();
expect(new Set(vm.widgets.map((entry) => entry.id)).size).toBe(
vm.widgets.length
);
expect(sources.salesOwn).not.toHaveBeenCalled();
expect(sources.executive).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,520 @@
import type {
AdminDashboardVM,
AdminDashboardWidgetId,
AdminDashboardWidgetInput,
} from "@hivegrid/view-models";
import { buildAdminDashboardVM } from "@hivegrid/view-models";
import type {
AdminPermissionName,
AdminRoleKey,
} from "@hivegrid/db/admin-permissions";
import {
adminSalesDealReadWhere,
adminSalesTaskReadWhere,
} from "@hivegrid/db/admin-sales-access-scope";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { db } from "~/utils/db.server";
import { adminGetAllTenantsIdsAndNames } from "~/utils/db/tenants.db.server";
import { getMrr } from "~/utils/services/.server/subscriptionService";
import { getOperatorHealthSnapshot } from "./operator-health.server";
type DashboardSource =
| "salesOwn"
| "salesTeam"
| "support"
| "engineering"
| "executive";
type DashboardSourceLoader = (input: {
readonly adminUserId: string;
readonly now: Date;
readonly locale: string;
}) => Promise<readonly AdminDashboardWidgetInput[]>;
export type AdminDashboardDataSources = Readonly<
Record<DashboardSource, DashboardSourceLoader>
>;
const ROLE_WIDGETS = {
super_admin: ["super_platform"],
sales: [
"sales_own_pipeline",
"sales_today",
"sales_appointments",
"sales_followups",
],
sales_manager: [
"sales_team_pipeline",
"sales_unassigned_leads",
"sales_team_activity",
],
support: ["support_inbox", "support_customer_events"],
engineering: [
"engineering_health",
"engineering_queues",
"engineering_errors",
"engineering_deploy",
],
executive: [
"executive_forecast",
"executive_revenue",
"executive_mrr",
"executive_arr",
"executive_churn",
],
viewer: ["viewer_reports"],
} as const satisfies Record<AdminRoleKey, readonly AdminDashboardWidgetId[]>;
const WIDGET_PERMISSION = {
sales_own_pipeline: "admin_sales.crm.read",
sales_today: "admin_sales.crm.read",
sales_appointments: "admin_sales.booking.manage",
sales_followups: "admin_sales.crm.read",
sales_team_pipeline: "admin_sales.crm.read_all",
sales_unassigned_leads: "admin_sales.crm.read_all",
sales_team_activity: "admin_sales.reporting.read_all",
support_inbox: "admin_identity.impersonation.start",
support_customer_events: "admin_identity.impersonation.start",
engineering_health: "admin.metrics.view",
engineering_queues: "admin.metrics.view",
engineering_errors: "admin.events.view",
engineering_deploy: "admin.metrics.view",
executive_forecast: "admin_sales.reporting.read_all",
executive_revenue: "admin_sales.reporting.read_all",
executive_mrr: "admin_sales.reporting.read_all",
executive_arr: "admin_sales.reporting.read_all",
executive_churn: "admin_sales.reporting.read_all",
viewer_reports: "admin_sales.reporting.read",
super_platform: "admin_identity.roles.manage",
} as const satisfies Record<AdminDashboardWidgetId, AdminPermissionName>;
const WIDGET_SOURCE = {
sales_own_pipeline: "salesOwn",
sales_today: "salesOwn",
sales_appointments: "salesOwn",
sales_followups: "salesOwn",
sales_team_pipeline: "salesTeam",
sales_unassigned_leads: "salesTeam",
sales_team_activity: "salesTeam",
support_inbox: "support",
support_customer_events: "support",
engineering_health: "engineering",
engineering_queues: "engineering",
engineering_errors: "engineering",
engineering_deploy: "engineering",
executive_forecast: "executive",
executive_revenue: "executive",
executive_mrr: "executive",
executive_arr: "executive",
executive_churn: "executive",
viewer_reports: null,
super_platform: null,
} as const satisfies Record<
AdminDashboardWidgetId,
DashboardSource | null
>;
export function selectAdminDashboardWidgetIds(input: {
readonly roleKeys: readonly AdminRoleKey[];
readonly permissions: readonly AdminPermissionName[];
}): readonly AdminDashboardWidgetId[] {
const permissions = new Set(input.permissions);
const selected = new Set<AdminDashboardWidgetId>();
for (const roleKey of input.roleKeys) {
for (const widgetId of ROLE_WIDGETS[roleKey]) {
if (permissions.has(WIDGET_PERMISSION[widgetId])) {
selected.add(widgetId);
}
}
}
return [...selected];
}
export async function loadPersonalizedAdminDashboard(
input: {
readonly adminUserId: string;
readonly roleKeys: readonly AdminRoleKey[];
readonly permissions: readonly AdminPermissionName[];
readonly now?: Date;
readonly locale?: string;
},
sources: AdminDashboardDataSources = DEFAULT_SOURCES
): Promise<AdminDashboardVM> {
const selectedIds = selectAdminDashboardWidgetIds(input);
const selectedSet = new Set(selectedIds);
const sourceNames = new Set(
selectedIds
.map((widgetId) => WIDGET_SOURCE[widgetId])
.filter((source): source is DashboardSource => source !== null)
);
const now = input.now ?? new Date();
const locale = input.locale ?? "de";
const loaded = await Promise.all(
[...sourceNames].map((sourceName) =>
sources[sourceName]({ adminUserId: input.adminUserId, now, locale })
)
);
const loadedById = new Map(
loaded.flat().map((widget) => [widget.id, widget])
);
const widgets = selectedIds.flatMap((widgetId) => {
const loadedWidget = loadedById.get(widgetId);
if (loadedWidget) return [loadedWidget];
if (widgetId === "viewer_reports") {
return [
widget(
widgetId,
"admin.dashboard.personalized.readOnly",
adminPath("dashboard", { mode: "host-aware" })
),
];
}
if (widgetId === "super_platform") {
return [
widget(
widgetId,
"admin.dashboard.personalized.fullAccess",
adminPath("accounts", { mode: "host-aware" }),
"positive"
),
];
}
return [];
});
return buildAdminDashboardVM({
roles: input.roleKeys,
widgets: widgets.filter((entry) => selectedSet.has(entry.id)),
});
}
const DEFAULT_SOURCES: AdminDashboardDataSources = {
salesOwn: loadSalesOwnWidgets,
salesTeam: loadSalesTeamWidgets,
support: loadSupportWidgets,
engineering: loadEngineeringWidgets,
executive: loadExecutiveWidgets,
};
async function loadSalesOwnWidgets({
adminUserId,
now,
locale,
}: Parameters<DashboardSourceLoader>[0]) {
const endOfToday = new Date(now);
endOfToday.setHours(24, 0, 0, 0);
const nextThirtyDays = new Date(now);
nextThirtyDays.setDate(nextThirtyDays.getDate() + 30);
const dealScope = adminSalesDealReadWhere({
adminUserId,
canReadAll: false,
canWriteAll: false,
canReadAllCommunication: false,
});
const taskScope = adminSalesTaskReadWhere({
adminUserId,
canReadAll: false,
canWriteAll: false,
canReadAllCommunication: false,
});
const [pipeline, today, appointments, followups] = await Promise.all([
db.adminDeal.aggregate({
where: { ...dealScope, archivedAt: null, status: "open" },
_sum: { amountCents: true },
}),
db.adminTask.count({
where: {
...taskScope,
archivedAt: null,
status: "open",
dueAt: { lt: endOfToday },
},
}),
db.adminBooking.count({
where: {
adminUserId,
status: { in: ["reserved", "confirmed"] },
startsAt: { gte: now, lt: nextThirtyDays },
},
}),
db.adminTask.count({
where: {
...taskScope,
archivedAt: null,
status: "open",
reminderAt: { not: null },
},
}),
]);
return [
widget(
"sales_own_pipeline",
formatEuroCents(pipeline._sum.amountCents ?? 0, locale),
adminPath("sales/deals", { mode: "host-aware" })
),
widget(
"sales_today",
String(today),
adminPath("sales/tasks/today", { mode: "host-aware" }),
today > 0 ? "warning" : "positive"
),
widget(
"sales_appointments",
String(appointments),
adminPath("sales/bookings", { mode: "host-aware" })
),
widget(
"sales_followups",
String(followups),
adminPath("sales/tasks/today", { mode: "host-aware" })
),
];
}
async function loadSalesTeamWidgets({
now,
locale,
}: Parameters<DashboardSourceLoader>[0]) {
const activityStart = new Date(now);
activityStart.setDate(activityStart.getDate() - 7);
const [pipeline, unassignedLeads, activity] = await Promise.all([
db.adminDeal.aggregate({
where: { archivedAt: null, status: "open" },
_sum: { amountCents: true },
}),
db.adminLead.count({
where: {
archivedAt: null,
assignedToAdminUserId: null,
status: { in: ["new", "contacted", "qualified"] },
},
}),
db.adminActivity.count({
where: { occurredAt: { gte: activityStart } },
}),
]);
return [
widget(
"sales_team_pipeline",
formatEuroCents(pipeline._sum.amountCents ?? 0, locale),
adminPath("sales/deals", { mode: "host-aware" })
),
widget(
"sales_unassigned_leads",
String(unassignedLeads),
adminPath("leads", { mode: "host-aware" }),
unassignedLeads > 0 ? "warning" : "positive"
),
widget(
"sales_team_activity",
String(activity),
adminPath("sales/tasks/today", { mode: "host-aware" })
),
];
}
async function loadSupportWidgets({
now,
}: Parameters<DashboardSourceLoader>[0]) {
const eventStart = new Date(now);
eventStart.setDate(eventStart.getDate() - 1);
const [openTickets, customerEvents] = await Promise.all([
db.supportTicket.count({
where: { status: { in: ["open", "answered"] } },
}),
db.supportTicket.count({ where: { updatedAt: { gte: eventStart } } }),
]);
return [
widget(
"support_inbox",
String(openTickets),
adminPath("support", { mode: "host-aware" }),
openTickets > 0 ? "warning" : "positive"
),
widget(
"support_customer_events",
String(customerEvents),
adminPath("audit", { mode: "host-aware" })
),
];
}
async function loadEngineeringWidgets() {
try {
const snapshot = await getOperatorHealthSnapshot();
const issueCount = snapshot.subsystems.filter(
(subsystem) => subsystem.status !== "ok"
).length;
return [
widget(
"engineering_health",
issueCount === 0 ? "OK" : String(issueCount),
adminPath("system", { mode: "host-aware" }),
issueCount === 0 ? "positive" : "warning"
),
widget(
"engineering_queues",
String(snapshot.signals.failedJobsTotal),
adminPath("system/jobs", { mode: "host-aware" }),
snapshot.signals.failedJobsTotal > 0 ? "critical" : "positive"
),
widget(
"engineering_errors",
String(
snapshot.signals.webhookFailures +
snapshot.signals.billingErrors
),
adminPath("events", { mode: "host-aware" }),
snapshot.signals.webhookFailures + snapshot.signals.billingErrors > 0
? "critical"
: "positive"
),
widget(
"engineering_deploy",
snapshot.deploy.release,
adminPath("system/deploys", { mode: "host-aware" })
),
];
} catch {
return [
widget(
"engineering_health",
"admin.dashboard.personalized.unavailable",
adminPath("system", { mode: "host-aware" }),
"critical"
),
widget(
"engineering_queues",
"admin.dashboard.personalized.unavailable",
adminPath("system/jobs", { mode: "host-aware" }),
"critical"
),
widget(
"engineering_errors",
"admin.dashboard.personalized.unavailable",
adminPath("events", { mode: "host-aware" }),
"critical"
),
widget(
"engineering_deploy",
"admin.dashboard.personalized.unavailable",
adminPath("system/deploys", { mode: "host-aware" }),
"critical"
),
];
}
}
async function loadExecutiveWidgets({
now,
locale,
}: Parameters<DashboardSourceLoader>[0]) {
const yearStart = new Date(now.getFullYear(), 0, 1);
const tenants = await adminGetAllTenantsIdsAndNames();
const tenantIds = tenants.map((tenant) => tenant.id);
const [forecast, revenue, mrr, subscriptions] = await Promise.all([
db.adminDeal.aggregate({
where: { archivedAt: null, status: "open" },
_sum: { amountCents: true },
}),
db.adminDeal.aggregate({
where: { archivedAt: null, status: "won", wonAt: { gte: yearStart } },
_sum: { amountCents: true },
}),
getMrr("eur", tenantIds),
loadTenantSubscriptions(tenantIds),
]);
const churned = subscriptions.filter(
(subscription) =>
subscription?.cancelledAt !== null ||
subscription?.status === "cancelled"
).length;
const churnRate =
subscriptions.length === 0
? 0
: Math.round((churned / subscriptions.length) * 10_000) / 100;
return [
widget(
"executive_forecast",
formatEuroCents(forecast._sum.amountCents ?? 0, locale),
adminPath("sales/deals", { mode: "host-aware" })
),
widget(
"executive_revenue",
formatEuroCents(revenue._sum.amountCents ?? 0, locale),
adminPath("sales/deals", { mode: "host-aware" })
),
widget(
"executive_mrr",
formatEuroUnits(mrr.total, locale),
adminPath("dashboard", { mode: "host-aware" })
),
widget(
"executive_arr",
formatEuroUnits(mrr.total * 12, locale),
adminPath("dashboard", { mode: "host-aware" })
),
widget(
"executive_churn",
`${new Intl.NumberFormat(locale, {
maximumFractionDigits: 2,
}).format(churnRate)} %`,
adminPath("dashboard", { mode: "host-aware" }),
churnRate > 5 ? "warning" : "neutral"
),
];
}
async function loadTenantSubscriptions(tenantIds: readonly string[]) {
const subscriptions: Array<{
readonly status: string;
readonly cancelledAt: Date | null;
} | null> = [];
for (let index = 0; index < tenantIds.length; index += 10) {
const batch = tenantIds.slice(index, index + 10);
subscriptions.push(
...(await Promise.all(
batch.map((tenantId) =>
runWithRlsContext({ tenantId }, () =>
db.tenantSubscription.findUnique({
where: { tenantId },
select: { status: true, cancelledAt: true },
})
)
)
))
);
}
return subscriptions.filter(
(
subscription
): subscription is { readonly status: string; readonly cancelledAt: Date | null } =>
subscription !== null
);
}
function widget(
id: AdminDashboardWidgetId,
value: string,
href: string,
tone: AdminDashboardWidgetInput["tone"] = "neutral"
): AdminDashboardWidgetInput {
return { id, value, href, tone };
}
function formatEuroCents(value: number, locale: string) {
return formatEuroUnits(value / 100, locale);
}
function formatEuroUnits(value: number, locale: string) {
return new Intl.NumberFormat(locale, {
style: "currency",
currency: "EUR",
maximumFractionDigits: 0,
}).format(value);
}
@@ -0,0 +1,257 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import {
createAdminConnectionsService,
createPrismaAdminConnectionsRepository,
} from "@hivegrid/db/admin-connections.server";
import {
createAdminEmailComposeService,
createPrismaAdminEmailComposeRepository,
} from "@hivegrid/db/admin-email-compose.server";
import {
createPrismaAdminMailboxRepository,
} from "@hivegrid/db/admin-mailboxes.server";
import {
createAdminMailProviderGateway,
type AdminMailConnectionProvider,
type AdminOAuthCredentialBundle,
} from "@hivegrid/integrations";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export type AdminEmailOperatorContext = {
readonly adminUserId: string;
readonly email: string;
readonly locale: string | null;
readonly canReadAllCommunication: boolean;
readonly connections: ReturnType<typeof createAdminConnectionsService>;
readonly mailboxes: ReturnType<typeof createPrismaAdminMailboxRepository>;
readonly providers: ReturnType<typeof createAdminMailProviderGateway>;
readonly compose: ReturnType<typeof createAdminEmailComposeService>;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
};
export async function runAsAdminEmailOperator<T>(
request: Request,
permission:
| Extract<
AdminPermissionName,
| "admin_sales.email.connect"
| "admin_sales.email.send"
| "admin_sales.email.track"
| "admin_sales.email.bulk_send"
| "admin_sales.communication.read_all"
>
| readonly Extract<
AdminPermissionName,
| "admin_sales.email.connect"
| "admin_sales.email.send"
| "admin_sales.email.track"
| "admin_sales.email.bulk_send"
| "admin_sales.communication.read_all"
>[],
operation: (context: AdminEmailOperatorContext) => Promise<T>
): Promise<T> {
return runAsAdminIdentity(request, permission, async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true, locale: true },
});
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
const authorize = async (requested: AdminPermissionName) => {
if (!(await adminHasPermission(admin.id, requested, db))) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
};
const auditBase = {
adminUserId: admin.id,
email: admin.email,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
const canReadAllCommunication = await adminHasPermission(
admin.id,
"admin_sales.communication.read_all",
db
);
return operation({
adminUserId: admin.id,
email: admin.email,
locale: admin.locale,
canReadAllCommunication,
connections: createAdminConnectionsService({
repository: createPrismaAdminConnectionsRepository(db),
authorize,
}),
mailboxes: createPrismaAdminMailboxRepository(db),
providers: createAdminMailProviderGateway(),
compose: createAdminEmailComposeService({
repository: createPrismaAdminEmailComposeRepository(db),
authorize,
}),
actor: (reason) => ({ ...auditBase, reason }),
});
});
}
export async function completeAdminEmailConnection(input: {
readonly context: AdminEmailOperatorContext;
readonly provider: AdminMailConnectionProvider;
readonly code: string;
}) {
const grant = await input.context.providers.exchange(
input.provider,
input.code
);
const reason = "Persönliches Vertriebspostfach verbinden";
const actor = input.context.actor(reason);
const connection = await input.context.connections.connect({
adminUserId: input.context.adminUserId,
provider: input.provider,
capability: "email",
label: grant.account.displayName ?? grant.account.emailAddress,
externalAccountId: grant.account.externalAccountId,
externalAccountEmail: grant.account.emailAddress,
scopes: grant.credentials.scopes,
tokenExpiresAt: new Date(grant.credentials.expiresAt),
credentials: grant.credentials,
actor,
});
const mailbox = await input.context.mailboxes.activate({
adminUserId: input.context.adminUserId,
connectionId: connection.id,
provider: input.provider,
emailAddress: grant.account.emailAddress,
displayName: grant.account.displayName,
providerAccountId: grant.account.externalAccountId,
actor,
});
return { connectionId: connection.id, mailboxId: mailbox.id };
}
export async function listAdminEmailConnectionSettings(
context: AdminEmailOperatorContext
) {
const accounts = await db.adminMailbox.findMany({
where: {
adminUserId: context.adminUserId,
archivedAt: null,
},
orderBy: [{ normalizedEmail: "asc" }, { id: "asc" }],
select: {
id: true,
connectionId: true,
emailAddress: true,
displayName: true,
status: true,
lastSyncAt: true,
connection: {
select: {
provider: true,
healthMessageKey: true,
},
},
},
});
return accounts.map((account) => {
if (
account.connection.provider !== "google_mail" &&
account.connection.provider !== "microsoft_mail"
) {
throw new Error(
"admin.sales.email.connections.errors.invalidProvider"
);
}
return {
id: account.id,
connectionId: account.connectionId,
provider: account.connection.provider,
emailAddress: account.emailAddress,
displayName: account.displayName,
status: account.status,
lastSyncAt: account.lastSyncAt,
healthMessageKey: account.connection.healthMessageKey,
};
});
}
export async function refreshAdminEmailConnection(input: {
readonly context: AdminEmailOperatorContext;
readonly connectionId: string;
readonly provider: AdminMailConnectionProvider;
}) {
return input.context.connections.withCredentials(
input.connectionId,
input.context.adminUserId,
async (raw) => {
const current = credentialBundle(raw);
const refreshed = await input.context.providers.refresh(
input.provider,
current
);
return input.context.connections.refresh({
connectionId: input.connectionId,
adminUserId: input.context.adminUserId,
credentials: refreshed,
scopes: refreshed.scopes,
tokenExpiresAt: new Date(refreshed.expiresAt),
actor: input.context.actor("OAuth-Token erneuern"),
});
}
);
}
export async function disconnectAdminEmailConnection(input: {
readonly context: AdminEmailOperatorContext;
readonly connectionId: string;
readonly mailboxId: string;
readonly provider: AdminMailConnectionProvider;
}) {
await input.context.connections.disconnect({
connectionId: input.connectionId,
adminUserId: input.context.adminUserId,
actor: input.context.actor("Persönliches Vertriebspostfach trennen"),
revokeProviderCredentials: (raw) =>
input.context.providers.revoke(input.provider, credentialBundle(raw)),
});
return input.context.mailboxes.revoke({
adminUserId: input.context.adminUserId,
mailboxId: input.mailboxId,
actor: input.context.actor("Persönliches Vertriebspostfach trennen"),
});
}
function credentialBundle(
raw: Readonly<Record<string, unknown>>
): AdminOAuthCredentialBundle {
if (
typeof raw.accessToken !== "string" ||
typeof raw.refreshToken !== "string" ||
typeof raw.expiresAt !== "string" ||
!Array.isArray(raw.scopes) ||
raw.scopes.some((scope) => typeof scope !== "string")
) {
throw new Error("admin.sales.email.connections.errors.invalidCredential");
}
return {
accessToken: raw.accessToken,
refreshToken: raw.refreshToken,
expiresAt: raw.expiresAt,
scopes: raw.scopes as string[],
};
}
@@ -0,0 +1,94 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { config } = vi.hoisted(() => ({
config: {
nodeEnv: "test",
sessionSecret: "admin-email-oauth-state-secret-aaaaaaaa",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https" as const,
},
},
}));
vi.mock("@hivegrid/config", async () => {
const actual =
await vi.importActual<typeof import("@hivegrid/config")>(
"@hivegrid/config"
);
return {
...actual,
loadRequiredWebConfig: () => config,
};
});
import {
consumeAdminEmailOAuthState,
createAdminEmailOAuthState,
} from "./admin-email-oauth-state.server.js";
function requestWith(cookie: string) {
return new Request("https://admin.example.test/callback", {
headers: { cookie: cookie.split(";")[0] ?? "" },
});
}
beforeEach(() => {
config.nodeEnv = "test";
});
describe("admin email OAuth state", () => {
it("round-trips one owner/provider state and clears it", () => {
const created = createAdminEmailOAuthState({
adminUserId: "admin-1",
provider: "google_mail",
now: () => 1_000,
});
expect(
consumeAdminEmailOAuthState(requestWith(created.cookie), {
expectedState: created.state,
expectedProvider: "google_mail",
expectedAdminUserId: "admin-1",
now: () => 2_000,
})
).toMatchObject({
ok: true,
clearCookie: expect.stringContaining("Max-Age=0"),
});
});
it("rejects provider, owner and replay-age mismatches", () => {
const created = createAdminEmailOAuthState({
adminUserId: "admin-1",
provider: "google_mail",
now: () => 1_000,
});
expect(
consumeAdminEmailOAuthState(requestWith(created.cookie), {
expectedState: created.state,
expectedProvider: "microsoft_mail",
expectedAdminUserId: "admin-1",
now: () => 2_000,
})
).toMatchObject({ ok: false, reason: "mismatch" });
expect(
consumeAdminEmailOAuthState(requestWith(created.cookie), {
expectedState: created.state,
expectedProvider: "google_mail",
expectedAdminUserId: "admin-2",
now: () => 2_000,
})
).toMatchObject({ ok: false, reason: "mismatch" });
expect(
consumeAdminEmailOAuthState(requestWith(created.cookie), {
expectedState: created.state,
expectedProvider: "google_mail",
expectedAdminUserId: "admin-1",
now: () => 11 * 60 * 1_000,
})
).toMatchObject({ ok: false, reason: "expired" });
});
});
@@ -0,0 +1,161 @@
import {
createHmac,
randomBytes,
timingSafeEqual,
} from "node:crypto";
import {
loadRequiredWebConfig,
resolveHostOnlyCookiePolicy,
} from "@hivegrid/config";
import type { AdminMailConnectionProvider } from "@hivegrid/integrations";
const SECURE_COOKIE = "__Host-hivegrid_admin_mail_oauth";
const LOCAL_COOKIE = "hivegrid_admin_mail_oauth";
const TTL_MS = 10 * 60 * 1_000;
export type AdminEmailOAuthState = {
readonly state: string;
readonly adminUserId: string;
readonly provider: AdminMailConnectionProvider;
readonly createdAt: number;
};
export function createAdminEmailOAuthState(input: {
readonly adminUserId: string;
readonly provider: AdminMailConnectionProvider;
readonly now?: () => number;
readonly secret?: string;
}): { readonly state: string; readonly cookie: string } {
const payload: AdminEmailOAuthState = {
state: randomBytes(32).toString("hex"),
adminUserId: required(input.adminUserId),
provider: input.provider,
createdAt: input.now?.() ?? Date.now(),
};
const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString(
"base64url"
);
const signature = sign(encoded, resolveSecret(input.secret));
const policy = cookiePolicy();
return {
state: payload.state,
cookie: [
`${policy.name}=${encoded}.${signature}`,
`Path=${policy.path}`,
"HttpOnly",
"SameSite=Lax",
`Max-Age=${Math.ceil(TTL_MS / 1_000)}`,
...(policy.secure ? ["Secure"] : []),
].join("; "),
};
}
export function consumeAdminEmailOAuthState(
request: Request,
input: {
readonly expectedState: string;
readonly expectedProvider: AdminMailConnectionProvider;
readonly expectedAdminUserId: string;
readonly now?: () => number;
readonly secret?: string;
}
):
| {
readonly ok: true;
readonly clearCookie: string;
}
| {
readonly ok: false;
readonly reason:
| "missing"
| "malformed"
| "invalid_signature"
| "expired"
| "mismatch";
readonly clearCookie: string;
} {
const policy = cookiePolicy();
const clearCookie = [
`${policy.name}=`,
`Path=${policy.path}`,
"HttpOnly",
"SameSite=Lax",
"Max-Age=0",
...(policy.secure ? ["Secure"] : []),
].join("; ");
const value = readCookie(request, policy.name);
if (!value) return { ok: false, reason: "missing", clearCookie };
const [encoded, signature, ...rest] = value.split(".");
if (!encoded || !signature || rest.length > 0) {
return { ok: false, reason: "malformed", clearCookie };
}
const expectedSignature = sign(encoded, resolveSecret(input.secret));
const left = Buffer.from(signature);
const right = Buffer.from(expectedSignature);
if (left.length !== right.length || !timingSafeEqual(left, right)) {
return { ok: false, reason: "invalid_signature", clearCookie };
}
let payload: AdminEmailOAuthState;
try {
payload = JSON.parse(
Buffer.from(encoded, "base64url").toString("utf8")
) as AdminEmailOAuthState;
} catch {
return { ok: false, reason: "malformed", clearCookie };
}
const now = input.now?.() ?? Date.now();
if (
!Number.isFinite(payload.createdAt) ||
payload.createdAt > now + 60_000 ||
now - payload.createdAt > TTL_MS
) {
return { ok: false, reason: "expired", clearCookie };
}
if (
payload.state !== input.expectedState ||
payload.provider !== input.expectedProvider ||
payload.adminUserId !== input.expectedAdminUserId
) {
return { ok: false, reason: "mismatch", clearCookie };
}
return { ok: true, clearCookie };
}
function resolveSecret(override?: string): string {
const secret = override ?? loadRequiredWebConfig().sessionSecret;
if (!secret || Buffer.byteLength(secret, "utf8") < 32) {
throw new Error("SESSION_SECRET is required for admin mail OAuth state.");
}
return secret;
}
function cookiePolicy() {
const config = loadRequiredWebConfig();
return resolveHostOnlyCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
secureName: SECURE_COOKIE,
localName: LOCAL_COOKIE,
maxAge: Math.ceil(TTL_MS / 1_000),
});
}
function sign(value: string, secret: string): string {
return createHmac("sha256", secret).update(value).digest("base64url");
}
function readCookie(request: Request, name: string): string | null {
for (const segment of request.headers.get("cookie")?.split(/;\s*/) ?? []) {
const separator = segment.indexOf("=");
if (separator > 0 && segment.slice(0, separator) === name) {
return segment.slice(separator + 1);
}
}
return null;
}
function required(value: string): string {
const normalized = value.trim();
if (!normalized) throw new Error("adminUserId is required");
return normalized;
}
@@ -0,0 +1,140 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
threadList: vi.fn(),
threadDetail: vi.fn(),
contacts: vi.fn(),
deals: vi.fn(),
policy: vi.fn(),
scheduled: vi.fn(),
bulkRuns: vi.fn(),
reminders: vi.fn(),
mailboxes: vi.fn(),
audit: vi.fn(),
}));
vi.mock("@hivegrid/db/admin-sales-core.server", () => ({
writeAdminSalesAudit: mocks.audit,
}));
vi.mock("~/utils/db.server", () => ({
db: {
adminEmailThread: {
findMany: mocks.threadList,
findFirst: mocks.threadDetail,
},
adminContact: { findMany: mocks.contacts },
adminDeal: { findMany: mocks.deals },
adminEmailOutboundPolicy: { findUnique: mocks.policy },
adminScheduledEmail: { findMany: mocks.scheduled },
adminBulkEmailRun: { findMany: mocks.bulkRuns },
adminNoReplyReminder: { findMany: mocks.reminders },
adminMailbox: { findMany: mocks.mailboxes },
},
}));
import {
readAdminEmailInbox,
readAdminEmailScheduled,
} from "./admin-email-workspace.server";
describe("admin email team scope", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.threadList.mockResolvedValue([]);
mocks.contacts.mockResolvedValue([]);
mocks.deals.mockResolvedValue([]);
mocks.policy.mockResolvedValue(null);
mocks.scheduled.mockResolvedValue([]);
mocks.bulkRuns.mockResolvedValue([]);
mocks.reminders.mockResolvedValue([]);
mocks.mailboxes.mockResolvedValue([]);
mocks.threadDetail.mockResolvedValue({
id: "thread-b",
adminUserId: "sales-b",
normalizedSubject: "Team-Anfrage",
messages: [],
});
});
it("reads a selected team thread only with read-all and audits actor, owner and target", async () => {
const actor = vi.fn((reason: string) => ({
adminUserId: "manager",
email: "manager@example.test",
reason,
}));
await readAdminEmailInbox(
{
adminUserId: "manager",
canReadAllCommunication: true,
actor,
} as never,
"thread-b"
);
expect(mocks.threadList).toHaveBeenCalledWith(
expect.objectContaining({ where: { archivedAt: null } })
);
expect(mocks.threadDetail).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "thread-b", archivedAt: null },
})
);
expect(mocks.audit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "admin.sales.email.foreignThread.read",
targetType: "AdminEmailThread",
targetId: "thread-b",
after: {
dataOwnerAdminUserId: "sales-b",
accessKind: "read",
},
})
);
});
it("audits every foreign scheduled communication target exposed to the manager", async () => {
mocks.scheduled.mockResolvedValue([
{
id: "scheduled-b",
adminUserId: "sales-b",
subject: "Follow-up",
toAddresses: ["buyer@example.test"],
scheduledFor: new Date("2026-07-26T10:00:00.000Z"),
status: "queued",
noReplyAfterDays: null,
lastErrorMessageKey: null,
},
]);
await readAdminEmailScheduled({
adminUserId: "manager",
canReadAllCommunication: true,
actor: (reason: string) => ({
adminUserId: "manager",
email: "manager@example.test",
reason,
}),
} as never);
expect(mocks.audit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "admin.sales.email.foreignScheduled.read",
targetType: "AdminScheduledEmail",
targetId: "scheduled-b",
after: {
foreignTargets: [
{
targetType: "AdminScheduledEmail",
targetId: "scheduled-b",
dataOwnerAdminUserId: "sales-b",
},
],
accessKind: "read",
},
})
);
});
});
@@ -0,0 +1,582 @@
import { saveAdminSendingDomain } from "@hivegrid/db/admin-email-domain.server";
import { renderAdminBulkEmailTemplate } from "@hivegrid/db/admin-email-compose.server";
import { assignAdminEmailMessage } from "@hivegrid/db/admin-email-sync.server";
import { writeAdminSalesAudit } from "@hivegrid/db/admin-sales-core.server";
import type { AdminEmailOperatorContext } from "./admin-email-connections.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { db } from "~/utils/db.server";
export function adminEmailWorkspaceHrefs() {
return {
inbox: adminPath("sales/email/inbox", { mode: "host-aware" }),
templates: adminPath("sales/email/templates", { mode: "host-aware" }),
scheduled: adminPath("sales/email/scheduled", { mode: "host-aware" }),
accounts: adminPath("sales/settings/email-accounts", {
mode: "host-aware",
}),
domains: adminPath("sales/settings/sending-domains", {
mode: "host-aware",
}),
};
}
export async function readAdminEmailInbox(context: AdminEmailOperatorContext, selectedThreadId?: string | null) {
const ownerWhere = context.canReadAllCommunication
? {}
: { adminUserId: context.adminUserId };
const [threads, contacts, deals] = await Promise.all([
db.adminEmailThread.findMany({
where: { ...ownerWhere, archivedAt: null },
orderBy: [{ latestMessageAt: "desc" }, { id: "asc" }],
take: 100,
include: {
messages: {
orderBy: [{ sentAt: "desc" }, { id: "desc" }],
take: 1,
include: {
matchedContact: {
select: { firstName: true, lastName: true },
},
matchedDeal: { select: { title: true } },
events: { select: { type: true } },
attachments: { select: { id: true } },
},
},
},
}),
db.adminContact.findMany({
where: { archivedAt: null },
orderBy: [{ lastName: "asc" }, { firstName: "asc" }, { id: "asc" }],
take: 250,
select: { id: true, firstName: true, lastName: true, email: true },
}),
db.adminDeal.findMany({
where: { archivedAt: null },
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
take: 250,
select: { id: true, title: true },
}),
]);
const foreignThreads = threads.filter(
(thread) => thread.adminUserId !== context.adminUserId
);
if (foreignThreads.length > 0) {
await writeAdminSalesAudit(db, {
actor: context.actor("Fremde Team-Postfächer aufgelistet"),
action: "admin.sales.email.foreignThreads.read",
targetType: "AdminEmailThread",
targetId: foreignThreads[0]!.id,
after: {
foreignTargets: foreignThreads.map((thread) => ({
targetId: thread.id,
dataOwnerAdminUserId: thread.adminUserId,
})),
accessKind: "read",
},
});
}
const selected = selectedThreadId
? await db.adminEmailThread.findFirst({
where: {
id: selectedThreadId,
...ownerWhere,
archivedAt: null,
},
include: {
messages: {
orderBy: [{ sentAt: "asc" }, { id: "asc" }],
include: {
events: { select: { type: true } },
attachments: {
select: { id: true, filename: true, sizeBytes: true },
},
},
},
},
})
: null;
if (selected && selected.adminUserId !== context.adminUserId) {
await writeAdminSalesAudit(db, {
actor: context.actor("Fremdes Team-Postfach geöffnet"),
action: "admin.sales.email.foreignThread.read",
targetType: "AdminEmailThread",
targetId: selected.id,
after: {
dataOwnerAdminUserId: selected.adminUserId,
accessKind: "read",
},
});
}
const rows = threads.map((thread) => {
const latest = thread.messages[0];
return {
id: thread.id,
subject: thread.normalizedSubject ?? latest?.subject ?? "",
latestMessageAt: thread.latestMessageAt.toISOString(),
messageCount: thread.messageCount,
unreadCount: thread.unreadCount,
matchStatus: latest?.matchStatus ?? ("unmatched" as const),
preview: latest?.snippet ?? latest?.bodyText ?? "",
fromAddress: latest?.fromAddress ?? "",
contactLabel: latest?.matchedContact ? `${latest.matchedContact.firstName} ${latest.matchedContact.lastName}`.trim() : null,
dealLabel: latest?.matchedDeal?.title ?? null,
eventTypes: latest?.events.map((event) => event.type) ?? [],
attachmentCount: latest?.attachments.length ?? 0,
};
});
return {
stats: {
threads: rows.length,
unread: rows.reduce((sum, row) => sum + row.unreadCount, 0),
assignmentQueue: rows.filter((row) => row.matchStatus === "ambiguous" || row.matchStatus === "unmatched").length,
},
threads: rows,
selectedThread: selected
? {
id: selected.id,
subject: selected.normalizedSubject ?? "",
messages: selected.messages.map((message) => ({
id: message.id,
direction: message.direction,
fromAddress: message.fromAddress,
sentAt: message.sentAt.toISOString(),
bodyText: message.bodyText ?? message.snippet ?? "",
eventTypes: message.events.map((event) => event.type),
attachments: message.attachments.map((attachment) => ({
...attachment,
downloadHref: adminPath(
`sales/email/attachments/${encodeURIComponent(attachment.id)}`,
{ mode: "host-aware" }
),
})),
})),
}
: null,
assignmentOptions: {
contacts: contacts.map((contact) => ({
id: contact.id,
label: `${contact.firstName} ${contact.lastName}`.trim(),
email: contact.email,
})),
deals: deals.map((deal) => ({ id: deal.id, label: deal.title })),
},
};
}
export async function readAdminEmailTemplates(context: AdminEmailOperatorContext) {
const [templates, snippets, signature] = await Promise.all([
db.adminEmailTemplate.findMany({
where: { adminUserId: context.adminUserId, archivedAt: null },
orderBy: [{ name: "asc" }, { version: "desc" }],
}),
db.adminEmailSnippet.findMany({
where: { adminUserId: context.adminUserId, archivedAt: null },
orderBy: [{ title: "asc" }, { id: "asc" }],
}),
db.adminEmailSignature.findUnique({
where: { adminUserId: context.adminUserId },
}),
]);
return {
templates: templates.map((template) => ({
id: template.id,
name: template.name,
subjectTemplate: template.subjectTemplate,
htmlTemplate: template.htmlTemplate,
allowedPlaceholders: template.allowedPlaceholders,
version: template.version,
updatedAt: template.updatedAt.toISOString(),
})),
snippets: snippets.map((snippet) => ({
id: snippet.id,
shortcut: snippet.shortcut,
title: snippet.title,
content: snippet.content,
})),
signature: signature ? { html: signature.html, text: signature.text } : null,
};
}
export async function readAdminEmailScheduled(context: AdminEmailOperatorContext) {
const ownerWhere = context.canReadAllCommunication
? {}
: { adminUserId: context.adminUserId };
const [policy, scheduled, bulkRuns, reminders, mailboxes, contacts] = await Promise.all([
db.adminEmailOutboundPolicy.findUnique({
where: { adminUserId: context.adminUserId },
}),
db.adminScheduledEmail.findMany({
where: ownerWhere,
orderBy: [{ scheduledFor: "desc" }, { id: "asc" }],
take: 100,
}),
db.adminBulkEmailRun.findMany({
where: ownerWhere,
orderBy: [{ createdAt: "desc" }, { id: "asc" }],
take: 50,
}),
db.adminNoReplyReminder.findMany({
where: ownerWhere,
orderBy: [{ dueAt: "desc" }, { id: "asc" }],
take: 50,
include: {
outboundMessage: { select: { subject: true } },
},
}),
db.adminMailbox.findMany({
where: {
...ownerWhere,
archivedAt: null,
status: "active",
},
orderBy: [{ normalizedEmail: "asc" }, { id: "asc" }],
select: { id: true, emailAddress: true, displayName: true },
}),
db.adminContact.findMany({
where: { archivedAt: null, email: { not: null } },
orderBy: [{ lastName: "asc" }, { firstName: "asc" }, { id: "asc" }],
take: 250,
select: { id: true, firstName: true, lastName: true, email: true },
}),
]);
const foreignScheduledTargets = [
...scheduled
.filter((row) => row.adminUserId !== context.adminUserId)
.map((row) => ({
targetType: "AdminScheduledEmail",
targetId: row.id,
dataOwnerAdminUserId: row.adminUserId,
})),
...bulkRuns
.filter((row) => row.adminUserId !== context.adminUserId)
.map((row) => ({
targetType: "AdminBulkEmailRun",
targetId: row.id,
dataOwnerAdminUserId: row.adminUserId,
})),
...reminders
.filter((row) => row.adminUserId !== context.adminUserId)
.map((row) => ({
targetType: "AdminNoReplyReminder",
targetId: row.id,
dataOwnerAdminUserId: row.adminUserId,
})),
];
if (foreignScheduledTargets.length > 0) {
await writeAdminSalesAudit(db, {
actor: context.actor("Fremde geplante Team-Kommunikation aufgelistet"),
action: "admin.sales.email.foreignScheduled.read",
targetType: foreignScheduledTargets[0]!.targetType,
targetId: foreignScheduledTargets[0]!.targetId,
after: {
foreignTargets: foreignScheduledTargets,
accessKind: "read",
},
});
}
return {
outboundLocked: !policy?.configuredAt || !policy.consentRulesConfigured || policy.allowedWeekDays.length === 0,
policy: policy
? {
timeZone: policy.timeZone,
workdayStartMinutes: policy.workdayStartMinutes,
workdayEndMinutes: policy.workdayEndMinutes,
allowedWeekDays: policy.allowedWeekDays,
dailySendLimit: policy.dailySendLimit,
bulkDailySendLimit: policy.bulkDailySendLimit,
consentRulesConfigured: policy.consentRulesConfigured,
trackingEnabled: policy.trackingEnabled,
liveOpenEnabled: policy.liveOpenEnabled,
trackingRetentionDays: policy.trackingRetentionDays,
}
: null,
scheduled: scheduled.map((item) => ({
id: item.id,
subject: item.subject,
recipients: item.toAddresses,
scheduledFor: item.scheduledFor.toISOString(),
status: item.status,
noReplyAfterDays: item.noReplyAfterDays,
errorMessageKey: item.lastErrorMessageKey,
})),
bulkRuns: bulkRuns.map((run) => ({
id: run.id,
name: run.name,
status: run.status,
scheduledFor: run.scheduledFor?.toISOString() ?? null,
recipientCount: run.recipientCount,
sentCount: run.sentCount,
failedCount: run.failedCount,
})),
reminders: reminders.map((reminder) => ({
id: reminder.id,
dueAt: reminder.dueAt.toISOString(),
status: reminder.status,
subject: reminder.outboundMessage.subject ?? "",
taskId: reminder.taskId,
})),
mailboxes,
contacts: contacts.flatMap((contact) =>
contact.email
? [
{
id: contact.id,
label: `${contact.firstName} ${contact.lastName}`.trim(),
email: contact.email,
},
]
: []
),
};
}
export async function readAdminEmailDomains(context: AdminEmailOperatorContext) {
const [domains, bccAddresses, policy] = await Promise.all([
db.adminSendingDomain.findMany({
where: { adminUserId: context.adminUserId, archivedAt: null },
orderBy: [{ domain: "asc" }, { id: "asc" }],
}),
db.adminBccAddress.findMany({
where: { adminUserId: context.adminUserId, archivedAt: null },
orderBy: [{ createdAt: "desc" }, { id: "asc" }],
include: {
mailbox: { select: { emailAddress: true, displayName: true } },
},
}),
db.adminEmailOutboundPolicy.findUnique({
where: { adminUserId: context.adminUserId },
}),
]);
return {
domains: domains.map((domain) => ({
id: domain.id,
domain: domain.domain,
status: domain.status,
spfStatus: domain.spfStatus,
dkimStatus: domain.dkimStatus,
spfRecordName: domain.spfRecordName,
spfExpectedValue: domain.spfExpectedValue,
dkimRecordName: domain.dkimRecordName,
dkimExpectedValue: domain.dkimExpectedValue,
lastCheckedAt: domain.lastCheckedAt?.toISOString() ?? null,
})),
bccAddresses: bccAddresses.map((address) => ({
id: address.id,
mailboxId: address.mailboxId,
mailboxLabel: address.mailbox.displayName ?? address.mailbox.emailAddress,
displayAddress: address.displayAddress,
rotatedAt: address.rotatedAt?.toISOString() ?? null,
})),
tracking: {
enabled: policy?.trackingEnabled ?? false,
liveOpenEnabled: policy?.liveOpenEnabled ?? false,
retentionDays: policy?.trackingRetentionDays ?? 180,
},
};
}
export async function applyAdminEmailWorkspaceAction(
context: AdminEmailOperatorContext,
input:
| {
readonly intent: "assign-message";
readonly messageId: string;
readonly contactId: string | null;
readonly dealId: string | null;
}
| {
readonly intent: "queue-email";
readonly mailboxId: string;
readonly contactId: string | null;
readonly dealId: string | null;
readonly toAddress: string;
readonly subject: string;
readonly body: string;
readonly scheduledFor: string;
readonly timeZone: string;
readonly noReplyAfterDays: number | null;
readonly idempotencyKey: string;
}
| {
readonly intent: "queue-bulk-email";
readonly mailboxId: string;
readonly name: string;
readonly contactIds: readonly string[];
readonly subjectTemplate: string;
readonly bodyTemplate: string;
readonly scheduledFor: string;
readonly timeZone: string;
readonly noReplyAfterDays: number | null;
readonly idempotencyKey: string;
}
| {
readonly intent: "save-template";
readonly name: string;
readonly subjectTemplate: string;
readonly htmlTemplate: string;
readonly allowedPlaceholders: readonly string[];
}
| {
readonly intent: "save-snippet";
readonly shortcut: string;
readonly title: string;
readonly content: string;
}
| {
readonly intent: "save-signature";
readonly html: string;
readonly text: string | null;
}
| {
readonly intent: "save-policy";
readonly timeZone: string;
readonly workdayStartMinutes: number;
readonly workdayEndMinutes: number;
readonly allowedWeekDays: readonly number[];
readonly dailySendLimit: number;
readonly bulkDailySendLimit: number;
readonly consentRulesConfigured: boolean;
readonly trackingEnabled: boolean;
readonly liveOpenEnabled: boolean;
}
| {
readonly intent: "save-domain";
readonly domain: string;
readonly spfRecordName: string;
readonly spfExpectedValue: string;
readonly dkimRecordName: string;
readonly dkimExpectedValue: string;
}
) {
const actor = context.actor(actionReason(input.intent));
if (input.intent === "assign-message") {
return assignAdminEmailMessage(db, {
adminUserId: context.adminUserId,
messageId: input.messageId,
contactId: input.contactId,
dealId: input.dealId,
actor,
});
}
if (input.intent === "queue-email") {
return context.compose.queue({
adminUserId: context.adminUserId,
mailboxId: input.mailboxId,
contactId: input.contactId,
dealId: input.dealId,
toAddresses: [input.toAddress],
subject: input.subject,
bodyHtml: `<p>${escapeHtml(input.body).replaceAll("\n", "<br />")}</p>`,
bodyText: input.body,
scheduledFor: new Date(input.scheduledFor),
timeZone: input.timeZone,
noReplyAfterDays: input.noReplyAfterDays,
idempotencyKey: input.idempotencyKey,
actor,
});
}
if (input.intent === "queue-bulk-email") {
const contacts = await db.adminContact.findMany({
where: {
id: { in: [...new Set(input.contactIds)] },
archivedAt: null,
email: { not: null },
},
orderBy: { id: "asc" },
select: { id: true, firstName: true, lastName: true, email: true },
});
if (contacts.length !== new Set(input.contactIds).size) {
throw new Error("admin_email_bulk_contact_invalid");
}
return context.compose.queueBulk({
adminUserId: context.adminUserId,
mailboxId: input.mailboxId,
name: input.name,
scheduledFor: new Date(input.scheduledFor),
timeZone: input.timeZone,
idempotencyKey: input.idempotencyKey,
recipients: contacts.map((contact) => {
const values = {
first_name: contact.firstName,
last_name: contact.lastName,
full_name: `${contact.firstName} ${contact.lastName}`.trim(),
email: contact.email!,
};
const subject = renderAdminBulkEmailTemplate(input.subjectTemplate, values);
const body = renderAdminBulkEmailTemplate(input.bodyTemplate, values);
return {
contactId: contact.id,
toAddress: contact.email!,
subject,
bodyHtml: `<p>${escapeHtml(body).replaceAll("\n", "<br />")}</p>`,
bodyText: body,
noReplyAfterDays: input.noReplyAfterDays,
};
}),
actor,
});
}
if (input.intent === "save-template") {
return context.compose.saveTemplate({
adminUserId: context.adminUserId,
name: input.name,
subjectTemplate: input.subjectTemplate,
htmlTemplate: `<p>${escapeHtml(input.htmlTemplate).replaceAll("\n", "<br />")}</p>`,
textTemplate: null,
allowedPlaceholders: input.allowedPlaceholders,
actor,
});
}
if (input.intent === "save-snippet") {
return context.compose.saveSnippet({
adminUserId: context.adminUserId,
shortcut: input.shortcut,
title: input.title,
content: input.content,
actor,
});
}
if (input.intent === "save-signature") {
return context.compose.saveSignature({
adminUserId: context.adminUserId,
html: `<p>${escapeHtml(input.text ?? input.html).replaceAll("\n", "<br />")}</p>`,
text: input.text,
actor,
});
}
if (input.intent === "save-policy") {
return context.compose.savePolicy({
adminUserId: context.adminUserId,
...input,
actor,
});
}
return saveAdminSendingDomain(db, {
adminUserId: context.adminUserId,
domain: input.domain,
spfRecordName: input.spfRecordName,
spfExpectedValue: input.spfExpectedValue,
dkimRecordName: input.dkimRecordName,
dkimExpectedValue: input.dkimExpectedValue,
actor,
});
}
function actionReason(intent: string) {
const reasons: Record<string, string> = {
"assign-message": "E-Mail einem Sales-Vorgang zuordnen",
"queue-email": "E-Mail im Sales Workspace planen",
"queue-bulk-email": "Personalisierte Serienmail planen",
"save-template": "E-Mail-Vorlage speichern",
"save-snippet": "E-Mail-Textbaustein speichern",
"save-signature": "Persönliche E-Mail-Signatur speichern",
"save-policy": "Outbound-Regeln konfigurieren",
"save-domain": "Sende-Domain konfigurieren",
};
return reasons[intent] ?? "E-Mail-Einstellung ändern";
}
function escapeHtml(value: string) {
return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#039;");
}
@@ -0,0 +1,45 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
import { getUserInfo, getValidatedServerSession } from "~/utils/session.server";
export type AdminPermissionRequirement =
| AdminPermissionName
| readonly AdminPermissionName[];
export async function requireAdminIdentityPermission(
request: Request,
permission: AdminPermissionRequirement
) {
const userInfo = await getUserInfo(request);
if (!userInfo.userId) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
const session = await getValidatedServerSession(request, userInfo);
if (!session || !("adminUser" in session) || session.adminUserId !== userInfo.userId) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
const permissions = Array.isArray(permission) ? permission : [permission];
const allowed = await runWithRlsContext(
{ userId: session.adminUserId },
async () =>
(
await Promise.all(
permissions.map((candidate) =>
adminHasPermission(session.adminUserId, candidate)
)
)
).some(Boolean)
);
if (!allowed) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
return session;
}
export async function runAsAdminIdentity<T>(
request: Request,
permission: AdminPermissionRequirement,
operation: (session: Awaited<ReturnType<typeof requireAdminIdentityPermission>>) => Promise<T>
): Promise<T> {
const session = await requireAdminIdentityPermission(request, permission);
return runWithRlsContext({ userId: session.adminUserId }, () => operation(session));
}
@@ -0,0 +1,315 @@
import type {
AdminPermissionName,
AdminRoleKey,
} from "@hivegrid/db/admin-permissions";
import {
ADMIN_ROLE_DEFINITIONS,
permissionsForAdminRoles,
} from "@hivegrid/db/admin-permissions";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AdminSidebar } from "~/application/sidebar/AdminSidebar";
import { getSidebarCommandActions } from "~/services/command-registry/commandRegistry";
import { filterCommandActions } from "~/services/search/commandSearch";
import {
ADMIN_AREA_ACCESS,
ADMIN_ROUTE_ACCESS,
} from "./admin-access-contract";
import type { AdminDashboardDataSources } from "./admin-dashboard-personalization.server";
import { loadPersonalizedAdminDashboard } from "./admin-dashboard-personalization.server";
const authMocks = vi.hoisted(() => ({
adminHasPermission: vi.fn(),
getUserInfo: vi.fn(),
getValidatedServerSession: vi.fn(),
runWithRlsContext: vi.fn(
async (
_context: unknown,
operation: () => Promise<unknown> | unknown
) => operation()
),
}));
vi.mock("@hivegrid/db/admin-rbac.server", () => ({
adminHasPermission: authMocks.adminHasPermission,
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: authMocks.runWithRlsContext,
}));
vi.mock("~/utils/session.server", () => ({
getUserInfo: authMocks.getUserInfo,
getValidatedServerSession: authMocks.getValidatedServerSession,
}));
import { requireAdminIdentityPermission } from "./admin-identity.server";
const t = vi.fn((key: string) => key) as never;
const sources = {
salesOwn: vi.fn(async () => [
{ id: "sales_own_pipeline" as const, value: "10 €", href: "/sales/deals" },
{ id: "sales_today" as const, value: "2", href: "/sales/tasks/today" },
{ id: "sales_appointments" as const, value: "1", href: "/sales/bookings" },
{ id: "sales_followups" as const, value: "3", href: "/sales/tasks/today" },
]),
salesTeam: vi.fn(async () => [
{ id: "sales_team_pipeline" as const, value: "20 €", href: "/sales/deals" },
{ id: "sales_unassigned_leads" as const, value: "4", href: "/leads" },
{ id: "sales_team_activity" as const, value: "5", href: "/sales/tasks/today" },
]),
support: vi.fn(async () => [
{ id: "support_inbox" as const, value: "6", href: "/support" },
{ id: "support_customer_events" as const, value: "7", href: "/audit" },
]),
engineering: vi.fn(async () => [
{ id: "engineering_health" as const, value: "OK", href: "/system" },
{ id: "engineering_queues" as const, value: "0", href: "/system/jobs" },
{ id: "engineering_errors" as const, value: "0", href: "/events" },
{ id: "engineering_deploy" as const, value: "abc123", href: "/system/deploys" },
]),
executive: vi.fn(async () => [
{ id: "executive_forecast" as const, value: "1 €", href: "/sales/deals" },
{ id: "executive_revenue" as const, value: "2 €", href: "/sales/deals" },
{ id: "executive_mrr" as const, value: "3 €", href: "/dashboard" },
{ id: "executive_arr" as const, value: "36 €", href: "/dashboard" },
{ id: "executive_churn" as const, value: "0 %", href: "/dashboard" },
]),
} satisfies AdminDashboardDataSources;
const PERSONAS = [
{
role: "super_admin",
widgets: ["super_platform"],
allowedCommands: ["/dashboard", "/support", "/system", "/system/jobs", "/system/deploys"],
deniedCommands: [],
},
{
role: "sales",
widgets: [
"sales_own_pipeline",
"sales_today",
"sales_appointments",
"sales_followups",
],
allowedCommands: ["/dashboard", "/sales/deals"],
deniedCommands: ["/support", "/system", "/system/deploys"],
},
{
role: "sales_manager",
widgets: [
"sales_team_pipeline",
"sales_unassigned_leads",
"sales_team_activity",
],
allowedCommands: ["/dashboard", "/sales/deals"],
deniedCommands: ["/support", "/system", "/system/deploys"],
},
{
role: "support",
widgets: ["support_inbox", "support_customer_events"],
allowedCommands: ["/dashboard", "/support"],
deniedCommands: ["/system", "/system/deploys", "/sales/deals"],
},
{
role: "engineering",
widgets: [
"engineering_health",
"engineering_queues",
"engineering_errors",
"engineering_deploy",
],
allowedCommands: ["/dashboard", "/system", "/system/jobs", "/system/deploys"],
deniedCommands: ["/support", "/sales/deals"],
},
{
role: "executive",
widgets: [
"executive_forecast",
"executive_revenue",
"executive_mrr",
"executive_arr",
"executive_churn",
],
allowedCommands: ["/dashboard", "/sales/deals"],
deniedCommands: ["/support", "/system", "/system/deploys"],
},
{
role: "viewer",
widgets: ["viewer_reports"],
allowedCommands: ["/dashboard"],
deniedCommands: ["/support", "/system", "/system/deploys", "/sales/deals"],
},
] as const satisfies readonly {
role: AdminRoleKey;
widgets: readonly string[];
allowedCommands: readonly string[];
deniedCommands: readonly string[];
}[];
function permissionsFor(roleKeys: readonly AdminRoleKey[]) {
return [...permissionsForAdminRoles(roleKeys)];
}
function commandIdsFor(permissions: readonly AdminPermissionName[]) {
const actions = getSidebarCommandActions(
AdminSidebar({
t,
appConfiguration: {
app: { features: { tenantApiKeys: true } },
} as never,
}),
"admin"
);
return new Set(
filterCommandActions({
actions,
query: "",
layout: "admin",
appData: {
isSuperAdmin: false,
permissions,
user: { admin: true },
} as never,
rootData: { user: { admin: true } } as never,
}).map((action) => action.id)
);
}
describe("admin personas end to end", () => {
beforeEach(() => {
vi.clearAllMocks();
authMocks.getUserInfo.mockResolvedValue({ userId: "admin_persona" });
authMocks.getValidatedServerSession.mockResolvedValue({
adminUser: { id: "admin_persona" },
adminUserId: "admin_persona",
});
});
it.each(PERSONAS)(
"loads and exposes only the $role persona contract",
async ({ role, widgets, allowedCommands, deniedCommands }) => {
const permissions = permissionsFor([role]);
const vm = await loadPersonalizedAdminDashboard(
{
adminUserId: `admin_${role}`,
roleKeys: [role],
permissions,
},
sources
);
const commandIds = commandIdsFor(permissions);
expect(vm.widgets.map((widget) => widget.id)).toEqual(widgets);
expect(new Set(vm.widgets.map((widget) => widget.id)).size).toBe(
vm.widgets.length
);
for (const path of allowedCommands) {
expect(commandIds.has(path), `${role} should see ${path}`).toBe(true);
}
for (const path of deniedCommands) {
expect(commandIds.has(path), `${role} must not see ${path}`).toBe(false);
}
}
);
it.each(PERSONAS)(
"returns 404 for every denied $role direct-route permission",
async ({ role }) => {
const permissions = new Set(permissionsFor([role]));
authMocks.adminHasPermission.mockImplementation(
async (_adminUserId: string, permission: AdminPermissionName) =>
permissions.has(permission)
);
for (const route of ADMIN_ROUTE_ACCESS) {
const access = requireAdminIdentityPermission(
new Request(`https://admin.example.test${route.path}`),
route.permission
);
if (permissions.has(route.permission)) {
await expect(access, `${role} should open ${route.path}`).resolves.toMatchObject({
adminUserId: "admin_persona",
});
} else {
await expect(access, `${role} must 404 ${route.path}`).rejects.toMatchObject({
status: 404,
});
}
}
}
);
it("unions combined roles across permissions, widgets and navigation", async () => {
const roleKeys = ["sales", "engineering"] as const;
const permissions = permissionsFor(roleKeys);
const vm = await loadPersonalizedAdminDashboard(
{
adminUserId: "admin_combined",
roleKeys,
permissions,
},
sources
);
const commandIds = commandIdsFor(permissions);
expect(vm.widgets.map((widget) => widget.id)).toEqual([
"sales_own_pipeline",
"sales_today",
"sales_appointments",
"sales_followups",
"engineering_health",
"engineering_queues",
"engineering_errors",
"engineering_deploy",
]);
expect(new Set(vm.widgets.map((widget) => widget.id)).size).toBe(
vm.widgets.length
);
for (const path of [
"/dashboard",
"/sales/deals",
"/system",
"/system/jobs",
"/system/deploys",
]) {
expect(commandIds.has(path), `combined role should see ${path}`).toBe(
true
);
}
expect(commandIds.has("/support")).toBe(false);
expect(sources.salesOwn).toHaveBeenCalledOnce();
expect(sources.engineering).toHaveBeenCalledOnce();
expect(sources.support).not.toHaveBeenCalled();
expect(sources.executive).not.toHaveBeenCalled();
});
it("keeps the own/all and read-only persona boundaries explicit", () => {
const sales = permissionsForAdminRoles(["sales"]);
const manager = permissionsForAdminRoles(["sales_manager"]);
const support = permissionsForAdminRoles(["support"]);
const engineering = permissionsForAdminRoles(["engineering"]);
const executive = permissionsForAdminRoles(["executive"]);
expect(sales.has("admin_sales.crm.read")).toBe(true);
expect(sales.has("admin_sales.crm.read_all")).toBe(false);
expect(manager.has("admin_sales.crm.read_all")).toBe(true);
expect(manager.has("admin_sales.communication.read_all")).toBe(true);
expect(support.has(ADMIN_AREA_ACCESS.deploys)).toBe(false);
expect(engineering.has(ADMIN_AREA_ACCESS.deploys)).toBe(true);
expect(executive.has("admin_sales.reporting.read_all")).toBe(true);
expect(executive.has("admin_sales.communication.read_all")).toBe(false);
expect(
[...executive].some((permission) => permission.includes(".write"))
).toBe(false);
});
it("covers every fixed role exactly once", () => {
const covered = PERSONAS.map((persona) => persona.role);
expect(new Set(covered)).toEqual(
new Set(ADMIN_ROLE_DEFINITIONS.map((role) => role.key))
);
expect(covered).toHaveLength(ADMIN_ROLE_DEFINITIONS.length);
});
});
@@ -0,0 +1,176 @@
import { createHash } from "node:crypto";
import {
createAdminBookingLifecycleService,
createPrismaAdminBookingLifecycleRepository,
type AdminBookingManageProof,
} from "@hivegrid/db/admin-booking-lifecycle.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
import {
hashAdminBookingManageNonce,
type AdminBookingManageClaims,
} from "./admin-booking-manage-token.server";
import {
loadAdminPublicBookingPage,
submitAdminPublicBooking,
} from "./admin-public-booking.server";
export async function loadAdminManagedBooking(input: {
readonly claims: AdminBookingManageClaims;
readonly date: string;
}) {
return runWithRlsContext({ userId: input.claims.adminUserId }, async () => {
const booking = await readManagedBooking(input.claims);
if (!booking) return null;
const page = await loadAdminPublicBookingPage({
slug: booking.bookingPage.slug,
date: input.date,
});
return page ? { booking, page } : null;
});
}
export async function cancelAdminManagedBooking(input: {
readonly claims: AdminBookingManageClaims;
readonly reason: string;
readonly now?: Date;
}) {
const now = input.now ?? new Date();
return runWithRlsContext({ userId: input.claims.adminUserId }, async () => {
const booking = await readManagedBooking(input.claims, now);
if (!booking) throw new AdminPublicBookingManageError("booking_unavailable");
return lifecycle().cancelPublic({
bookingId: booking.id,
reason: input.reason,
actor: publicActor(input.claims.adminUserId),
manageProof: proof(input.claims, now),
});
});
}
export async function rescheduleAdminManagedBooking(input: {
readonly claims: AdminBookingManageClaims;
readonly date: string;
readonly startsAt: Date;
readonly endsAt: Date;
readonly now?: Date;
}) {
const now = input.now ?? new Date();
return runWithRlsContext({ userId: input.claims.adminUserId }, async () => {
const previous = await readManagedBooking(input.claims, now);
const participant = previous?.participants[0];
if (!previous || !participant) {
throw new AdminPublicBookingManageError("booking_unavailable");
}
const replacement = await submitAdminPublicBooking(
{
slug: previous.bookingPage.slug,
date: input.date,
startsAt: input.startsAt,
endsAt: input.endsAt,
firstName: previous.contact.firstName,
lastName: previous.contact.lastName,
email: participant.email,
timeZone: previous.bookerTimeZone,
locale: participant.locale ?? "de",
answers: toAnswers(previous.intakeAnswers),
submissionId: rescheduleSubmissionId(
input.claims.nonce,
input.startsAt
),
manualHostAdminUserId: previous.adminUserId,
dealId: previous.dealId,
reschedule: {
claims: input.claims,
nonceHash: hashAdminBookingManageNonce(
input.claims.nonce
),
},
},
now
);
return replacement;
});
}
async function readManagedBooking(
claims: AdminBookingManageClaims,
now = new Date()
) {
return db.adminBooking.findFirst({
where: {
id: claims.bookingId,
adminUserId: claims.adminUserId,
manageTokenVersion: claims.version,
manageTokenExpiresAt: { gt: now },
status: {
in: ["reserved", "confirmed", "provider_sync_failed"],
},
},
include: {
bookingPage: { select: { slug: true, title: true } },
meetingType: { select: { name: true, durationMinutes: true } },
contact: { select: { firstName: true, lastName: true } },
participants: {
where: { isOrganizer: false },
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
take: 1,
select: { email: true, locale: true },
},
},
});
}
function lifecycle() {
return createAdminBookingLifecycleService({
repository: createPrismaAdminBookingLifecycleRepository(db),
authorize: () => undefined,
});
}
function proof(
claims: AdminBookingManageClaims,
now: Date
): AdminBookingManageProof {
return {
version: claims.version,
nonceHash: hashAdminBookingManageNonce(claims.nonce),
now,
};
}
function publicActor(adminUserId: string) {
return {
adminUserId,
reason: "Öffentliche Terminverwaltung",
};
}
function toAnswers(value: unknown): Readonly<Record<string, string>> {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return Object.fromEntries(
Object.entries(value).filter(
(entry): entry is [string, string] => typeof entry[1] === "string"
)
);
}
function rescheduleSubmissionId(nonce: string, startsAt: Date): string {
return createHash("sha256")
.update("admin-booking-reschedule")
.update("\0")
.update(nonce)
.update("\0")
.update(startsAt.toISOString())
.digest("hex");
}
export class AdminPublicBookingManageError extends Error {
constructor(readonly code: string) {
super(code);
this.name = "AdminPublicBookingManageError";
}
}
@@ -0,0 +1,25 @@
import { describe, expect, it } from "vitest";
import { isAdminPublicBookingHost } from "./admin-public-booking.server";
describe("admin public booking boundary", () => {
it("accepts only the dedicated meeting host", () => {
expect(
isAdminPublicBookingHost(
new Request("http://meet.localhost:3000/erstgespraech")
)
).toBe(true);
expect(
isAdminPublicBookingHost(
new Request("http://admin.localhost:3000/erstgespraech")
)
).toBe(false);
expect(
isAdminPublicBookingHost(
new Request("http://attacker.invalid/erstgespraech", {
headers: { "x-forwarded-host": "meet.localhost:3000" },
})
)
).toBe(false);
});
});
@@ -0,0 +1,393 @@
import { createHmac } from "node:crypto";
import { hostMatches } from "@hivegrid/config";
import {
computeAdminBookingSlots,
type AdminAnonymousBusyInterval,
type AdminBookingHostAvailability,
} from "@hivegrid/db/admin-booking-availability";
import {
AdminBookingError,
createAdminBookingService,
createPrismaAdminBookingRepository,
type ReservedAdminBooking,
} from "@hivegrid/db/admin-booking.server";
import { resolveAdminBookingPageRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { createFixedWindowRateLimiter } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
import { getAdminBookingHost } from "~/utils/app/HostRouting.server";
import { db } from "~/utils/db.server";
import { createScopedLogger } from "~/utils/logger.server";
import { getTrustedClientIp } from "~/utils/server/IpUtils";
import type { AdminBookingManageClaims } from "./admin-booking-manage-token.server";
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/u;
const bookingLogger = createScopedLogger("admin-public-booking");
export type AdminPublicBookingQuestion = {
readonly id: string;
readonly label: string;
readonly required: boolean;
readonly type: "text" | "textarea" | "select";
readonly options: readonly string[];
};
export type AdminPublicBookingPage = {
readonly pageId: string;
readonly ownerAdminUserId: string;
readonly slug: string;
readonly title: string;
readonly description: string | null;
readonly meetingTypeName: string;
readonly durationMinutes: number;
readonly questions: readonly AdminPublicBookingQuestion[];
readonly date: string;
readonly slots: readonly {
readonly startsAt: Date;
readonly endsAt: Date;
readonly availableHostAdminUserIds: readonly string[];
}[];
};
export type SubmitAdminPublicBookingInput = {
readonly slug: string;
readonly date: string;
readonly startsAt: Date;
readonly endsAt: Date;
readonly firstName: string;
readonly lastName: string;
readonly email: string;
readonly timeZone: string;
readonly locale?: string | null;
readonly answers: Readonly<Record<string, string>>;
readonly submissionId: string;
readonly manualHostAdminUserId?: string | null;
readonly dealId?: string | null;
readonly reschedule?: {
readonly claims: AdminBookingManageClaims;
readonly nonceHash: string;
};
};
export async function loadAdminPublicBookingPage(input: {
readonly slug: string;
readonly date: string;
readonly now?: Date;
}): Promise<AdminPublicBookingPage | null> {
if (!ISO_DATE.test(input.date)) return null;
const identity = await resolveAdminBookingPageRlsIdentity(input.slug, db);
if (!identity) return null;
const page = await runWithRlsContext({ userId: identity.userId }, () =>
db.adminBookingPage.findFirst({
where: {
id: identity.resourceId,
createdByAdminUserId: identity.userId,
published: true,
archivedAt: null,
meetingType: { active: true, archivedAt: null },
},
include: { meetingType: true },
})
);
if (!page) return null;
const now = input.now ?? new Date();
const hosts = await Promise.all(
page.meetingType.hostAdminUserIds.map((adminUserId) =>
readHostAvailability({
adminUserId,
date: input.date,
now,
horizonDays: page.meetingType.bookingHorizonDays,
})
)
);
const slots = computeAdminBookingSlots({
date: input.date,
now,
hosts,
config: {
durationMinutes: page.meetingType.durationMinutes,
bufferBeforeMinutes: page.meetingType.bufferBeforeMinutes,
bufferAfterMinutes: page.meetingType.bufferAfterMinutes,
slotIncrementMinutes: page.meetingType.slotIncrementMinutes,
minimumNoticeMinutes: page.meetingType.minimumNoticeMinutes,
bookingHorizonDays: page.meetingType.bookingHorizonDays,
},
});
return {
pageId: page.id,
ownerAdminUserId: identity.userId,
slug: page.slug,
title: page.title,
description: page.description,
meetingTypeName: page.meetingType.name,
durationMinutes: page.meetingType.durationMinutes,
questions: parseQuestions(page.meetingType.intakeQuestions),
date: input.date,
slots,
};
}
export async function submitAdminPublicBooking(
input: SubmitAdminPublicBookingInput,
now: Date = new Date()
): Promise<ReservedAdminBooking> {
const page = await loadAdminPublicBookingPage({
slug: input.slug,
date: input.date,
now,
});
if (!page) throw new AdminBookingError("page_unavailable");
const slot = page.slots.find(
(candidate) =>
candidate.startsAt.getTime() === input.startsAt.getTime() &&
candidate.endsAt.getTime() === input.endsAt.getTime()
);
if (!slot) throw new AdminBookingError("slot_taken");
const allowedQuestionIds = new Set(
page.questions.map((question) => question.id)
);
if (
Object.keys(input.answers).some((id) => !allowedQuestionIds.has(id)) ||
page.questions.some(
(question) =>
question.required && !input.answers[question.id]?.trim()
)
) {
throw new AdminBookingError("invalid_answers");
}
const identity = {
resourceId: page.pageId,
userId: page.ownerAdminUserId,
};
return runWithRlsContext({ userId: identity.userId }, () =>
createAdminBookingService({
repository: createPrismaAdminBookingRepository(db, { now: () => now }),
}).reserve({
bookingPageId: identity.resourceId,
startsAt: input.startsAt,
endsAt: input.endsAt,
bookerTimeZone: input.timeZone,
bookerFirstName: input.firstName,
bookerLastName: input.lastName,
bookerEmail: input.email,
bookerLocale: input.locale,
intakeAnswers: input.answers,
availableHostAdminUserIds: slot.availableHostAdminUserIds,
manualHostAdminUserId: input.manualHostAdminUserId,
dealId: input.dealId,
idempotencyKey: `public-booking:${identity.resourceId}:${input.submissionId}`,
manageTokenExpiresAt: new Date(
Math.max(input.startsAt.getTime(), now.getTime()) + 30 * 86_400_000
),
...(input.reschedule
? {
reschedule: {
previousBookingId: input.reschedule.claims.bookingId,
manageTokenVersion: input.reschedule.claims.version,
manageTokenExpiresAfter: now,
manageNonceHash: input.reschedule.nonceHash,
},
}
: {}),
})
);
}
export async function checkAdminPublicBookingRateLimit(input: {
readonly request: Request;
readonly slug: string;
readonly email: string;
readonly secret: string;
}): Promise<{ readonly allowed: boolean; readonly retryAfterSeconds: number }> {
const retryAfterSeconds = 900;
try {
if (input.secret.length < 32) throw new Error("invalid secret");
const client = getTrustedClientIp(input.request) || "unknown";
const key = createHmac("sha256", input.secret)
.update(
`admin-booking-v1\0${input.slug.trim().toLowerCase()}\0${client}\0${input.email.trim().toLowerCase()}`
)
.digest("hex");
const decision = await createFixedWindowRateLimiter({
store: getSharedStore(),
prefix: "admin-booking-v1-submit",
windowSeconds: retryAfterSeconds,
max: 8,
}).consume(key);
return { allowed: decision.allowed, retryAfterSeconds };
} catch (error) {
bookingLogger.error(
{
event: "admin_booking.rate_limit_unavailable",
errorName: error instanceof Error ? error.name : "UnknownError",
},
"Admin booking rate limit unavailable; request denied"
);
return { allowed: false, retryAfterSeconds };
}
}
export function isAdminPublicBookingHost(request: Request): boolean {
const url = new URL(request.url);
const actualHost = request.headers.get("host") ?? url.host;
return hostMatches(actualHost, getAdminBookingHost());
}
async function readHostAvailability(input: {
readonly adminUserId: string;
readonly date: string;
readonly now: Date;
readonly horizonDays: number;
}): Promise<AdminBookingHostAvailability> {
return runWithRlsContext({ userId: input.adminUserId }, async () => {
const date = new Date(`${input.date}T00:00:00.000Z`);
const rangeEnd = new Date(
date.getTime() + Math.max(1, input.horizonDays) * 86_400_000
);
const [eligibleUser, rules, overrides, cursors, bookings] =
await Promise.all([
db.adminUser.findFirst({
where: {
id: input.adminUserId,
status: "active",
roles: {
some: {
role: {
active: true,
permissions: {
some: {
permission: {
name: "admin_sales.booking.manage",
},
},
},
},
},
},
},
select: { id: true },
}),
db.adminAvailabilityRule.findMany({
where: { adminUserId: input.adminUserId, archivedAt: null },
}),
db.adminAvailabilityOverride.findMany({
where: {
adminUserId: input.adminUserId,
archivedAt: null,
date,
},
}),
db.adminCalendarSyncCursor.findMany({
where: {
adminUserId: input.adminUserId,
status: "active",
calendarConnection: {
status: "active",
archivedAt: null,
},
},
select: { busyIntervals: true },
}),
db.adminBooking.findMany({
where: {
adminUserId: input.adminUserId,
status: { in: ["reserved", "confirmed"] },
startsAt: { lt: rangeEnd },
endsAt: { gt: date },
},
select: { startsAt: true, endsAt: true },
}),
]);
const absent = overrides.some(
(override) => override.kind === "unavailable"
);
return {
adminUserId: input.adminUserId,
eligible: Boolean(eligibleUser),
absent,
rules: rules.map((rule) => ({
dayOfWeek: rule.dayOfWeek,
startMinutes: rule.startMinutes,
endMinutes: rule.endMinutes,
timeZone: rule.timeZone,
})),
overrides: overrides.map((override) => ({
date: input.date,
kind: override.kind,
startMinutes: override.startMinutes,
endMinutes: override.endMinutes,
timeZone: override.timeZone,
})),
busyIntervals: [
...cursors.flatMap((cursor) =>
parseBusyIntervals(cursor.busyIntervals)
),
...bookings,
],
};
});
}
function parseBusyIntervals(value: unknown): AdminAnonymousBusyInterval[] {
if (!Array.isArray(value)) return [];
return value.flatMap((item) => {
if (!item || typeof item !== "object") return [];
const startsAt = new Date(
"startsAt" in item && typeof item.startsAt === "string"
? item.startsAt
: Number.NaN
);
const endsAt = new Date(
"endsAt" in item && typeof item.endsAt === "string"
? item.endsAt
: Number.NaN
);
return Number.isFinite(startsAt.getTime()) &&
Number.isFinite(endsAt.getTime()) &&
endsAt > startsAt
? [{ startsAt, endsAt }]
: [];
});
}
function parseQuestions(value: unknown): AdminPublicBookingQuestion[] {
if (!Array.isArray(value)) return [];
return value.flatMap((item) => {
if (
!item ||
typeof item !== "object" ||
!("id" in item) ||
typeof item.id !== "string" ||
!("label" in item) ||
typeof item.label !== "string"
) {
return [];
}
const type =
"type" in item &&
(item.type === "textarea" || item.type === "select")
? item.type
: "text";
return [
{
id: item.id,
label: item.label,
required: "required" in item && item.required === true,
type,
options:
"options" in item && Array.isArray(item.options)
? item.options.filter(
(option: unknown): option is string =>
typeof option === "string"
)
: [],
},
];
});
}
@@ -0,0 +1,223 @@
import {
adminSalesBulkContactsActionSchema,
adminSalesCustomFieldActionSchema,
adminSalesExportActionSchema,
adminSalesImportConfirmActionSchema,
adminSalesTagActionSchema,
buildAdminSalesDataManagementVM,
type AdminSalesImportPreviewVM,
} from "@hivegrid/view-models";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { getTranslations } from "~/locale/i18next.server";
import {
confirmAdminSalesContactsImport,
prepareAdminSalesContactsImport,
requestAdminSalesContactsExport,
runAsAdminSalesDataOperator,
} from "~/services/admin/admin-sales-data.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { validateCSRFToken } from "~/utils/session.server";
export type AdminSalesDataActionData = {
readonly success?: string;
readonly error?: string;
readonly preview?: AdminSalesImportPreviewVM;
};
export async function loadAdminSalesDataRoute({
request,
}: LoaderFunctionArgs) {
return runAsAdminSalesDataOperator(
request,
"admin_sales.crm.read",
async ({ service, canWrite, canExport }) => ({
vm: buildAdminSalesDataManagementVM({
source: await service.listWorkspace(),
buildContactHref: (contactId) =>
adminPath(`sales/contacts/${encodeURIComponent(contactId)}`, {
mode: "host-aware",
}),
buildCompanyHref: (companyId) =>
adminPath(`sales/companies/${encodeURIComponent(companyId)}`, {
mode: "host-aware",
}),
buildImportErrorHref: (jobId) =>
adminPath(
`sales/data-jobs/${encodeURIComponent(jobId)}/download?kind=import-error`,
{ mode: "host-aware" }
),
buildExportHref: (jobId) =>
adminPath(
`sales/data-jobs/${encodeURIComponent(jobId)}/download?kind=export`,
{ mode: "host-aware" }
),
permissions: { canRead: true, canWrite, canExport },
}),
})
);
}
export async function mutateAdminSalesDataRoute({
request,
}: ActionFunctionArgs) {
const { t } = await getTranslations(request);
await validateCSRFToken(request);
const form = await request.formData();
const intent = String(form.get("intent") ?? "");
try {
if (intent === "preview-import") {
const file = form.get("file");
if (!(file instanceof File)) throw new Error("INVALID_FILE");
return runAsAdminSalesDataOperator(
request,
"admin_sales.crm.write",
async (context) => {
const prepared = await prepareAdminSalesContactsImport({
file,
reason: t("admin.sales.data.audit.importPrepared"),
context,
});
return Response.json({
preview: {
jobId: prepared.job.id,
fileName: prepared.job.fileName,
rowCount: prepared.preview.rowCount,
headers: [...prepared.preview.headers],
mapping: [...prepared.preview.suggestedMapping],
},
} satisfies AdminSalesDataActionData);
}
);
}
if (intent === "confirm-import") {
const command = adminSalesImportConfirmActionSchema.parse({
importJobId: form.get("importJobId"),
reason: form.get("reason"),
});
await runAsAdminSalesDataOperator(
request,
"admin_sales.crm.write",
(context) =>
confirmAdminSalesContactsImport({
importJobId: command.importJobId,
reason: command.reason,
context,
})
);
return Response.json({
success: t("admin.sales.data.feedback.importQueued"),
} satisfies AdminSalesDataActionData);
}
if (intent === "create-tag") {
const command = adminSalesTagActionSchema.parse({
name: form.get("name"),
color: nullableString(form.get("color")),
reason: form.get("reason"),
});
await runAsAdminSalesDataOperator(
request,
"admin_sales.crm.write",
({ service, actor }) => {
const { reason, ...data } = command;
return service.createTag({ ...data, actor: actor(reason) });
}
);
return Response.json({
success: t("admin.sales.data.feedback.tagCreated"),
} satisfies AdminSalesDataActionData);
}
if (intent === "create-field") {
const command = adminSalesCustomFieldActionSchema.parse({
target: form.get("target"),
key: form.get("key"),
label: form.get("label"),
type: form.get("type"),
options: parseStringArray(form.get("options")),
required: form.get("required") === "true",
position: Number(form.get("position")),
reason: form.get("reason"),
});
await runAsAdminSalesDataOperator(
request,
"admin_sales.crm.write",
({ service, actor }) => {
const { reason, ...data } = command;
return service.createCustomField({
...data,
actor: actor(reason),
});
}
);
return Response.json({
success: t("admin.sales.data.feedback.fieldCreated"),
} satisfies AdminSalesDataActionData);
}
if (intent === "bulk-update") {
const localeWasProvided = form.get("localeChanged") === "true";
const command = adminSalesBulkContactsActionSchema.parse({
contactIds: parseStringArray(form.get("contactIds")),
locale: nullableString(form.get("locale")),
addTagIds: parseStringArray(form.get("addTagIds")),
removeTagIds: [],
reason: form.get("reason"),
});
await runAsAdminSalesDataOperator(
request,
"admin_sales.crm.write",
({ service, actor }) =>
service.bulkUpdateContacts({
contactIds: command.contactIds,
...(localeWasProvided ? { locale: command.locale } : {}),
addTagIds: command.addTagIds,
removeTagIds: command.removeTagIds,
actor: actor(command.reason),
})
);
return Response.json({
success: t("admin.sales.data.feedback.contactsUpdated"),
} satisfies AdminSalesDataActionData);
}
if (intent === "export") {
const command = adminSalesExportActionSchema.parse({
contactIds: parseStringArray(form.get("contactIds")),
reason: form.get("reason"),
});
await runAsAdminSalesDataOperator(
request,
"admin_sales.crm.export",
(context) =>
requestAdminSalesContactsExport({
contactIds: command.contactIds,
reason: command.reason,
context,
})
);
return Response.json({
success: t("admin.sales.data.feedback.exportQueued"),
} satisfies AdminSalesDataActionData);
}
throw new Error("INVALID_INTENT");
} catch {
return Response.json(
{ error: t("admin.sales.data.errors.actionFailed") } satisfies AdminSalesDataActionData,
{ status: 400 }
);
}
}
function parseStringArray(value: FormDataEntryValue | null): string[] {
if (typeof value !== "string") return [];
const parsed: unknown = JSON.parse(value);
if (
!Array.isArray(parsed) ||
parsed.some((entry) => typeof entry !== "string")
) {
throw new Error("INVALID_ARRAY");
}
return parsed;
}
function nullableString(value: FormDataEntryValue | null): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
@@ -0,0 +1,182 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
import {
confirmAdminSalesContactsImport,
prepareAdminSalesContactsImport,
requestAdminSalesContactsExport,
type AdminSalesDataOperatorContext,
} from "./admin-sales-data.server";
function context() {
return {
adminUserId: "admin_1",
email: "sales@hivegrid.de",
canWrite: true,
canExport: true,
actor: (reason: string) => ({
adminUserId: "admin_1",
email: "sales@hivegrid.de",
reason,
requestId: "request_1",
ip: null,
userAgent: null,
}),
service: {
createImportJob: vi.fn(async (input) => ({
id: "import_1",
fileName: input.fileName,
sourceBucket: input.sourceBucket,
sourceKey: input.sourceKey,
sourceHeaders: input.sourceHeaders,
fieldMapping: input.fieldMapping,
requestedByAdminUserId: "admin_1",
})),
getImportJobForQueue: vi.fn(async () => ({
id: "import_1",
requestedByAdminUserId: "admin_1",
})),
markImportJobQueued: vi.fn(async () => ({ id: "import_1" })),
createExportJob: vi.fn(async () => ({
id: "export_1",
requestedByAdminUserId: "admin_1",
})),
markExportJobQueued: vi.fn(async () => ({ id: "export_1" })),
},
};
}
describe("admin sales data web service", () => {
it("scans and stores CSV bytes before creating a pending preview job", async () => {
const operator = context();
const store = vi.fn(async () => "stored");
const remove = vi.fn(async () => undefined);
const result = await prepareAdminSalesContactsImport(
{
file: new File(
["Vorname,Nachname,E-Mail\nAda,Lovelace,ada@example.com\n"],
"kontakte.csv",
{ type: "text/csv" }
),
reason: "Kontaktimport prüfen",
context: operator as unknown as AdminSalesDataOperatorContext,
},
{
bucket: () => "hivegrid-files",
store,
remove,
id: () => "upload_1",
}
);
expect(store).toHaveBeenCalledWith(
expect.objectContaining({
bucket: "hivegrid-files",
id: "admin-sales/imports/admin_1/upload_1.csv",
throwOnFailure: true,
scan: expect.objectContaining({
context: "formUpload",
requireMalwareScan: true,
filename: "kontakte.csv",
}),
})
);
expect(operator.service.createImportJob).toHaveBeenCalledWith(
expect.objectContaining({
sourceHeaders: ["Vorname", "Nachname", "E-Mail"],
fieldMapping: [
"Vorname=firstName",
"Nachname=lastName",
"E-Mail=email",
],
})
);
expect(result.preview.rowCount).toBe(1);
expect(remove).not.toHaveBeenCalled();
});
it("removes the scanned object if pending-job persistence fails", async () => {
const operator = context();
operator.service.createImportJob.mockRejectedValueOnce(
new Error("database unavailable")
);
const remove = vi.fn(async () => undefined);
await expect(
prepareAdminSalesContactsImport(
{
file: new File(
["Vorname,Nachname\nAda,Lovelace\n"],
"kontakte.csv"
),
reason: "Kontaktimport prüfen",
context: operator as unknown as AdminSalesDataOperatorContext,
},
{
bucket: () => "hivegrid-files",
store: vi.fn(async () => "stored"),
remove,
id: () => "upload_1",
}
)
).rejects.toThrow("database unavailable");
expect(remove).toHaveBeenCalledWith({
bucket: "hivegrid-files",
key: "admin-sales/imports/admin_1/upload_1.csv",
});
});
it("queues only an owned reviewed import and marks it queued afterward", async () => {
const operator = context();
const add = vi.fn(async () => ({ id: "queue_1" }));
await confirmAdminSalesContactsImport({
importJobId: "import_1",
reason: "Geprüften Import starten",
context: operator as unknown as AdminSalesDataOperatorContext,
createQueue: async () => ({ add } as never),
});
expect(operator.service.getImportJobForQueue).toHaveBeenCalledWith(
expect.objectContaining({ jobId: "import_1" })
);
expect(add).toHaveBeenCalledWith(
"run-import",
expect.objectContaining({
kind: "admin-sales.contacts-import",
importJobId: "import_1",
}),
expect.objectContaining({ priority: 1 })
);
expect(
operator.service.markImportJobQueued.mock.invocationCallOrder[0]
).toBeGreaterThan(add.mock.invocationCallOrder[0]!);
});
it("uses the same worker queue for bounded contact exports", async () => {
const operator = context();
const add = vi.fn(async () => ({ id: "queue_1" }));
await requestAdminSalesContactsExport({
contactIds: ["contact_1"],
reason: "Kontakte exportieren",
requestId: "export_request_1",
context: operator as unknown as AdminSalesDataOperatorContext,
createQueue: async () => ({ add } as never),
});
expect(operator.service.createExportJob).toHaveBeenCalledWith(
expect.objectContaining({
selectedContactIds: ["contact_1"],
idempotencyKey:
"admin-sales-export:admin_1:export_request_1",
})
);
expect(add).toHaveBeenCalledWith(
"run-import",
expect.objectContaining({
kind: "admin-sales.contacts-export",
exportJobId: "export_1",
}),
expect.any(Object)
);
expect(
operator.service.markExportJobQueued.mock.invocationCallOrder[0]
).toBeGreaterThan(add.mock.invocationCallOrder[0]!);
});
});
@@ -0,0 +1,292 @@
import { randomUUID } from "node:crypto";
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import {
createAdminSalesDataService,
createPrismaAdminSalesDataRepository,
previewAdminSalesContactsCsv,
} from "@hivegrid/db/admin-sales-data.server";
import {
buildAdminSalesContactsExportJob,
buildAdminSalesContactsImportJob,
enqueueJob,
queueNames,
resolveRedisConnectionOptionsFromProcessEnv,
type TypedQueue,
} from "@hivegrid/queue";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
import {
deleteFile,
resolveStorageBucket,
storeFile,
} from "~/utils/integrations/storageService";
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
const MAX_IMPORT_BYTES = 5 * 1024 * 1024;
type AdminSalesDataPermission = Extract<
AdminPermissionName,
| "admin_sales.crm.read"
| "admin_sales.crm.write"
| "admin_sales.crm.export"
>;
type ImportQueue = TypedQueue<typeof queueNames.imports>;
export type AdminSalesDataOperatorContext = {
readonly adminUserId: string;
readonly email: string;
readonly canWrite: boolean;
readonly canExport: boolean;
readonly service: ReturnType<typeof createAdminSalesDataService>;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
};
export async function runAsAdminSalesDataOperator<T>(
request: Request,
permission: AdminSalesDataPermission,
operation: (context: AdminSalesDataOperatorContext) => Promise<T>
): Promise<T> {
return runAsAdminIdentity(request, permission, async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true },
});
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
const authorize = async (requestedPermission: AdminPermissionName) => {
if (!(await adminHasPermission(admin.id, requestedPermission, db))) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
};
const [canWrite, canExport] = await Promise.all([
adminHasPermission(admin.id, "admin_sales.crm.write", db),
adminHasPermission(admin.id, "admin_sales.crm.export", db),
]);
const auditBase = {
adminUserId: admin.id,
email: admin.email,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
return operation({
adminUserId: admin.id,
email: admin.email,
canWrite,
canExport,
service: createAdminSalesDataService({
repository: createPrismaAdminSalesDataRepository(db),
authorize,
}),
actor: (reason) => ({ ...auditBase, reason }),
});
});
}
export async function prepareAdminSalesContactsImport(
input: {
readonly file: File;
readonly reason: string;
readonly context: AdminSalesDataOperatorContext;
},
dependencies: {
readonly bucket?: () => string;
readonly store?: typeof storeFile;
readonly remove?: typeof deleteFile;
readonly id?: () => string;
} = {}
) {
const fileName = input.file.name.trim();
if (!fileName.toLocaleLowerCase("en").endsWith(".csv")) {
throw new Error("Admin sales contact import requires a CSV file.");
}
if (input.file.size <= 0 || input.file.size > MAX_IMPORT_BYTES) {
throw new Error("Admin sales contact import exceeds the 5 MB limit.");
}
const bytes = new Uint8Array(await input.file.arrayBuffer());
if (bytes.byteLength > MAX_IMPORT_BYTES) {
throw new Error("Admin sales contact import exceeds the 5 MB limit.");
}
const csvText = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
const preview = previewAdminSalesContactsCsv(csvText);
if (
!preview.suggestedMapping.some((entry) => entry.endsWith("=firstName")) ||
!preview.suggestedMapping.some((entry) => entry.endsWith("=lastName"))
) {
throw new Error(
"Admin sales contact import requires recognizable first and last name columns."
);
}
const bucket = (dependencies.bucket ?? resolveStorageBucket)();
const storageKey = `admin-sales/imports/${input.context.adminUserId}/${(dependencies.id ?? randomUUID)()}.csv`;
const store = dependencies.store ?? storeFile;
const remove = dependencies.remove ?? deleteFile;
await store({
bucket,
id: storageKey,
content: `data:text/csv;base64,${Buffer.from(bytes).toString("base64")}`,
throwOnFailure: true,
scan: {
context: "formUpload",
declaredMimeType: "text/csv",
filename: fileName,
requireMalwareScan: true,
},
});
try {
const job = await input.context.service.createImportJob({
fileName,
sourceBucket: bucket,
sourceKey: storageKey,
sourceHeaders: preview.headers,
fieldMapping: preview.suggestedMapping,
idempotencyKey: `admin-sales-import:${input.context.adminUserId}:${storageKey}`,
actor: input.context.actor(input.reason),
});
return { job, preview };
} catch (error) {
await remove({ bucket, key: storageKey }).catch(() => undefined);
throw error;
}
}
export async function confirmAdminSalesContactsImport(input: {
readonly importJobId: string;
readonly reason: string;
readonly context: AdminSalesDataOperatorContext;
readonly createQueue?: () => Promise<ImportQueue | undefined>;
}) {
const actor = input.context.actor(input.reason);
const job = await input.context.service.getImportJobForQueue({
jobId: input.importJobId,
actor,
});
if (!job) throw new Error("Admin sales import job was not found.");
const queue = await (input.createQueue ?? createAdminSalesDataQueue)();
if (!queue) {
throw new Error("Admin sales import queue is not available.");
}
const descriptor = buildAdminSalesContactsImportJob({
importJobId: job.id,
requestedByAdminUserId: job.requestedByAdminUserId,
requestId: actor.requestId ?? undefined,
});
await enqueueJob(queue, descriptor, {
tenantId: null,
idempotencyKey: `admin-sales-import:${job.id}`,
});
await input.context.service.markImportJobQueued({
jobId: job.id,
actor,
});
return job.id;
}
export async function requestAdminSalesContactsExport(input: {
readonly contactIds: readonly string[];
readonly reason: string;
readonly context: AdminSalesDataOperatorContext;
readonly createQueue?: () => Promise<ImportQueue | undefined>;
readonly requestId?: string;
}) {
const actor = input.context.actor(input.reason);
const requestId = input.requestId ?? randomUUID();
const job = await input.context.service.createExportJob({
selectedContactIds: input.contactIds,
idempotencyKey: `admin-sales-export:${input.context.adminUserId}:${requestId}`,
actor,
});
const queue = await (input.createQueue ?? createAdminSalesDataQueue)();
if (!queue) throw new Error("Admin sales export queue is not available.");
const descriptor = buildAdminSalesContactsExportJob({
exportJobId: job.id,
requestedByAdminUserId: job.requestedByAdminUserId,
requestId: actor.requestId ?? undefined,
});
await enqueueJob(queue, descriptor, {
tenantId: null,
idempotencyKey: `admin-sales-export:${job.id}`,
});
await input.context.service.markExportJobQueued({
jobId: job.id,
actor,
});
return job.id;
}
export async function resolveAdminSalesDataDownload(input: {
readonly jobId: string;
readonly kind: "import-error" | "export";
}): Promise<string> {
const bucket = resolveStorageBucket();
if (input.kind === "import-error") {
const job = await db.adminImportJob.findFirst({
where: {
id: input.jobId,
status: "completed_with_errors",
errorReportBucket: bucket,
errorReportKey: `admin-sales/import-errors/${input.jobId}.csv`,
},
select: { errorReportKey: true },
});
if (!job?.errorReportKey) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
return createMediaDownloadUrl({
key: job.errorReportKey,
filename: `admin-sales-importfehler-${input.jobId}.csv`,
ttlSeconds: 60,
});
}
const job = await db.adminExportJob.findFirst({
where: {
id: input.jobId,
status: "completed",
artifactBucket: bucket,
artifactKey: `admin-sales/exports/${input.jobId}.csv`,
expiresAt: { gt: new Date() },
},
select: { artifactKey: true },
});
if (!job?.artifactKey) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
return createMediaDownloadUrl({
key: job.artifactKey,
filename: "admin-sales-contacts.csv",
ttlSeconds: 60,
});
}
async function createAdminSalesDataQueue(): Promise<ImportQueue | undefined> {
if (
process.env.IMPORT_QUEUE_ENABLED !== "true" ||
process.env.IMPORT_QUEUE_RUNTIME_READY !== "true"
) {
return undefined;
}
const connection = resolveRedisConnectionOptionsFromProcessEnv();
if (!connection) return undefined;
const runtimeModule = "@hivegrid/queue/runtime";
const { createQueue } = (await import(
/* @vite-ignore */ runtimeModule
)) as typeof import("@hivegrid/queue/runtime");
return createQueue(queueNames.imports, { connection });
}
@@ -0,0 +1,96 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import {
createAdminSalesPipelineService,
createPrismaAdminSalesPipelineRepository,
} from "@hivegrid/db/admin-sales-pipeline.server";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export type AdminSalesPipelineOperatorContext = {
readonly adminUserId: string;
readonly email: string;
readonly firstName: string;
readonly locale: string | null;
readonly canWrite: boolean;
readonly canConfigure: boolean;
readonly service: ReturnType<typeof createAdminSalesPipelineService>;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
};
export async function runAsAdminSalesPipelineOperator<T>(
request: Request,
permission: Extract<AdminPermissionName, "admin_sales.crm.read" | "admin_sales.crm.write" | "admin_sales.crm.assign">,
operation: (context: AdminSalesPipelineOperatorContext) => Promise<T>
): Promise<T> {
return runAsAdminIdentity(request, permission, async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true, firstName: true, locale: true },
});
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
const authorize = async (requestedPermission: AdminPermissionName) => {
if (!(await adminHasPermission(admin.id, requestedPermission, db))) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
};
const [canWrite, canConfigure, canReadAll, canWriteAll, canReadAllCommunication] =
await Promise.all([
adminHasPermission(admin.id, "admin_sales.crm.write", db),
adminHasPermission(admin.id, "admin_sales.crm.assign", db),
adminHasPermission(admin.id, "admin_sales.crm.read_all", db),
adminHasPermission(admin.id, "admin_sales.crm.write_all", db),
adminHasPermission(
admin.id,
"admin_sales.communication.read_all",
db
),
]);
const service = createAdminSalesPipelineService({
repository: createPrismaAdminSalesPipelineRepository(db, {
accessScope: {
adminUserId: admin.id,
canReadAll,
canWriteAll,
canReadAllCommunication,
},
}),
authorize,
});
const auditBase = {
adminUserId: admin.id,
email: admin.email,
firstName: admin.firstName,
locale: admin.locale,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
return operation({
adminUserId: admin.id,
email: admin.email,
firstName: admin.firstName,
locale: admin.locale,
canWrite,
canConfigure,
service,
actor: (reason) => ({ ...auditBase, reason }),
});
});
}
@@ -0,0 +1,50 @@
/**
* Route metadata for the `/sales/settings/*` branch.
*
* The branch layout is the deepest match that returns a `title`, so its title
* became the document title *and* the header breadcrumb for every child
* (`useTitleData` takes the last titled match). Until this map existed, opening
* "Telefonie-Einstellungen" or "Felder und Tags" announced itself as
* "Pipeline konfigurieren" — including the 404 page under
* `/sales/settings/leads` (admin audit 2026-07-26, P0-08).
*
* Keys are path prefixes below `/sales/settings`; the longest match wins, so a
* nested route can refine its parent. Labels reuse the navigation strings the
* operator clicked, which keeps title, breadcrumb and sidebar in one wording.
*/
export const ADMIN_SALES_SETTINGS_TITLE_KEYS: ReadonlyArray<readonly [path: string, i18nKey: string]> = [
["pipelines", "admin.sales.navigation.pipelineSettings"],
["leads", "admin.sales.navigation.leadSettings"],
["fields-tags", "admin.sales.navigation.fieldsTags"],
["telephony", "admin.sales.navigation.telephonySettings"],
["calendars", "admin.sales.booking.calendars.title"],
["meeting-types", "admin.sales.booking.settings.meetingTypes.title"],
["availability", "admin.sales.booking.settings.availability.title"],
["email-accounts", "admin.sales.email.accounts.title"],
["sending-domains", "admin.sales.email.domains.title"],
];
/** Fallback for a child that is not mapped yet: the branch's own section name. */
export const ADMIN_SALES_SETTINGS_FALLBACK_TITLE_KEY = "admin.sales.navigation.configurationSection";
/**
* Resolves the i18n key for a `/sales/settings/...` pathname. Matching is done
* on whole segments so `telephony-legacy` never matches `telephony`.
*/
export function resolveAdminSalesSettingsTitleKey(pathname: string): string {
const branchIndex = pathname.indexOf("/sales/settings");
const remainder = branchIndex === -1 ? "" : pathname.slice(branchIndex + "/sales/settings".length);
const segments = remainder.split("/").filter(Boolean);
let bestKey = ADMIN_SALES_SETTINGS_FALLBACK_TITLE_KEY;
let bestDepth = 0;
for (const [path, i18nKey] of ADMIN_SALES_SETTINGS_TITLE_KEYS) {
const candidate = path.split("/").filter(Boolean);
const matches = candidate.length <= segments.length && candidate.every((segment, index) => segment === segments[index]);
if (matches && candidate.length > bestDepth) {
bestKey = i18nKey;
bestDepth = candidate.length;
}
}
return bestKey;
}
@@ -0,0 +1,102 @@
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import {
adminSalesDayRange,
createAdminSalesTaskService,
createPrismaAdminSalesTaskRepository,
} from "@hivegrid/db/admin-sales-tasks.server";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
type AdminSalesTaskPermission = Extract<
AdminPermissionName,
"admin_sales.crm.read" | "admin_sales.crm.write"
>;
export type AdminSalesTaskOperatorContext = {
readonly adminUserId: string;
readonly email: string;
readonly timeZone: string;
readonly canWrite: boolean;
readonly service: ReturnType<typeof createAdminSalesTaskService>;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
};
export function getAdminSalesTaskDayRange(
now: Date,
timeZone: string
): { readonly start: Date; readonly end: Date } {
return adminSalesDayRange(now, timeZone);
}
export async function runAsAdminSalesTaskOperator<T>(
request: Request,
permission: AdminSalesTaskPermission,
operation: (context: AdminSalesTaskOperatorContext) => Promise<T>
): Promise<T> {
return runAsAdminIdentity(request, permission, async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true },
});
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
const authorize = async (requestedPermission: AdminPermissionName) => {
if (!(await adminHasPermission(admin.id, requestedPermission, db))) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
};
const [canWrite, canReadAll, canWriteAll, canReadAllCommunication] =
await Promise.all([
adminHasPermission(admin.id, "admin_sales.crm.write", db),
adminHasPermission(admin.id, "admin_sales.crm.read_all", db),
adminHasPermission(admin.id, "admin_sales.crm.write_all", db),
adminHasPermission(
admin.id,
"admin_sales.communication.read_all",
db
),
]);
const service = createAdminSalesTaskService({
repository: createPrismaAdminSalesTaskRepository(db, {
accessScope: {
adminUserId: admin.id,
canReadAll,
canWriteAll,
canReadAllCommunication,
},
}),
authorize,
});
const auditBase = {
adminUserId: admin.id,
email: admin.email,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
return operation({
adminUserId: admin.id,
email: admin.email,
timeZone: "Europe/Berlin",
canWrite,
service,
actor: (reason) => ({ ...auditBase, reason }),
});
});
}
@@ -0,0 +1,168 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
findDeal: vi.fn(),
findTenant: vi.fn(),
prepareInvitation: vi.fn(),
issueInvitation: vi.fn(),
createTenant: vi.fn(),
linkDeal: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({
db: {
adminDeal: { findFirst: mocks.findDeal },
tenant: { findUnique: mocks.findTenant },
},
}));
vi.mock("~/domain/tenant-bootstrap/ownerInvitationIssuance.server", () => ({
prepareReservedOwnerInvitation: mocks.prepareInvitation,
issueReservedOwnerInvitationWithTx: mocks.issueInvitation,
}));
vi.mock("~/utils/db/tenants.db.server", () => ({
createTenant: mocks.createTenant,
}));
vi.mock("@hivegrid/db/admin-sales-pipeline.server", () => ({
linkAdminDealToTenantWithTx: mocks.linkDeal,
}));
import {
createAndLinkAdminSalesTenant,
deriveAdminSalesTenantReservationKey,
} from "./admin-sales-tenant.server";
const input = {
request: new Request("https://admin.hivegrid.de/sales/deals/deal_1"),
dealId: "deal_1",
tenantName: "Muster GmbH",
tenantSlug: "muster-gmbh",
ownerEmail: "ada@example.test",
ownerFirstName: "Ada",
ownerLastName: "Lovelace",
admin: { id: "admin_1", firstName: "Raffael", locale: "de" },
actor: {
adminUserId: "admin_1",
email: "raffael@example.test",
reason: "Gewonnenen Deal ausdrücklich als Tenant anlegen",
},
} as const;
describe("admin sales tenant promotion", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.findDeal.mockResolvedValue({
status: "won",
promotedTenantId: null,
});
mocks.prepareInvitation.mockResolvedValue({
issuanceKey: deriveAdminSalesTenantReservationKey("deal_1"),
email: "ada@example.test",
firstName: "Ada",
lastName: "Lovelace",
fromUserId: null,
token: "token_value_that_is_long_enough_123456",
mail: { subject: "Einladung", html: "<p>token</p>" },
});
mocks.createTenant.mockImplementation(async (options) => {
const tenant = {
id: options.tenantId,
name: options.name,
slug: options.slug,
active: false,
deactivatedReason: "pending_owner",
};
await options.setup(tenant, { adminDeal: {} });
return tenant;
});
mocks.issueInvitation.mockResolvedValue({
invitationId: "invitation_1",
replayed: false,
});
mocks.linkDeal.mockResolvedValue({
id: "deal_1",
promotedTenantId: deriveAdminSalesTenantReservationKey("deal_1"),
});
});
it("derives one stable UUID-shaped reservation identity per deal", () => {
const first = deriveAdminSalesTenantReservationKey("deal_1");
expect(first).toBe(deriveAdminSalesTenantReservationKey("deal_1"));
expect(first).toMatch(
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-8[0-9a-f]{3}-[0-9a-f]{12}$/u
);
expect(first).not.toBe(deriveAdminSalesTenantReservationKey("deal_2"));
});
it("creates the pending owner reservation and deal link in one setup transaction", async () => {
await expect(createAndLinkAdminSalesTenant(input)).resolves.toMatchObject({
name: "Muster GmbH",
active: false,
deactivatedReason: "pending_owner",
});
expect(mocks.prepareInvitation).toHaveBeenCalledWith(
expect.objectContaining({
issuanceKey: deriveAdminSalesTenantReservationKey("deal_1"),
issuer: { id: null, firstName: "Raffael", locale: "de" },
})
);
expect(mocks.createTenant).toHaveBeenCalledWith(
expect.objectContaining({
active: false,
emitCreatedHook: false,
rejectSlugCollision: true,
rlsUserId: "admin_1",
setup: expect.any(Function),
validateExistingReplay: expect.any(Function),
})
);
expect(mocks.issueInvitation).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ tenantId: expect.any(String), fromUserId: null })
);
expect(mocks.linkDeal).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
dealId: "deal_1",
actor: input.actor,
allowPendingOwner: true,
})
);
});
it("replays an existing link without creating or sending again", async () => {
mocks.findDeal.mockResolvedValue({
status: "won",
promotedTenantId: "tenant_existing",
});
mocks.findTenant.mockResolvedValue({
id: "tenant_existing",
name: "Muster GmbH",
slug: "muster",
});
await expect(createAndLinkAdminSalesTenant(input)).resolves.toMatchObject({
id: "tenant_existing",
});
expect(mocks.prepareInvitation).not.toHaveBeenCalled();
expect(mocks.createTenant).not.toHaveBeenCalled();
});
it("aborts before every side effect when the deal is not won", async () => {
mocks.findDeal.mockResolvedValue({
status: "open",
promotedTenantId: null,
});
await expect(createAndLinkAdminSalesTenant(input)).rejects.toThrow(
"requires a won deal"
);
expect(mocks.prepareInvitation).not.toHaveBeenCalled();
expect(mocks.createTenant).not.toHaveBeenCalled();
expect(mocks.linkDeal).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,125 @@
import { createHash } from "node:crypto";
import {
linkAdminDealToTenantWithTx,
} from "@hivegrid/db/admin-sales-pipeline.server";
import type { AdminSalesActor } from "@hivegrid/db/admin-sales-core.server";
import type { Tenant } from "@hivegrid/db/prisma-browser";
import {
prepareReservedOwnerInvitation,
issueReservedOwnerInvitationWithTx,
} from "~/domain/tenant-bootstrap/ownerInvitationIssuance.server";
import { TENANT_PENDING_OWNER_REASON } from "~/domain/tenant-bootstrap/tenantBootstrap.constants";
import { db } from "~/utils/db.server";
import { createTenant } from "~/utils/db/tenants.db.server";
export type CreateAdminSalesTenantInput = {
readonly request: Request;
readonly dealId: string;
readonly tenantName: string;
readonly tenantSlug: string;
readonly ownerEmail: string;
readonly ownerFirstName: string;
readonly ownerLastName: string;
readonly admin: {
readonly id: string;
readonly firstName: string;
readonly locale: string | null;
};
readonly actor: AdminSalesActor;
};
export async function createAndLinkAdminSalesTenant(
input: CreateAdminSalesTenantInput
): Promise<Tenant> {
const replay = await resolveExistingPromotion(input.dealId);
if (replay) return replay;
const reservationKey = deriveAdminSalesTenantReservationKey(input.dealId);
const ownerInvitation = await prepareReservedOwnerInvitation({
request: input.request,
issuanceKey: reservationKey,
tenantName: input.tenantName,
email: input.ownerEmail,
firstName: input.ownerFirstName,
lastName: input.ownerLastName,
issuer: {
id: null,
firstName: input.admin.firstName,
locale: input.admin.locale,
},
});
return createTenant({
tenantId: reservationKey,
name: input.tenantName,
slug: input.tenantSlug,
rejectSlugCollision: true,
active: false,
deactivatedReason: TENANT_PENDING_OWNER_REASON,
rlsUserId: input.admin.id,
emitCreatedHook: false,
validateExistingReplay: async (tenant, tx) => {
const deal = await tx.adminDeal.findUnique({
where: { id: input.dealId },
select: { status: true, promotedTenantId: true },
});
if (
tenant.name !== input.tenantName ||
deal?.status !== "won" ||
deal.promotedTenantId !== tenant.id
) {
throw new Error("Admin sales tenant creation replay does not match.");
}
},
setup: async (tenant, tx) => {
await issueReservedOwnerInvitationWithTx(tx, {
tenantId: tenant.id,
...ownerInvitation,
});
await linkAdminDealToTenantWithTx(tx, {
dealId: input.dealId,
tenantId: tenant.id,
actor: input.actor,
allowPendingOwner: true,
});
return tenant;
},
});
}
export function deriveAdminSalesTenantReservationKey(dealId: string): string {
const normalized = dealId.trim();
if (!/^[A-Za-z0-9_:-]{1,191}$/u.test(normalized)) {
throw new Error("Admin sales deal identifier is invalid.");
}
const digest = createHash("sha256")
.update(`admin-sales:tenant:${normalized}`)
.digest("hex")
.slice(0, 32)
.split("");
digest[12] = "4";
digest[16] = "8";
const value = digest.join("");
return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
}
async function resolveExistingPromotion(dealId: string): Promise<Tenant | null> {
const deal = await db.adminDeal.findFirst({
where: { id: dealId, archivedAt: null },
select: { status: true, promotedTenantId: true },
});
if (!deal) throw new Error("Admin sales deal was not found.");
if (deal.status !== "won") {
throw new Error("Admin sales tenant promotion requires a won deal.");
}
if (!deal.promotedTenantId) return null;
const tenant = await db.tenant.findUnique({
where: { id: deal.promotedTenantId },
});
if (!tenant) {
throw new Error("Admin sales linked tenant was not found.");
}
return tenant;
}
@@ -0,0 +1,286 @@
import { createHash } from "node:crypto";
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { adminHasPermission } from "@hivegrid/db/admin-rbac.server";
import {
createAdminConnectionsService,
createPrismaAdminConnectionsRepository,
} from "@hivegrid/db/admin-connections.server";
import {
createAdminTelephonyService,
createPrismaAdminTelephonyRepository,
} from "@hivegrid/db/admin-telephony.server";
import {
createAdminTelephonyActionsService,
createPrismaAdminTelephonyActionsRepository,
} from "@hivegrid/db/admin-telephony-actions.server";
import {
createAdminTelephonyRecordingService,
createPrismaAdminTelephonyRecordingRepository,
} from "@hivegrid/db/admin-telephony-recordings.server";
import {
AIRCALL_CALL_WEBHOOK_EVENTS,
AIRCALL_OAUTH_SCOPE,
aircallTelephonyProvider,
exchangeAircallCodeForToken,
resolveAircallOAuthConfig,
} from "@hivegrid/integrations";
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
import {
extractWebActorIp,
extractWebActorUserAgent,
extractWebRequestId,
} from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
export type AdminTelephonyOperatorContext = {
readonly adminUserId: string;
readonly email: string;
readonly connections: ReturnType<typeof createAdminConnectionsService>;
readonly telephony: ReturnType<typeof createAdminTelephonyService>;
readonly actions: ReturnType<typeof createAdminTelephonyActionsService>;
readonly recordings: ReturnType<
typeof createAdminTelephonyRecordingService
>;
readonly canCall: boolean;
readonly canReadAllCommunication: boolean;
readonly canManageSettings: boolean;
readonly canManageRecording: boolean;
readonly actor: (reason: string) => {
readonly adminUserId: string;
readonly email: string;
readonly reason: string;
readonly requestId: string | null;
readonly ip: string | null;
readonly userAgent: string | null;
};
};
export async function runAsAdminTelephonyOperator<T>(
request: Request,
permission:
| Extract<
AdminPermissionName,
| "admin_sales.phone.call"
| "admin_sales.phone.recording"
| "admin_sales.integrations.manage"
| "admin_sales.communication.read_all"
>
| readonly Extract<
AdminPermissionName,
| "admin_sales.phone.call"
| "admin_sales.phone.recording"
| "admin_sales.integrations.manage"
| "admin_sales.communication.read_all"
>[],
operation: (context: AdminTelephonyOperatorContext) => Promise<T>
): Promise<T> {
return runAsAdminIdentity(request, permission, async (session) => {
const admin = await db.adminUser.findFirst({
where: { id: session.adminUserId, status: "active" },
select: { id: true, email: true },
});
if (!admin) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
const authorize = async (requested: AdminPermissionName) => {
if (!(await adminHasPermission(admin.id, requested, db))) {
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
}
};
const auditBase = {
adminUserId: admin.id,
email: admin.email,
requestId: extractWebRequestId(request),
ip: extractWebActorIp(request),
userAgent: extractWebActorUserAgent(request),
};
const [
canCall,
canManageSettings,
canManageRecording,
canReadAllCommunication,
] = await Promise.all([
adminHasPermission(admin.id, "admin_sales.phone.call", db),
adminHasPermission(admin.id, "admin_sales.integrations.manage", db),
adminHasPermission(admin.id, "admin_sales.phone.recording", db),
adminHasPermission(
admin.id,
"admin_sales.communication.read_all",
db
),
]);
return operation({
adminUserId: admin.id,
email: admin.email,
connections: createAdminConnectionsService({
repository: createPrismaAdminConnectionsRepository(db),
authorize,
permission: "admin_sales.integrations.manage",
}),
telephony: createAdminTelephonyService({
repository: createPrismaAdminTelephonyRepository(db),
authorize,
}),
actions: createAdminTelephonyActionsService({
repository: createPrismaAdminTelephonyActionsRepository(db),
authorize,
}),
recordings: createAdminTelephonyRecordingService({
repository: createPrismaAdminTelephonyRecordingRepository(db),
authorize,
}),
canCall,
canReadAllCommunication,
canManageSettings,
canManageRecording,
actor: (reason) => ({ ...auditBase, reason }),
});
});
}
export function getAdminAircallAuthorizationUrl(state: string): string {
const config = resolveAircallOAuthConfig();
if (!config) {
throw new Error("admin.sales.telephony.errors.aircallNotConfigured");
}
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
scope: AIRCALL_OAUTH_SCOPE,
state,
});
return `https://dashboard.aircall.io/oauth/authorize?${params.toString()}`;
}
export async function completeAdminAircallConnection(input: {
readonly context: AdminTelephonyOperatorContext;
readonly code: string;
readonly webhookUrl?: string;
}) {
const config = resolveAircallOAuthConfig();
const webhookUrl =
input.webhookUrl ?? process.env.ADMIN_AIRCALL_WEBHOOK_URL?.trim();
if (!config || !webhookUrl) {
throw new Error("admin.sales.telephony.errors.aircallNotConfigured");
}
const credentials = await exchangeAircallCodeForToken(config, input.code);
await aircallTelephonyProvider.probe(credentials);
const users = await aircallTelephonyProvider.listUsers(credentials);
const matchingUsers = users.filter(
(user) => user.email === input.context.email.trim().toLowerCase()
);
if (matchingUsers.length !== 1) {
throw new Error(
matchingUsers.length === 0
? "admin.sales.telephony.errors.aircallUserMissing"
: "admin.sales.telephony.errors.aircallUserAmbiguous"
);
}
const providerUser = matchingUsers[0]!;
const phoneNumbers = await aircallTelephonyProvider.listUserNumbers(
credentials,
providerUser.id
);
if (phoneNumbers.length === 0) {
throw new Error("admin.sales.telephony.errors.aircallNumberMissing");
}
const webhook = await aircallTelephonyProvider.createWebhook(credentials, {
name: `admin-sales-${input.context.adminUserId}`,
url: webhookUrl,
events: AIRCALL_CALL_WEBHOOK_EVENTS,
});
let connectionId: string | null = null;
try {
const actor = input.context.actor("Aircall für Admin Sales verbinden");
const connection = await input.context.connections.connect({
adminUserId: input.context.adminUserId,
provider: "aircall",
capability: "telephony",
label: providerUser.name,
externalAccountId: providerUser.id,
externalAccountEmail: providerUser.email,
scopes: [AIRCALL_OAUTH_SCOPE],
tokenExpiresAt: null,
credentials: { accessToken: credentials.accessToken },
actor,
});
connectionId = connection.id;
await input.context.telephony.activateConnection({
adminUserId: input.context.adminUserId,
connectionId: connection.id,
providerUserId: providerUser.id,
providerUserEmail: providerUser.email,
defaultProviderNumberId:
phoneNumbers.length === 1
? phoneNumbers[0]!.id
: providerUser.defaultNumberId,
webhookRegistrationId: webhook.id,
webhookTokenHash: createHash("sha256")
.update(webhook.token, "utf8")
.digest("hex"),
phoneNumbers: phoneNumbers.map((number) => ({
providerNumberId: number.id,
label: number.label,
e164: number.e164,
countryCode: number.countryCode,
selected: true,
})),
actor,
});
return { connectionId: connection.id };
} catch (error) {
await aircallTelephonyProvider
.deleteWebhook(credentials, webhook.id)
.catch(() => undefined);
if (connectionId) {
await input.context.connections
.disconnect({
connectionId,
adminUserId: input.context.adminUserId,
actor: input.context.actor(
"Unvollständige Aircall-Verbindung zurückrollen"
),
revokeProviderCredentials: () => Promise.resolve(),
})
.catch(() => undefined);
}
throw error;
}
}
export async function listAdminTelephonyConnectionSettings(
context: AdminTelephonyOperatorContext
) {
return db.adminPhoneConnection.findMany({
where: { adminUserId: context.adminUserId, archivedAt: null },
orderBy: [{ createdAt: "asc" }, { id: "asc" }],
select: {
id: true,
connectionId: true,
providerUserId: true,
providerUserEmail: true,
defaultPhoneNumberId: true,
webhookVerifiedAt: true,
lastEventAt: true,
connection: {
select: {
label: true,
status: true,
healthMessageKey: true,
webhookRegistrationId: true,
},
},
phoneNumbers: {
where: { archivedAt: null },
orderBy: [{ label: "asc" }, { id: "asc" }],
select: {
id: true,
label: true,
e164: true,
selected: true,
},
},
},
});
}
@@ -0,0 +1,78 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const config = vi.hoisted(() => ({
nodeEnv: "test",
routing: {
adminHost: "admin.localhost",
appHost: "app.localhost",
},
sessionSecret: "admin-phone-oauth-state-secret-aaaaaaaa",
}));
vi.mock("@hivegrid/config", async (importOriginal) => {
const original = await importOriginal<typeof import("@hivegrid/config")>();
return {
...original,
loadRequiredWebConfig: () => config,
};
});
import {
consumeAdminTelephonyOAuthState,
createAdminTelephonyOAuthState,
} from "./admin-telephony-oauth-state.server.js";
describe("admin telephony OAuth state", () => {
beforeEach(() => {
config.nodeEnv = "test";
});
it("binds the signed challenge to the admin and expires it after ten minutes", () => {
const challenge = createAdminTelephonyOAuthState({
adminUserId: "admin-1",
now: () => 1_000,
});
const cookie = challenge.cookie.split(";")[0]!;
const accepted = consumeAdminTelephonyOAuthState(
new Request("http://admin.localhost/callback", {
headers: { cookie },
}),
{
expectedState: challenge.state,
expectedAdminUserId: "admin-1",
now: () => 1_000 + 9 * 60_000,
}
);
expect(accepted.ok).toBe(true);
const expired = consumeAdminTelephonyOAuthState(
new Request("http://admin.localhost/callback", {
headers: { cookie },
}),
{
expectedState: challenge.state,
expectedAdminUserId: "admin-1",
now: () => 1_000 + 11 * 60_000,
}
);
expect(expired).toMatchObject({ ok: false, reason: "expired" });
});
it("rejects a challenge copied to another admin", () => {
const challenge = createAdminTelephonyOAuthState({
adminUserId: "admin-1",
now: () => 1_000,
});
const result = consumeAdminTelephonyOAuthState(
new Request("http://admin.localhost/callback", {
headers: { cookie: challenge.cookie.split(";")[0]! },
}),
{
expectedState: challenge.state,
expectedAdminUserId: "admin-2",
now: () => 2_000,
}
);
expect(result).toMatchObject({ ok: false, reason: "mismatch" });
});
});
@@ -0,0 +1,151 @@
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import {
loadRequiredWebConfig,
resolveHostOnlyCookiePolicy,
} from "@hivegrid/config";
const SECURE_COOKIE = "__Host-hivegrid_admin_phone_oauth";
const LOCAL_COOKIE = "hivegrid_admin_phone_oauth";
const TTL_MS = 10 * 60 * 1_000;
type AdminTelephonyOAuthState = {
readonly state: string;
readonly adminUserId: string;
readonly provider: "aircall";
readonly createdAt: number;
};
export function createAdminTelephonyOAuthState(input: {
readonly adminUserId: string;
readonly now?: () => number;
readonly secret?: string;
}): { readonly state: string; readonly cookie: string } {
const payload: AdminTelephonyOAuthState = {
state: randomBytes(32).toString("hex"),
adminUserId: required(input.adminUserId),
provider: "aircall",
createdAt: input.now?.() ?? Date.now(),
};
const encoded = Buffer.from(JSON.stringify(payload), "utf8").toString(
"base64url"
);
const signature = sign(encoded, resolveSecret(input.secret));
const policy = cookiePolicy();
return {
state: payload.state,
cookie: [
`${policy.name}=${encoded}.${signature}`,
`Path=${policy.path}`,
"HttpOnly",
"SameSite=Lax",
`Max-Age=${Math.ceil(TTL_MS / 1_000)}`,
...(policy.secure ? ["Secure"] : []),
].join("; "),
};
}
export function consumeAdminTelephonyOAuthState(
request: Request,
input: {
readonly expectedState: string;
readonly expectedAdminUserId: string;
readonly now?: () => number;
readonly secret?: string;
}
):
| { readonly ok: true; readonly clearCookie: string }
| {
readonly ok: false;
readonly reason:
| "missing"
| "malformed"
| "invalid_signature"
| "expired"
| "mismatch";
readonly clearCookie: string;
} {
const policy = cookiePolicy();
const clearCookie = [
`${policy.name}=`,
`Path=${policy.path}`,
"HttpOnly",
"SameSite=Lax",
"Max-Age=0",
...(policy.secure ? ["Secure"] : []),
].join("; ");
const value = readCookie(request, policy.name);
if (!value) return { ok: false, reason: "missing", clearCookie };
const [encoded, signature, ...rest] = value.split(".");
if (!encoded || !signature || rest.length > 0) {
return { ok: false, reason: "malformed", clearCookie };
}
const expectedSignature = sign(encoded, resolveSecret(input.secret));
const left = Buffer.from(signature);
const right = Buffer.from(expectedSignature);
if (left.length !== right.length || !timingSafeEqual(left, right)) {
return { ok: false, reason: "invalid_signature", clearCookie };
}
let payload: AdminTelephonyOAuthState;
try {
payload = JSON.parse(
Buffer.from(encoded, "base64url").toString("utf8")
) as AdminTelephonyOAuthState;
} catch {
return { ok: false, reason: "malformed", clearCookie };
}
const now = input.now?.() ?? Date.now();
if (
!Number.isFinite(payload.createdAt) ||
payload.createdAt > now + 60_000 ||
now - payload.createdAt > TTL_MS
) {
return { ok: false, reason: "expired", clearCookie };
}
if (
payload.state !== input.expectedState ||
payload.provider !== "aircall" ||
payload.adminUserId !== input.expectedAdminUserId
) {
return { ok: false, reason: "mismatch", clearCookie };
}
return { ok: true, clearCookie };
}
function resolveSecret(override?: string): string {
const secret = override ?? loadRequiredWebConfig().sessionSecret;
if (!secret || Buffer.byteLength(secret, "utf8") < 32) {
throw new Error("SESSION_SECRET is required for admin phone OAuth state.");
}
return secret;
}
function cookiePolicy() {
const config = loadRequiredWebConfig();
return resolveHostOnlyCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
secureName: SECURE_COOKIE,
localName: LOCAL_COOKIE,
maxAge: Math.ceil(TTL_MS / 1_000),
});
}
function sign(value: string, secret: string): string {
return createHmac("sha256", secret).update(value).digest("base64url");
}
function readCookie(request: Request, name: string): string | null {
for (const segment of request.headers.get("cookie")?.split(/;\s*/) ?? []) {
const separator = segment.indexOf("=");
if (separator > 0 && segment.slice(0, separator) === name) {
return segment.slice(separator + 1);
}
}
return null;
}
function required(value: string): string {
const normalized = value.trim();
if (!normalized) throw new Error("adminUserId is required");
return normalized;
}
@@ -0,0 +1,85 @@
// @vitest-environment node
import { createCipheriv, createHash, randomBytes } from "node:crypto";
import { describe, expect, it, vi } from "vitest";
import type { AdminCallRecordingPlayback } from "@hivegrid/db/admin-telephony-recordings.server";
import type { KeyWrapper } from "@hivegrid/foundation/crypto";
vi.mock("~/utils/integrations/storageService", () => ({
resolveStorageBucket: () => "eu-private",
}));
const wrapper: KeyWrapper = {
wrap: async (value) => Buffer.concat([Buffer.from("wrapped:"), value]),
unwrap: async (value) => value.subarray(Buffer.from("wrapped:").length),
};
import { readAdminCallRecordingPlayback } from "./admin-telephony-recording-playback.server";
async function fixture() {
const plaintext = Buffer.from("secure call recording");
const dek = randomBytes(32);
const iv = randomBytes(12);
const cipher = createCipheriv("aes-256-gcm", dek, iv);
const ciphertext = Buffer.concat([
cipher.update(plaintext),
cipher.final(),
]);
const recording: AdminCallRecordingPlayback = {
id: "recording_1",
adminUserId: "admin_1",
callSessionId: "call_1",
storageBucket: "eu-private",
storageKey: "admin-call-recordings/recording_1.enc",
encryptedSizeBytes: ciphertext.byteLength,
checksumSha256: createHash("sha256").update(plaintext).digest("hex"),
wrappedDek: await wrapper.wrap(dek),
iv,
authTag: cipher.getAuthTag(),
retainedUntil: new Date("2026-10-18T08:00:00.000Z"),
};
return { ciphertext, plaintext, recording };
}
describe("admin telephony recording playback", () => {
it("reads only the configured private bucket and decrypts the artifact", async () => {
const { ciphertext, plaintext, recording } = await fixture();
const createDownloadUrl = vi.fn().mockResolvedValue(
"https://storage.example.test/recording.enc"
);
const bytes = await readAdminCallRecordingPlayback({
recording,
wrapper,
createDownloadUrl,
fetchImpl: vi.fn().mockResolvedValue(
new Response(Uint8Array.from(ciphertext).buffer, {
status: 200,
headers: {
"content-length": String(ciphertext.byteLength),
},
})
),
});
expect(Buffer.from(bytes)).toEqual(plaintext);
expect(createDownloadUrl).toHaveBeenCalledWith({
key: recording.storageKey,
ttlSeconds: 60,
});
});
it("fails closed for an artifact in a different bucket", async () => {
const { recording } = await fixture();
const createDownloadUrl = vi.fn();
await expect(
readAdminCallRecordingPlayback({
recording: { ...recording, storageBucket: "other" },
wrapper,
createDownloadUrl,
})
).rejects.toThrow(
"admin.sales.telephony.errors.recordingUnavailable"
);
expect(createDownloadUrl).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,69 @@
import type { AdminCallRecordingPlayback } from "@hivegrid/db/admin-telephony-recordings.server";
import { ADMIN_CONNECTION_MASTER_KEY_ENV } from "@hivegrid/db/crypto/admin-connection-envelope.server";
import { EnvKeyWrapper, type KeyWrapper } from "@hivegrid/foundation/crypto";
import {
ADMIN_CALL_RECORDING_MAX_BYTES,
decryptAdminCallRecording,
} from "@hivegrid/integrations/admin-call-recordings.server";
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
import { resolveStorageBucket } from "~/utils/integrations/storageService";
const RECORDING_READ_TIMEOUT_MS = 30_000;
export async function readAdminCallRecordingPlayback(input: {
readonly recording: AdminCallRecordingPlayback;
readonly signal?: AbortSignal;
readonly createDownloadUrl?: typeof createMediaDownloadUrl;
readonly fetchImpl?: typeof fetch;
readonly wrapper?: KeyWrapper;
}): Promise<Uint8Array> {
if (
input.recording.storageBucket !== resolveStorageBucket() ||
input.recording.encryptedSizeBytes <= 0 ||
input.recording.encryptedSizeBytes > ADMIN_CALL_RECORDING_MAX_BYTES
) {
throw new Error("admin.sales.telephony.errors.recordingUnavailable");
}
const url = await (
input.createDownloadUrl ?? createMediaDownloadUrl
)({
key: input.recording.storageKey,
ttlSeconds: 60,
});
const controller = new AbortController();
const forwardAbort = () => controller.abort(input.signal?.reason);
if (input.signal?.aborted) forwardAbort();
else input.signal?.addEventListener("abort", forwardAbort, { once: true });
const timeout = setTimeout(
() => controller.abort(new Error("recording read timed out")),
RECORDING_READ_TIMEOUT_MS
);
try {
const response = await (input.fetchImpl ?? fetch)(url, {
method: "GET",
signal: controller.signal,
redirect: "error",
headers: { Accept: "application/octet-stream" },
});
const declaredLength = Number(response.headers.get("content-length"));
if (
!response.ok ||
(Number.isFinite(declaredLength) &&
declaredLength > 0 &&
declaredLength !== input.recording.encryptedSizeBytes)
) {
throw new Error("admin.sales.telephony.errors.recordingUnavailable");
}
const encrypted = new Uint8Array(await response.arrayBuffer());
return decryptAdminCallRecording(
input.recording,
encrypted,
input.wrapper ??
new EnvKeyWrapper(ADMIN_CONNECTION_MASTER_KEY_ENV)
);
} finally {
clearTimeout(timeout);
input.signal?.removeEventListener("abort", forwardAbort);
}
}
@@ -0,0 +1,86 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
calls: vi.fn(),
dispositions: vi.fn(),
contacts: vi.fn(),
policy: vi.fn(),
dialerLists: vi.fn(),
audit: vi.fn(),
}));
vi.mock("@hivegrid/db/admin-sales-core.server", () => ({
writeAdminSalesAudit: mocks.audit,
}));
vi.mock("~/utils/db.server", () => ({
db: {
adminCallSession: { findMany: mocks.calls },
adminCallDisposition: { findMany: mocks.dispositions },
adminContact: { findMany: mocks.contacts },
adminTelephonyPolicy: { findUnique: mocks.policy },
adminDialerList: { findMany: mocks.dialerLists },
},
}));
import { readAdminTelephonyWorkspace } from "./admin-telephony-workspace.server";
describe("admin telephony team scope", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.calls.mockResolvedValue([{ id: "call-b", adminUserId: "sales-b" }]);
mocks.dispositions.mockResolvedValue([]);
mocks.contacts.mockResolvedValue([]);
mocks.policy.mockResolvedValue(null);
mocks.dialerLists.mockResolvedValue([]);
});
it("loads team calls read-only and audits a selected foreign call", async () => {
const result = await readAdminTelephonyWorkspace(
{
adminUserId: "manager",
canReadAllCommunication: true,
canCall: false,
canManageSettings: false,
canManageRecording: false,
actor: (reason: string) => ({
adminUserId: "manager",
email: "manager@example.test",
reason,
}),
} as never,
"call-b"
);
expect(mocks.calls).toHaveBeenCalledWith(
expect.objectContaining({ where: {} })
);
expect(result.permissions.canCall).toBe(false);
expect(mocks.audit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "admin.sales.telephony.foreignCalls.read",
targetId: "call-b",
after: {
foreignTargets: [
{
targetId: "call-b",
dataOwnerAdminUserId: "sales-b",
},
],
accessKind: "read",
},
})
);
expect(mocks.audit).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
action: "admin.sales.telephony.foreignCall.read",
targetId: "call-b",
after: {
dataOwnerAdminUserId: "sales-b",
accessKind: "read",
},
})
);
});
});
@@ -0,0 +1,274 @@
import type { AdminTelephonyAction } from "@hivegrid/view-models";
import { writeAdminSalesAudit } from "@hivegrid/db/admin-sales-core.server";
import type { AdminTelephonyOperatorContext } from "./admin-telephony-connections.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { db } from "~/utils/db.server";
export function adminTelephonyWorkspaceHrefs() {
return {
calls: adminPath("sales/calls", { mode: "host-aware" }),
settings: adminPath("settings/telephony", {
mode: "host-aware",
}),
newLead: adminPath("leads/new", { mode: "host-aware" }),
};
}
export async function readAdminTelephonyWorkspace(
context: AdminTelephonyOperatorContext,
selectedCallId?: string | null
) {
const ownerWhere = context.canReadAllCommunication
? {}
: { adminUserId: context.adminUserId };
const [calls, dispositions, contacts, policy, dialerLists] =
await Promise.all([
db.adminCallSession.findMany({
where: ownerWhere,
orderBy: [{ startedAt: "desc" }, { id: "asc" }],
take: 100,
include: {
contact: {
select: { firstName: true, lastName: true },
},
lead: {
select: {
firstName: true,
lastName: true,
email: true,
},
},
deal: { select: { title: true } },
recording: {
select: { status: true, retainedUntil: true },
},
matchCandidates: {
orderBy: [
{ confidenceBasisPoints: "desc" },
{ createdAt: "asc" },
],
include: {
contact: {
select: {
firstName: true,
lastName: true,
deals: {
where: { deal: { status: "open" } },
orderBy: [
{ isPrimary: "desc" },
{ createdAt: "asc" },
],
take: 1,
select: { dealId: true },
},
},
},
lead: {
select: {
firstName: true,
lastName: true,
email: true,
},
},
},
},
},
}),
db.adminCallDisposition.findMany({
where: { active: true, archivedAt: null },
orderBy: [{ position: "asc" }, { code: "asc" }],
select: { code: true },
}),
db.adminContact.findMany({
where: {
archivedAt: null,
normalizedPhone: { not: null },
},
orderBy: [{ lastName: "asc" }, { firstName: "asc" }, { id: "asc" }],
take: 500,
select: {
id: true,
firstName: true,
lastName: true,
normalizedPhone: true,
doNotCall: true,
deals: {
where: { deal: { status: "open" } },
orderBy: [{ isPrimary: "desc" }, { createdAt: "asc" }],
take: 1,
select: { dealId: true },
},
},
}),
db.adminTelephonyPolicy.findUnique({
where: { adminUserId: context.adminUserId },
}),
db.adminDialerList.findMany({
where: {
...ownerWhere,
archivedAt: null,
},
orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
take: 50,
include: {
entries: {
orderBy: [{ position: "asc" }, { id: "asc" }],
include: {
contact: {
select: {
id: true,
firstName: true,
lastName: true,
normalizedPhone: true,
},
},
},
},
},
}),
]);
const foreignCalls = calls.filter(
(call) => call.adminUserId !== context.adminUserId
);
if (foreignCalls.length > 0) {
await writeAdminSalesAudit(db, {
actor: context.actor("Fremde Team-Anrufe aufgelistet"),
action: "admin.sales.telephony.foreignCalls.read",
targetType: "AdminCallSession",
targetId: foreignCalls[0]!.id,
after: {
foreignTargets: foreignCalls.map((call) => ({
targetId: call.id,
dataOwnerAdminUserId: call.adminUserId,
})),
accessKind: "read",
},
});
}
const selectedCall = selectedCallId
? calls.find((call) => call.id === selectedCallId)
: null;
if (
selectedCall &&
selectedCall.adminUserId !== context.adminUserId
) {
await writeAdminSalesAudit(db, {
actor: context.actor("Fremden Team-Anruf geöffnet"),
action: "admin.sales.telephony.foreignCall.read",
targetType: "AdminCallSession",
targetId: selectedCall.id,
after: {
dataOwnerAdminUserId: selectedCall.adminUserId,
accessKind: "read",
},
});
}
return {
calls,
selectedCallId,
dispositions,
contacts,
policy,
dialerLists,
permissions: {
canCall: context.canCall,
canManageSettings: context.canManageSettings,
canManageRecording: context.canManageRecording,
},
};
}
export async function applyAdminTelephonyWorkspaceAction(
context: AdminTelephonyOperatorContext,
action: AdminTelephonyAction
) {
const actor = context.actor(action.reason);
switch (action.intent) {
case "save-outcome":
return context.actions.saveOutcome({
adminUserId: context.adminUserId,
callSessionId: action.callSessionId,
dispositionCode: action.dispositionCode,
note: action.note,
callbackTask:
action.callbackTitle && action.callbackDueAt
? {
title: action.callbackTitle,
dueAt: new Date(action.callbackDueAt),
timeZone: "Europe/Berlin",
priority: "high",
}
: null,
actor,
});
case "confirm-match":
return context.actions.confirmMatch({
adminUserId: context.adminUserId,
callSessionId: action.callSessionId,
contactId: action.contactId,
leadId: action.leadId,
dealId: action.dealId,
actor,
});
case "queue-call":
return context.actions.queueOutboundCall({
adminUserId: context.adminUserId,
contactId: action.contactId,
dealId: action.dealId,
dialerEntryId: action.dialerEntryId,
idempotencyKey: action.idempotencyKey,
actor,
});
case "create-dialer":
return context.actions.createDialerList({
adminUserId: context.adminUserId,
name: action.name,
contactIds: action.contactIds,
actor,
});
case "next-dialer":
return context.actions.activateNextDialerEntry({
adminUserId: context.adminUserId,
dialerListId: action.dialerListId,
actor,
});
case "finish-dialer":
return context.actions.finishDialerEntry({
adminUserId: context.adminUserId,
dialerEntryId: action.dialerEntryId,
outcome: action.outcome,
callSessionId: action.callSessionId,
actor,
});
case "update-policy":
return context.actions.updatePolicy({
adminUserId: context.adminUserId,
outboundEnabled: action.outboundEnabled,
dailyCallLimit: action.dailyCallLimit,
workDayStartMinutes: action.workDayStartMinutes,
workDayEndMinutes: action.workDayEndMinutes,
workDays: action.workDays,
timeZone: action.timeZone,
dncEnforced: true,
actor,
});
case "update-recording-policy":
return context.recordings.updatePolicy({
adminUserId: context.adminUserId,
enabled: action.enabled,
accepted: action.accepted,
consentText: action.consentText,
consentVersion: action.consentVersion,
actor,
});
case "confirm-recording-consent":
return context.recordings.confirmCallConsent({
adminUserId: context.adminUserId,
callSessionId: action.callSessionId,
confirmed: action.confirmed,
actor,
});
}
}
@@ -0,0 +1,96 @@
import { describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { getApiAdminSnapshot } from "./api-admin.server";
function makeDb() {
return {
apiKey: {
findMany: vi.fn(async () => {
const context = getRlsExecutionContext();
expect(context).toMatchObject({ userId: "operator_1", tenantId: "tenant_1" });
return [
{ id: "key_1", active: true, expires: null, createdAt: new Date("2026-07-09T09:00:00.000Z") },
{ id: "key_2", active: false, expires: new Date("2026-07-08T09:00:00.000Z"), createdAt: new Date("2026-07-08T09:00:00.000Z") },
];
}),
},
apiKeyLog: { count: vi.fn(async () => 1) },
registration: {
count: vi.fn(async () => 1),
findMany: vi.fn(async () => [
{ id: "reg_1", email: "lead@example.test", company: "Acme", createdAt: new Date("2026-07-09T10:00:00.000Z"), createdTenantId: null },
]),
},
adminLead: {
count: vi.fn(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1" });
return 3;
}),
findMany: vi.fn(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1" });
return [
{
id: "lead_1",
email: "lead@example.test",
company: "Acme",
source: { displayName: "HiveGrid Website" },
status: "new",
capturedAt: new Date("2026-07-09T10:00:00.000Z"),
},
];
}),
},
tenant: {
findMany: vi.fn(async () => [
{
id: "tenant_1",
name: "Acme",
slug: "acme",
},
]),
},
};
}
describe("getApiAdminSnapshot", () => {
it("aggregates API keys, logs, consumers, and inbound registrations", async () => {
const db = makeDb();
const snapshot = await runWithRlsContext({ userId: "operator_1" }, () =>
getApiAdminSnapshot({
db: db as never,
now: () => new Date("2026-07-09T10:00:00.000Z"),
platformLeadVisibility: {
actorAdminUserId: "operator_1",
canReadAll: false,
},
})
);
expect(db.apiKey.findMany).toHaveBeenCalledWith({
orderBy: { createdAt: "desc" },
select: { id: true, active: true, expires: true, createdAt: true },
});
expect(db.apiKeyLog.count).toHaveBeenCalledWith({ where: { status: { gte: 400 } } });
expect(db.adminLead.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
archivedAt: null,
assignedToAdminUserId: "operator_1",
},
})
);
expect(snapshot.metrics).toEqual(
expect.arrayContaining([
expect.objectContaining({ id: "keys", value: 2 }),
expect.objectContaining({ id: "activeKeys", value: 1 }),
expect.objectContaining({ id: "expiredKeys", value: 1 }),
])
);
expect(snapshot.consumers[0]).toMatchObject({ name: "Acme", keyCount: 2, activeKeyCount: 1 });
expect(snapshot.inbound.recentRegistrations[0]).toMatchObject({ email: "lead@example.test" });
expect(snapshot.inbound.recentLeads[0]).toMatchObject({
source: "HiveGrid Website",
});
});
});
@@ -0,0 +1,159 @@
import type { ApiAdminConsumerInput, ApiAdminInput } from "@hivegrid/view-models";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
export type ApiAdminDeps = {
readonly db?: typeof db;
readonly now?: () => Date;
readonly platformLeadVisibility: {
readonly actorAdminUserId: string;
readonly canReadAll: boolean;
} | null;
};
export async function getApiAdminSnapshot(deps: ApiAdminDeps): Promise<ApiAdminInput> {
const client = deps.db ?? db;
const now = deps.now?.() ?? new Date();
const platformLeadWhere = deps.platformLeadVisibility
? ({
archivedAt: null,
...(deps.platformLeadVisibility.canReadAll
? {}
: {
assignedToAdminUserId: deps.platformLeadVisibility.actorAdminUserId,
}),
} as const)
: null;
const [failedLogs, registrationsPending, leadsNew, leadsQualified, recentRegistrations, recentLeads, tenants] = await Promise.all([
client.apiKeyLog.count({ where: { status: { gte: 400 } } }),
client.registration.count({ where: { createdTenantId: null } }),
platformLeadWhere ? client.adminLead.count({ where: { ...platformLeadWhere, status: "new" } }) : Promise.resolve(0),
platformLeadWhere ? client.adminLead.count({ where: { ...platformLeadWhere, status: "qualified" } }) : Promise.resolve(0),
client.registration.findMany({
orderBy: { createdAt: "desc" },
take: 10,
select: { id: true, email: true, company: true, createdAt: true, createdTenantId: true },
}),
platformLeadWhere
? client.adminLead.findMany({
where: platformLeadWhere,
orderBy: [{ capturedAt: "desc" }, { id: "desc" }],
take: 10,
select: {
id: true,
email: true,
company: true,
status: true,
capturedAt: true,
source: { select: { displayName: true } },
},
})
: Promise.resolve([]),
client.tenant.findMany({
orderBy: { name: "asc" },
select: {
id: true,
name: true,
slug: true,
},
}),
]);
const tenantKeyGroups = await mapWithConcurrency(tenants, 8, async (tenant) => ({
tenant,
keys: await runWithRlsContext({ tenantId: tenant.id }, () =>
client.apiKey.findMany({
orderBy: { createdAt: "desc" },
select: { id: true, active: true, expires: true, createdAt: true },
})
),
}));
const allKeys = tenantKeyGroups.flatMap(({ keys }) => keys);
const keysTotal = allKeys.length;
const keysActive = allKeys.filter((key) => key.active && (!key.expires || key.expires > now)).length;
const keysExpired = allKeys.filter((key) => key.expires && key.expires <= now).length;
const consumers = tenantKeyGroups.filter(({ keys }) => keys.length > 0).slice(0, 50);
return {
metrics: [
{
id: "keys",
value: keysTotal,
labelKey: "admin.apiAdmin.metrics.keys.label",
detailKey: "admin.apiAdmin.metrics.keys.detail",
tone: keysTotal > 0 ? "success" : "warning",
},
{
id: "activeKeys",
value: keysActive,
labelKey: "admin.apiAdmin.metrics.activeKeys.label",
detailKey: "admin.apiAdmin.metrics.activeKeys.detail",
tone: keysActive > 0 ? "success" : "neutral",
},
{
id: "expiredKeys",
value: keysExpired,
labelKey: "admin.apiAdmin.metrics.expiredKeys.label",
detailKey: "admin.apiAdmin.metrics.expiredKeys.detail",
tone: keysExpired > 0 ? "warning" : "success",
},
{
id: "failedLogs",
value: failedLogs,
labelKey: "admin.apiAdmin.metrics.failedLogs.label",
detailKey: "admin.apiAdmin.metrics.failedLogs.detail",
tone: failedLogs > 0 ? "danger" : "success",
},
{
id: "inbound",
value: registrationsPending + leadsNew,
labelKey: "admin.apiAdmin.metrics.inbound.label",
detailKey: "admin.apiAdmin.metrics.inbound.detail",
tone: registrationsPending + leadsNew > 0 ? "warning" : "success",
},
],
consumers: consumers.map<ApiAdminConsumerInput>(({ tenant, keys }) => ({
id: tenant.id,
name: tenant.name,
slug: tenant.slug,
keyCount: keys.length,
activeKeyCount: keys.filter((key) => key.active && (!key.expires || key.expires > now)).length,
lastKeyCreatedAt: keys[0]?.createdAt.toISOString() ?? null,
})),
inbound: {
registrationsPending,
leadsNew,
leadsQualified,
recentRegistrations: recentRegistrations.map((registration) => ({
id: registration.id,
email: registration.email,
company: registration.company,
createdAt: registration.createdAt.toISOString(),
createdTenantId: registration.createdTenantId,
})),
recentLeads: recentLeads.map((lead) => ({
id: lead.id,
email: lead.email,
company: lead.company,
source: lead.source.displayName,
status: lead.status,
createdAt: lead.capturedAt.toISOString(),
})),
},
};
}
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;
}
@@ -1,9 +1,20 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AdminBillingError, listAdminBillingRows, requestManualBillingSync, setTenantBillingPlanSeats, type AdminBillingDeps } from "./billing-admin.server";
import { describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import {
AdminBillingError,
extendTenantTrial,
listAdminBillingRows,
normalizeTrialExtensionDays,
requestManualBillingSync,
resolveExtendedTrialEnd,
setTenantBillingPlanSeats,
type AdminBillingDeps,
} from "./billing-admin.server";
function createDeps(overrides: Partial<AdminBillingDeps> = {}): AdminBillingDeps {
const tx = {
$queryRaw: vi.fn(async () => []),
tenantSubscription: {
upsert: vi.fn(async () => ({ id: "sub_1" })),
},
@@ -13,12 +24,40 @@ function createDeps(overrides: Partial<AdminBillingDeps> = {}): AdminBillingDeps
update: vi.fn(async () => ({})),
create: vi.fn(async () => ({})),
},
portalDomainHostnameClaim: {
findMany: vi
.fn()
.mockResolvedValueOnce([{ id: "claim_1" }])
.mockResolvedValueOnce([]),
findFirst: vi.fn(async () => null),
updateMany: vi.fn(async () => ({ count: 0 })),
},
portalCustomDomain: {
updateMany: vi.fn(async () => ({ count: 0 })),
},
tenantProductAcquisition: {
findMany: vi.fn(async () => []),
},
outboxEvent: {
create: vi.fn(),
findUnique: vi.fn(async () => null),
},
};
const db = {
tenant: {
findMany: vi.fn(async () => [{ id: "tenant_1", name: "Acme", slug: "acme" }]),
findUnique: vi.fn(async () => ({ id: "tenant_1", name: "Acme", slug: "acme" })),
},
tenantSubscription: {
findUnique: vi.fn(async () => ({
id: "sub_1",
status: "past_due",
trialEndsAt: new Date("2026-07-01T00:00:00.000Z"),
pastDueSince: new Date("2026-07-02T00:00:00.000Z"),
frozenAt: null,
})),
upsert: vi.fn(async () => ({ id: "sub_1" })),
},
subscriptionProduct: {
findFirst: vi.fn(async () => ({ id: "product_1" })),
},
@@ -58,6 +97,39 @@ function createDeps(overrides: Partial<AdminBillingDeps> = {}): AdminBillingDeps
},
],
})),
resolveBillingStates: vi.fn(async () => [
{
tenantId: "tenant_1",
status: "active",
readOnly: false,
planCode: "starter",
seatQuantity: 3,
lagoCustomerId: "lago_1",
mollieCustomerId: "mollie_1",
lastInvoiceExternalId: "inv_1",
lastPaymentExternalId: "pay_1",
trialStartsAt: null,
trialEndsAt: null,
pastDueSince: null,
frozenAt: null,
cancelledAt: null,
currentPeriodStart: new Date("2026-07-01T00:00:00.000Z"),
currentPeriodEnd: new Date("2026-08-01T00:00:00.000Z"),
entitlements: [
{
featureKey: "crm",
title: "CRM",
enabled: true,
limitType: 1,
limit: 1,
quotaValue: null,
accumulate: false,
sourceProductId: "product_1",
sourcePlanCode: "starter",
},
],
},
]),
invalidateModuleCache: vi.fn(),
clearSubscriptionCache: vi.fn(),
recordAction: vi.fn(async () => undefined),
@@ -138,6 +210,10 @@ function createDeps(overrides: Partial<AdminBillingDeps> = {}): AdminBillingDeps
describe("listAdminBillingRows", () => {
it("maps tenants and billing state into loader rows", async () => {
const deps = createDeps();
vi.mocked(deps.resolveBillingState).mockImplementationOnce(async (tenantId) => {
expect(getRlsExecutionContext()?.tenantId).toBe(tenantId);
return createDeps().resolveBillingState(tenantId);
});
await expect(listAdminBillingRows(deps)).resolves.toMatchObject([
{
@@ -149,12 +225,37 @@ describe("listAdminBillingRows", () => {
currentPeriodStart: "2026-07-01T00:00:00.000Z",
},
]);
expect(deps.resolveBillingStates).not.toHaveBeenCalled();
expect(deps.resolveBillingState).toHaveBeenCalledWith("tenant_1");
});
it("loads cross-tenant billing details in one isolated context per tenant", async () => {
const deps = createDeps();
vi.mocked(deps.db.tenant.findMany).mockResolvedValue([
{ id: "tenant_1", name: "Acme", slug: "acme" },
{ id: "tenant_2", name: "Beta", slug: "beta" },
] as never);
const baseState = await createDeps().resolveBillingState("tenant_1");
const observedTenantIds: Array<string | undefined> = [];
vi.mocked(deps.resolveBillingState).mockImplementation(async (tenantId) => {
observedTenantIds.push(getRlsExecutionContext()?.tenantId);
return { ...baseState, tenantId };
});
const rows = await listAdminBillingRows(deps);
expect(rows.map((row) => row.tenantId)).toEqual(["tenant_1", "tenant_2"]);
expect(observedTenantIds).toEqual(["tenant_1", "tenant_2"]);
});
});
describe("setTenantBillingPlanSeats", () => {
it("sets plan/seats, attaches matching catalog product, invalidates caches, and audits the reason", async () => {
const deps = createDeps();
vi.mocked(deps.resolveBillingState).mockImplementationOnce(async (tenantId) => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
return createDeps().resolveBillingState(tenantId);
});
await setTenantBillingPlanSeats(
{
@@ -170,21 +271,30 @@ describe("setTenantBillingPlanSeats", () => {
expect(deps.db.tenant.findUnique).toHaveBeenCalledWith({ where: { id: "tenant_1" }, select: { id: true, name: true, slug: true } });
expect(deps.db.subscriptionProduct.findFirst).toHaveBeenCalled();
expect(
(
deps.db as never as {
__tx: { tenantSubscription: { upsert: ReturnType<typeof vi.fn> }; tenantSubscriptionProduct: { create: ReturnType<typeof vi.fn> } };
}
).__tx.tenantSubscription.upsert
).toHaveBeenCalledWith(
const transaction = (
deps.db as never as {
__tx: {
$queryRaw: ReturnType<typeof vi.fn>;
tenantSubscription: { upsert: ReturnType<typeof vi.fn> };
tenantSubscriptionProduct: { create: ReturnType<typeof vi.fn> };
};
}
).__tx;
const rawCalls = transaction.$queryRaw.mock.calls as Array<[TemplateStringsArray, ...unknown[]]>;
expect(rawCalls[0]?.[0].join("?")).toContain("hashtextextended('portal-domain-billing:' || ? || ':' || ?, 26003)");
expect(rawCalls[0]?.slice(1)).toEqual(["tenant_1", "claim_1"]);
expect(rawCalls[1]?.[0].join("?")).toContain('FROM "PortalCustomDomain"');
expect(rawCalls[2]?.[0].join("?")).toContain('FROM "PortalDomainHostnameClaim"');
expect(transaction.$queryRaw.mock.invocationCallOrder[2]).toBeLessThan(
transaction.tenantSubscription.upsert.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
);
expect(transaction.tenantSubscription.upsert).toHaveBeenCalledWith(
expect.objectContaining({
create: expect.objectContaining({ planCode: "starter", seatQuantity: 5, status: "active" }),
update: expect.objectContaining({ planCode: "starter", seatQuantity: 5, status: "active" }),
})
);
expect(
(deps.db as never as { __tx: { tenantSubscriptionProduct: { create: ReturnType<typeof vi.fn> } } }).__tx.tenantSubscriptionProduct.create
).toHaveBeenCalledWith(
expect(transaction.tenantSubscriptionProduct.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ subscriptionProductId: "product_1", planCode: "starter", seatQuantity: 5, quantity: 5 }),
})
@@ -207,6 +317,10 @@ describe("setTenantBillingPlanSeats", () => {
describe("requestManualBillingSync", () => {
it("refreshes Lago state directly and audits it", async () => {
const deps = createDeps();
vi.mocked(deps.resolveBillingState).mockImplementationOnce(async (tenantId) => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
return createDeps().resolveBillingState(tenantId);
});
await requestManualBillingSync({ tenantId: "tenant_1", provider: "lago", actorUserId: "user_1" }, deps);
@@ -221,7 +335,7 @@ describe("requestManualBillingSync", () => {
planCode: "starter",
seatQuantity: 3,
status: "active",
}),
})
);
expect(deps.clearSubscriptionCache).toHaveBeenCalledWith("tenant_1");
expect(deps.invalidateModuleCache).toHaveBeenCalledWith("tenant_1");
@@ -242,7 +356,7 @@ describe("requestManualBillingSync", () => {
paymentExternalId: "pay_1",
invoiceExternalId: "inv_1",
status: "paid",
}),
})
);
expect(deps.recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "subscription.syncRequested", reason: "manual-mollie-sync" }));
});
@@ -261,3 +375,111 @@ describe("requestManualBillingSync", () => {
expect(deps.mollieGateway?.getPayment).not.toHaveBeenCalled();
});
});
describe("extendTenantTrial", () => {
it("extends from the future trial end, clears dunning state, and audits the reason", async () => {
const deps = createDeps();
const db = deps.db as unknown as {
tenantSubscription: { findUnique: ReturnType<typeof vi.fn>; upsert: ReturnType<typeof vi.fn> };
};
// Current trial ends 2026-07-10, "now" is 2026-07-04 -> extension bases on the trial end.
db.tenantSubscription.findUnique.mockResolvedValueOnce({
id: "sub_1",
status: "trial",
trialEndsAt: new Date("2026-07-10T00:00:00.000Z"),
pastDueSince: null,
frozenAt: null,
});
await extendTenantTrial({ tenantId: "tenant_1", days: 14, reason: "Kunde testet noch", actorUserId: "admin_1", actorEmail: "op@example.test" }, deps);
expect(db.tenantSubscription.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { tenantId: "tenant_1" },
update: expect.objectContaining({
status: "trial",
trialEndsAt: new Date("2026-07-24T00:00:00.000Z"),
pastDueSince: null,
frozenAt: null,
}),
})
);
expect(deps.clearSubscriptionCache).toHaveBeenCalledWith("tenant_1");
expect(deps.invalidateModuleCache).toHaveBeenCalledWith("tenant_1");
expect(deps.recordAction).toHaveBeenCalledWith(
expect.objectContaining({
action: "tenant.trialExtended",
targetId: "tenant_1",
reason: "Kunde testet noch",
after: expect.objectContaining({ status: "trial", extendedByDays: 14 }),
})
);
});
it("bases the extension on now when the previous trial already expired (never backwards)", async () => {
const deps = createDeps();
const db = deps.db as unknown as {
tenantSubscription: { findUnique: ReturnType<typeof vi.fn>; upsert: ReturnType<typeof vi.fn> };
};
db.tenantSubscription.findUnique.mockResolvedValueOnce({
id: "sub_1",
status: "past_due",
trialEndsAt: new Date("2026-06-01T00:00:00.000Z"),
pastDueSince: new Date("2026-06-15T00:00:00.000Z"),
frozenAt: new Date("2026-06-20T00:00:00.000Z"),
});
await extendTenantTrial({ tenantId: "tenant_1", days: 7, reason: "Zahlung geklaert", actorUserId: "admin_1" }, deps);
expect(db.tenantSubscription.upsert).toHaveBeenCalledWith(
expect.objectContaining({
update: expect.objectContaining({
trialEndsAt: new Date("2026-07-11T00:00:00.000Z"),
pastDueSince: null,
frozenAt: null,
}),
})
);
});
it("rejects out-of-range day counts before writing", async () => {
const deps = createDeps();
await expect(extendTenantTrial({ tenantId: "tenant_1", days: 0, reason: "Kunde testet noch", actorUserId: "admin_1" }, deps)).rejects.toMatchObject({
code: "INVALID_TRIAL_DAYS",
});
await expect(extendTenantTrial({ tenantId: "tenant_1", days: 366, reason: "Kunde testet noch", actorUserId: "admin_1" }, deps)).rejects.toMatchObject({
code: "INVALID_TRIAL_DAYS",
});
const db = deps.db as unknown as { tenantSubscription: { upsert: ReturnType<typeof vi.fn> } };
expect(db.tenantSubscription.upsert).not.toHaveBeenCalled();
expect(deps.recordAction).not.toHaveBeenCalled();
});
it("binds the tenant RLS context for the whole write", async () => {
const deps = createDeps();
let observedTenantId: string | null | undefined;
const db = deps.db as unknown as { tenantSubscription: { upsert: ReturnType<typeof vi.fn> } };
db.tenantSubscription.upsert.mockImplementationOnce(async () => {
observedTenantId = getRlsExecutionContext()?.tenantId;
return { id: "sub_1" };
});
await extendTenantTrial({ tenantId: "tenant_1", days: 3, reason: "Kunde testet noch", actorUserId: "admin_1" }, deps);
expect(observedTenantId).toBe("tenant_1");
});
});
describe("trial extension helpers", () => {
it("normalizes numeric strings and rejects garbage", () => {
expect(normalizeTrialExtensionDays("30")).toBe(30);
expect(() => normalizeTrialExtensionDays("abc")).toThrow(AdminBillingError);
expect(() => normalizeTrialExtensionDays(2.5)).toThrow(AdminBillingError);
});
it("never moves the trial end backwards", () => {
const now = new Date("2026-07-04T00:00:00.000Z");
expect(resolveExtendedTrialEnd(new Date("2026-01-01T00:00:00.000Z"), now, 1)).toEqual(new Date("2026-07-05T00:00:00.000Z"));
expect(resolveExtendedTrialEnd(null, now, 1)).toEqual(new Date("2026-07-05T00:00:00.000Z"));
});
});
@@ -1,8 +1,14 @@
import { createLagoBillingGateway, createMolliePaymentGateway, type BillingGateway, type PaymentGateway } from "@hivegrid/billing";
import { loadWebConfig } from "@hivegrid/config";
import { resolveTenantBillingState } from "@hivegrid/db/billing-domain.server";
import { resolveTenantBillingState, resolveTenantBillingStates } from "@hivegrid/db/billing-domain.server";
import { applyLagoSubscriptionSync, applyMolliePaymentSync } from "@hivegrid/db/billing-sync.server";
import {
acquirePortalDomainBillingActivationLocks,
reactivateEntitledPortalDomains,
type PortalDomainBillingFenceClient,
} from "@hivegrid/db/portal-domain-billing-fence.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type { AdminBillingInputRow } from "@hivegrid/view-models";
import { db } from "~/utils/db.server";
import { invalidateTenantModuleAccessCache } from "~/utils/connector/tenantConnector.server";
@@ -15,7 +21,7 @@ export class AdminBillingError extends Error {
override readonly name = "AdminBillingError";
readonly i18nKey: string;
constructor(readonly code: "TENANT_NOT_FOUND" | "MISSING_PROVIDER_REFERENCE" | "INVALID_PLAN" | "INVALID_SEATS") {
constructor(readonly code: "TENANT_NOT_FOUND" | "MISSING_PROVIDER_REFERENCE" | "INVALID_PLAN" | "INVALID_SEATS" | "INVALID_TRIAL_DAYS") {
super(code);
this.i18nKey = `admin.billing.errors.${code}`;
}
@@ -30,6 +36,7 @@ type TenantSummary = {
export type AdminBillingDeps = {
readonly db: typeof db;
readonly resolveBillingState: typeof resolveTenantBillingState;
readonly resolveBillingStates: typeof resolveTenantBillingStates;
readonly invalidateModuleCache: (tenantId: string) => void;
readonly clearSubscriptionCache: (tenantId: string) => void;
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
@@ -64,6 +71,7 @@ function defaultDeps(): AdminBillingDeps {
return {
db,
resolveBillingState: resolveTenantBillingState,
resolveBillingStates: resolveTenantBillingStates,
invalidateModuleCache: invalidateTenantModuleAccessCache,
clearSubscriptionCache: clearTenantSubscriptionCache,
recordAction: recordAdminAction,
@@ -105,30 +113,31 @@ export async function listAdminBillingRows(deps: AdminBillingDeps = defaultDeps(
select: { id: true, name: true, slug: true },
});
return await Promise.all(
tenants.map(async (tenant) => {
const state = await deps.resolveBillingState(tenant.id);
return {
tenantId: tenant.id,
tenantName: tenant.name,
tenantSlug: tenant.slug,
status: state.status,
readOnly: state.readOnly,
planCode: state.planCode,
seatQuantity: state.seatQuantity,
lagoCustomerId: state.lagoCustomerId,
mollieCustomerId: state.mollieCustomerId,
lastInvoiceExternalId: state.lastInvoiceExternalId,
lastPaymentExternalId: state.lastPaymentExternalId,
currentPeriodStart: dateToIso(state.currentPeriodStart),
currentPeriodEnd: dateToIso(state.currentPeriodEnd),
pastDueSince: dateToIso(state.pastDueSince),
frozenAt: dateToIso(state.frozenAt),
cancelledAt: dateToIso(state.cancelledAt),
entitlementCount: state.entitlements.length,
};
})
);
const billingStates = await Promise.all(tenants.map((tenant) => runWithRlsContext({ tenantId: tenant.id }, () => deps.resolveBillingState(tenant.id))));
const billingStatesByTenantId = new Map(billingStates.map((state) => [state.tenantId, state]));
return tenants.map((tenant) => {
const state = billingStatesByTenantId.get(tenant.id);
if (!state) throw new AdminBillingError("TENANT_NOT_FOUND");
return {
tenantId: tenant.id,
tenantName: tenant.name,
tenantSlug: tenant.slug,
status: state.status,
readOnly: state.readOnly,
planCode: state.planCode,
seatQuantity: state.seatQuantity,
lagoCustomerId: state.lagoCustomerId,
mollieCustomerId: state.mollieCustomerId,
lastInvoiceExternalId: state.lastInvoiceExternalId,
lastPaymentExternalId: state.lastPaymentExternalId,
currentPeriodStart: dateToIso(state.currentPeriodStart),
currentPeriodEnd: dateToIso(state.currentPeriodEnd),
pastDueSince: dateToIso(state.pastDueSince),
frozenAt: dateToIso(state.frozenAt),
cancelledAt: dateToIso(state.cancelledAt),
entitlementCount: state.entitlements.length,
};
});
}
export type SetTenantBillingPlanSeatsInput = {
@@ -204,6 +213,10 @@ async function attachMatchingProduct(
}
export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeatsInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => setTenantBillingPlanSeatsInContext(input, deps));
}
async function setTenantBillingPlanSeatsInContext(input: SetTenantBillingPlanSeatsInput, deps: AdminBillingDeps): Promise<void> {
const reason = assertAdminActionReason(input.reason);
const planCode = normalizePlanCode(input.planCode);
const seatQuantity = normalizeSeatQuantity(input.seatQuantity);
@@ -218,6 +231,8 @@ export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeats
const product = await findPlanProduct(planCode, deps);
await deps.db.$transaction(async (tx) => {
const billingFenceClient = tx as unknown as PortalDomainBillingFenceClient;
await acquirePortalDomainBillingActivationLocks(billingFenceClient, { tenantId: tenant.id });
const subscription = await tx.tenantSubscription.upsert({
where: { tenantId: tenant.id },
create: {
@@ -239,6 +254,7 @@ export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeats
if (product) {
await attachMatchingProduct({ subscriptionId: subscription.id, product, planCode, seatQuantity, now }, tx);
}
await reactivateEntitledPortalDomains(billingFenceClient, { tenantId: tenant.id, now });
});
deps.clearSubscriptionCache(tenant.id);
@@ -257,6 +273,99 @@ export async function setTenantBillingPlanSeats(input: SetTenantBillingPlanSeats
});
}
/** Bounds for a single operator-issued trial extension. */
export const TRIAL_EXTENSION_MIN_DAYS = 1;
export const TRIAL_EXTENSION_MAX_DAYS = 365;
export function normalizeTrialExtensionDays(value: number | string | null | undefined): number {
const days = typeof value === "number" ? value : Number.parseInt(value ?? "", 10);
if (!Number.isInteger(days) || days < TRIAL_EXTENSION_MIN_DAYS || days > TRIAL_EXTENSION_MAX_DAYS) {
throw new AdminBillingError("INVALID_TRIAL_DAYS");
}
return days;
}
/**
* Pure date rule for a trial extension: extends from the current trial end
* when it is still in the future, otherwise from now — an extension can
* therefore never move a trial end backwards.
*/
export function resolveExtendedTrialEnd(currentTrialEnd: Date | null | undefined, now: Date, days: number): Date {
const base = currentTrialEnd && currentTrialEnd.getTime() > now.getTime() ? currentTrialEnd : now;
return new Date(base.getTime() + days * 24 * 60 * 60 * 1000);
}
export type ExtendTenantTrialInput = {
readonly tenantId: string;
readonly days: number | string;
readonly reason: string;
readonly actorUserId: string | null;
readonly actorEmail?: string | null;
readonly request?: Request;
};
/**
* Extends a tenant's trial (DoD #3): reason-gated, 1-365 days, never moves
* the trial end backwards, clears past_due/frozen dunning state and puts
* the subscription back onto `trial`. Audited as `tenant.trialExtended`.
*/
export async function extendTenantTrial(input: ExtendTenantTrialInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => extendTenantTrialInContext(input, deps));
}
async function extendTenantTrialInContext(input: ExtendTenantTrialInput, deps: AdminBillingDeps): Promise<void> {
const reason = assertAdminActionReason(input.reason);
const days = normalizeTrialExtensionDays(input.days);
const now = deps.now();
const tenant = requireTenant(
await deps.db.tenant.findUnique({
where: { id: input.tenantId },
select: { id: true, name: true, slug: true },
})
);
const existing = await deps.db.tenantSubscription.findUnique({
where: { tenantId: tenant.id },
select: { id: true, status: true, trialEndsAt: true, pastDueSince: true, frozenAt: true },
});
const trialEndsAt = resolveExtendedTrialEnd(existing?.trialEndsAt, now, days);
await deps.db.tenantSubscription.upsert({
where: { tenantId: tenant.id },
create: {
tenantId: tenant.id,
status: "trial",
trialEndsAt,
},
update: {
status: "trial",
trialEndsAt,
pastDueSince: null,
frozenAt: null,
},
});
deps.clearSubscriptionCache(tenant.id);
deps.invalidateModuleCache(tenant.id);
await deps.recordAction({
action: "tenant.trialExtended",
actorUserId: input.actorUserId,
actorEmail: input.actorEmail ?? null,
targetKind: "tenant",
targetId: tenant.id,
reason,
before: {
status: existing?.status ?? null,
trialEndsAt: existing?.trialEndsAt?.toISOString() ?? null,
pastDueSince: existing?.pastDueSince?.toISOString() ?? null,
frozenAt: existing?.frozenAt?.toISOString() ?? null,
},
after: { status: "trial", trialEndsAt: trialEndsAt.toISOString(), extendedByDays: days },
request: input.request,
});
}
export type RequestManualBillingSyncInput = {
readonly tenantId: string;
readonly provider: BillingSyncProvider;
@@ -265,12 +374,15 @@ export type RequestManualBillingSyncInput = {
readonly request?: Request;
};
async function applyManualProviderSync(input: {
provider: BillingSyncProvider;
tenantId: string;
state: Awaited<ReturnType<typeof resolveTenantBillingState>>;
now: Date;
}, deps: AdminBillingDeps): Promise<Record<string, unknown>> {
async function applyManualProviderSync(
input: {
provider: BillingSyncProvider;
tenantId: string;
state: Awaited<ReturnType<typeof resolveTenantBillingState>>;
now: Date;
},
deps: AdminBillingDeps
): Promise<Record<string, unknown>> {
if (input.provider === "lago") {
if (!deps.lagoGateway) throw new AdminBillingError("MISSING_PROVIDER_REFERENCE");
const [customer, invoices] = await Promise.all([
@@ -321,6 +433,10 @@ async function applyManualProviderSync(input: {
}
export async function requestManualBillingSync(input: RequestManualBillingSyncInput, deps: AdminBillingDeps = defaultDeps()): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => requestManualBillingSyncInContext(input, deps));
}
async function requestManualBillingSyncInContext(input: RequestManualBillingSyncInput, deps: AdminBillingDeps): Promise<void> {
const tenant = requireTenant(
await deps.db.tenant.findUnique({
where: { id: input.tenantId },
@@ -0,0 +1,58 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { buildDeployMetadata, getDeployAdminSnapshot } from "./deploy-admin.server";
describe("admin deploy snapshot service", () => {
it("builds deploy metadata from runtime env", () => {
expect(
buildDeployMetadata({
NODE_ENV: "production",
SENTRY_ENVIRONMENT: "staging",
APP_REVISION: "abc123",
SENTRY_RELEASE: "rel-1",
GIT_BRANCH: "main",
DOCKER_IMAGE: "git.tool-ctrl.de/toolctrl-labs/hivegrid-web:abc123",
BUILD_TIME: "2026-07-09T00:00:00.000Z",
})
).toEqual({
environment: "staging",
nodeEnv: "production",
release: "rel-1",
revision: "abc123",
branch: "main",
image: "git.tool-ctrl.de/toolctrl-labs/hivegrid-web:abc123",
buildTime: "2026-07-09T00:00:00.000Z",
});
});
it("merges repo migrations with applied DB state", async () => {
const snapshot = await getDeployAdminSnapshot({
env: { NODE_ENV: "production", APP_REVISION: "abc123" },
listMigrationNames: () => ["20260701000000_init", "20260702000000_next", "20260703000000_failed"],
listAppliedMigrations: async () => [
{ migration_name: "20260701000000_init", finished_at: new Date("2026-07-01T00:00:00.000Z"), rolled_back_at: null, logs: null },
{ migration_name: "20260703000000_failed", finished_at: null, rolled_back_at: null, logs: "failed" },
],
});
expect(snapshot.migrationDbReachable).toBe(true);
expect(snapshot.migrations.map((migration) => [migration.name, migration.state])).toEqual([
["20260703000000_failed", "failed"],
["20260702000000_next", "pending"],
["20260701000000_init", "applied"],
]);
});
it("falls back to unknown migration state when DB is unreachable", async () => {
const snapshot = await getDeployAdminSnapshot({
env: { NODE_ENV: "development" },
listMigrationNames: () => ["20260701000000_init"],
listAppliedMigrations: async () => {
throw new Error("db unavailable");
},
});
expect(snapshot.migrationDbReachable).toBe(false);
expect(snapshot.migrations).toEqual([{ name: "20260701000000_init", state: "unknown" }]);
});
});
@@ -0,0 +1,122 @@
import fs from "node:fs";
import path from "node:path";
import { getDbClient } from "@hivegrid/db/client.server";
import type { DeployMetadata, DeployMigrationInput, DeploySnapshotInput, MigrationState } from "@hivegrid/view-models";
import { createScopedLogger } from "~/utils/logger.server";
const deployLogger = createScopedLogger("admin-deploys");
type DbMigrationRow = {
readonly migration_name: string;
readonly finished_at: Date | string | null;
readonly rolled_back_at: Date | string | null;
readonly logs: string | null;
};
export type DeploySnapshotDeps = {
readonly env?: NodeJS.ProcessEnv;
readonly listMigrationNames?: () => readonly string[];
readonly listAppliedMigrations?: () => Promise<readonly DbMigrationRow[]>;
};
export async function getDeployAdminSnapshot(deps: DeploySnapshotDeps = {}): Promise<DeploySnapshotInput> {
const env = deps.env ?? process.env;
const listMigrationNames = deps.listMigrationNames ?? defaultListMigrationNames;
const listAppliedMigrations = deps.listAppliedMigrations ?? defaultListAppliedMigrations;
const migrationNames = [...listMigrationNames()].sort();
let migrationDbReachable = true;
let appliedRows: readonly DbMigrationRow[] = [];
try {
appliedRows = await listAppliedMigrations();
} catch (error) {
migrationDbReachable = false;
// The UI can only say "not readable"; without this log the actual cause
// stays invisible. The historical cause was a missing grant on
// `_prisma_migrations` for the non-superuser runtime role, which looks
// exactly like an unreachable database from here.
deployLogger.error(
{
event: "admin_deploys.migration_history_unreadable",
errorName: error instanceof Error ? error.name : "UnknownError",
errorMessage: error instanceof Error ? error.message : undefined,
},
"Applied migration history could not be read; operator view falls back to unknown state"
);
}
return {
metadata: buildDeployMetadata(env),
migrationDbReachable,
migrations: buildMigrationRows({ migrationNames, appliedRows, migrationDbReachable }).slice(-20).reverse(),
};
}
export function buildDeployMetadata(env: NodeJS.ProcessEnv): DeployMetadata {
const revision = firstPresent(env, ["APP_REVISION", "SENTRY_RELEASE", "GIT_SHA", "COMMIT_SHA", "CI_COMMIT_SHA"]) ?? "unknown";
return {
environment: firstPresent(env, ["SENTRY_ENVIRONMENT", "DEPLOY_ENVIRONMENT", "APP_ENV"]) ?? env.NODE_ENV ?? "development",
nodeEnv: env.NODE_ENV ?? "development",
release: firstPresent(env, ["SENTRY_RELEASE", "APP_REVISION", "GIT_SHA", "COMMIT_SHA", "CI_COMMIT_SHA"]) ?? "local",
revision,
branch: firstPresent(env, ["GIT_BRANCH", "BRANCH_NAME", "CI_COMMIT_BRANCH", "GITEA_REF_NAME", "COOLIFY_BRANCH"]) ?? "unknown",
image: firstPresent(env, ["DOCKER_IMAGE", "CONTAINER_IMAGE", "IMAGE_TAG", "DOCKER_IMAGE_TAG", "COOLIFY_IMAGE"]) ?? "unknown",
buildTime: firstPresent(env, ["BUILD_TIME", "BUILD_DATE", "CI_BUILD_CREATED_AT", "SOURCE_DATE_EPOCH"]) ?? "unknown",
};
}
function buildMigrationRows(input: {
readonly migrationNames: readonly string[];
readonly appliedRows: readonly DbMigrationRow[];
readonly migrationDbReachable: boolean;
}): DeployMigrationInput[] {
if (!input.migrationDbReachable) {
return input.migrationNames.map((name) => ({ name, state: "unknown" }));
}
const appliedByName = new Map(input.appliedRows.map((row) => [row.migration_name, row]));
return input.migrationNames.map((name) => {
const row = appliedByName.get(name);
if (!row) {
return { name, state: "pending" };
}
return {
name,
state: migrationStateFromDb(row),
appliedAt: row.finished_at ? new Date(row.finished_at).toISOString() : null,
};
});
}
function migrationStateFromDb(row: DbMigrationRow): MigrationState {
if (row.rolled_back_at) return "rolledBack";
if (!row.finished_at) return "failed";
if (row.logs?.trim()) return "failed";
return "applied";
}
function defaultListMigrationNames(): readonly string[] {
const migrationsRoot = path.resolve(process.cwd(), "prisma/migrations");
if (!fs.existsSync(migrationsRoot)) {
return [];
}
return fs
.readdirSync(migrationsRoot, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name);
}
async function defaultListAppliedMigrations(): Promise<readonly DbMigrationRow[]> {
const db = getDbClient();
return db.$queryRaw<DbMigrationRow[]>`
SELECT migration_name, finished_at, rolled_back_at, logs
FROM "_prisma_migrations"
ORDER BY migration_name ASC
`;
}
function firstPresent(env: NodeJS.ProcessEnv, names: readonly string[]): string | undefined {
return names.map((name) => env[name]?.trim()).find((value): value is string => Boolean(value));
}
@@ -0,0 +1,232 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
featureFlagFindFirst: vi.fn(),
tenantFindMany: vi.fn(),
tenantUserCount: vi.fn(),
tenantSubscriptionFindUnique: vi.fn(),
overrideUpsert: vi.fn(),
featureFlagAuditCreate: vi.fn(),
recordAdminAction: vi.fn(),
runWithRlsContext: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({
db: {
featureFlag: { findFirst: mocks.featureFlagFindFirst },
tenant: { findMany: mocks.tenantFindMany },
tenantUser: { count: mocks.tenantUserCount },
tenantSubscription: { findUnique: mocks.tenantSubscriptionFindUnique },
$transaction: vi.fn(async (operation: (transaction: unknown) => unknown) =>
operation({
featureFlag: { findFirst: mocks.featureFlagFindFirst },
tenant: { findMany: mocks.tenantFindMany },
adminFeatureFlagOverride: { upsert: mocks.overrideUpsert },
featureFlagAudit: { create: mocks.featureFlagAuditCreate },
})
),
},
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: (context: unknown, callback: () => unknown) => mocks.runWithRlsContext(context, callback),
}));
vi.mock("~/services/admin/admin-action-audit.server", () => ({
assertAdminActionReason: (reason: string) => {
const normalized = reason.trim();
if (normalized.length < 5) throw new Error("reason");
return normalized;
},
recordAdminAction: mocks.recordAdminAction,
}));
import {
AdminFeatureFlagRolloutError,
applyAdminFeatureFlagBulkOverride,
getAdminFeatureFlagRolloutView,
normalizeTenantIds,
} from "./feature-flag-rollout.server";
beforeEach(() => {
vi.clearAllMocks();
mocks.runWithRlsContext.mockImplementation((_context: unknown, callback: () => unknown) => callback());
});
describe("admin feature flag rollout preview", () => {
it("bounds tenant hydration concurrency while preserving full deterministic output", async () => {
const tenantIds = Array.from({ length: 6 }, (_, index) => `tenant-${index + 1}`);
const gates = new Map(tenantIds.map((tenantId) => [tenantId, createDeferred()]));
const started: string[] = [];
const completed: string[] = [];
let active = 0;
let maxActive = 0;
mocks.featureFlagFindFirst.mockResolvedValue({
id: "flag-1",
key: "sales_workspace",
name: "Sales Workspace",
description: "Sales Workspace",
defaultValue: false,
enabled: false,
lifecycleStage: "rollout",
filters: [
{
id: "filter-pilot",
name: "Pilot tenants",
priority: 10,
resultValue: true,
active: true,
createdAt: new Date("2026-07-01T00:00:00.000Z"),
criteria: { tenantIdIn: ["tenant-1", "tenant-3", "tenant-6"] },
},
],
tenantOverrides: [{ tenantId: "tenant-2", value: true, expiresAt: null }],
});
mocks.tenantFindMany.mockResolvedValue(
tenantIds.map((id, index) => ({
id,
name: `Tenant ${index + 1}`,
slug: id,
createdAt: new Date(`2026-06-0${index + 1}T00:00:00.000Z`),
active: id !== "tenant-4",
}))
);
mocks.tenantUserCount.mockImplementation(
async (input: { where: { tenantId: string } }) =>
({ "tenant-1": 1, "tenant-2": 11, "tenant-3": 26, "tenant-4": 51, "tenant-5": 101, "tenant-6": 0 })[input.where.tenantId]
);
mocks.tenantSubscriptionFindUnique.mockImplementation(async (input: { where: { tenantId: string } }) => {
await gates.get(input.where.tenantId)!.promise;
return input.where.tenantId === "tenant-1" ? { status: "trialing", products: [{ subscriptionProductId: "product-pro" }] } : null;
});
mocks.runWithRlsContext.mockImplementation(async (context: { tenantId: string }, callback: () => Promise<unknown>) => {
active += 1;
maxActive = Math.max(maxActive, active);
started.push(context.tenantId);
try {
return await callback();
} finally {
active -= 1;
completed.push(context.tenantId);
}
});
const viewPromise = getAdminFeatureFlagRolloutView("sales_workspace", new Date("2026-07-29T00:00:00.000Z"));
await vi.waitFor(() => expect(started).toEqual(["tenant-1", "tenant-2", "tenant-3", "tenant-4"]));
expect(maxActive).toBe(4);
gates.get("tenant-4")!.resolve();
await vi.waitFor(() => expect(started).toEqual(["tenant-1", "tenant-2", "tenant-3", "tenant-4", "tenant-5"]));
gates.get("tenant-2")!.resolve();
await vi.waitFor(() => expect(started).toEqual(["tenant-1", "tenant-2", "tenant-3", "tenant-4", "tenant-5", "tenant-6"]));
for (const gate of gates.values()) gate.resolve();
const view = await viewPromise;
expect(maxActive).toBe(4);
expect(completed.slice(0, 2)).toEqual(["tenant-4", "tenant-2"]);
expect(view?.tenants.map((tenant) => tenant.id)).toEqual(tenantIds);
expect(view?.tenants.map((tenant) => tenant.size)).toEqual(["1-10", "11-25", "26-50", "51-100", "100+", "1-10"]);
expect(view?.tenants[0]).toMatchObject({
status: "trialing",
subscriptionProductIds: ["product-pro"],
});
expect(view?.tenants[3]).toMatchObject({ status: "inactive", subscriptionProductIds: [] });
expect(view?.preview).toEqual({
enabled: 4,
disabled: 2,
overrides: 1,
filtered: 3,
defaulted: 2,
rows: [
{ tenantId: "tenant-1", decision: { value: true, source: "filter", filterId: "filter-pilot" } },
{ tenantId: "tenant-2", decision: { value: true, source: "override", filterId: null } },
{ tenantId: "tenant-3", decision: { value: true, source: "filter", filterId: "filter-pilot" } },
{ tenantId: "tenant-4", decision: { value: false, source: "default", filterId: null } },
{ tenantId: "tenant-5", decision: { value: false, source: "default", filterId: null } },
{ tenantId: "tenant-6", decision: { value: true, source: "filter", filterId: "filter-pilot" } },
],
});
});
});
describe("admin feature flag bulk override input", () => {
it("normalizes, deduplicates and sorts tenant identifiers", () => {
expect(normalizeTenantIds([" tenant-b ", "tenant-a", "tenant-b"])).toEqual(["tenant-a", "tenant-b"]);
});
it("rejects an empty selection and oversized batches", () => {
expect(() => normalizeTenantIds([])).toThrow(AdminFeatureFlagRolloutError);
expect(() => normalizeTenantIds(Array.from({ length: 501 }, (_, index) => `tenant-${index}`))).toThrow(
AdminFeatureFlagRolloutError
);
});
it("persists every override and both append-only audit contracts in one transaction", async () => {
mocks.featureFlagFindFirst.mockResolvedValue({
id: "flag-1",
key: "sales_workspace",
name: "Sales Workspace",
});
mocks.tenantFindMany.mockResolvedValue([{ id: "tenant-a" }, { id: "tenant-b" }]);
await expect(
applyAdminFeatureFlagBulkOverride({
flagKey: "sales_workspace",
tenantIds: ["tenant-b", "tenant-a"],
value: true,
actorAdminUserId: "admin-raffael",
reason: "Pilotgruppe freigeben",
note: "Vertriebspilot",
})
).resolves.toEqual({ updated: 2 });
expect(mocks.overrideUpsert).toHaveBeenCalledTimes(2);
expect(mocks.overrideUpsert.mock.calls.map(([input]) => input.where)).toEqual([
{
admin_feature_flag_override_flag_tenant_key: {
featureFlagId: "flag-1",
tenantId: "tenant-a",
},
},
{
admin_feature_flag_override_flag_tenant_key: {
featureFlagId: "flag-1",
tenantId: "tenant-b",
},
},
]);
expect(mocks.featureFlagAuditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
flagId: "flag-1",
actorUserId: "admin-raffael",
actorType: "admin",
action: "bulk_override",
metadata: {
reason: "Pilotgruppe freigeben",
tenantIds: ["tenant-a", "tenant-b"],
},
}),
});
expect(mocks.recordAdminAction).toHaveBeenCalledWith(
expect.objectContaining({
action: "featureFlag.bulkOverride",
actorUserId: "admin-raffael",
targetKind: "FeatureFlag",
targetId: "flag-1",
reason: "Pilotgruppe freigeben",
}),
expect.any(Object)
);
});
});
function createDeferred(): { readonly promise: Promise<void>; readonly resolve: () => void } {
let resolve!: () => void;
const promise = new Promise<void>((resolvePromise) => {
resolve = resolvePromise;
});
return { promise, resolve };
}
@@ -0,0 +1,265 @@
import {
buildFeatureFlagRolloutPreview,
type FeatureFlagRolloutCriteria,
type FeatureFlagRolloutFilter,
type FeatureFlagRolloutPreview,
type FeatureFlagRolloutTenant,
type FeatureFlagTenantSize,
} from "@hivegrid/feature-flags";
import type { AuditEventWriterClient } from "@hivegrid/db/audit-events.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { assertAdminActionReason, recordAdminAction } from "~/services/admin/admin-action-audit.server";
import { db } from "~/utils/db.server";
const MAX_BULK_OVERRIDE_TENANTS = 500;
const ROLLOUT_PREVIEW_TENANT_CONCURRENCY = 4;
export type AdminFeatureFlagRolloutTenant = FeatureFlagRolloutTenant & {
readonly name: string;
readonly slug: string;
};
export type AdminFeatureFlagRolloutView = {
readonly flag: {
readonly id: string;
readonly key: string;
readonly label: string;
readonly defaultValue: boolean;
readonly lifecycleStage: "beta" | "rollout" | "ga" | "deprecated";
};
readonly tenants: readonly AdminFeatureFlagRolloutTenant[];
readonly preview: FeatureFlagRolloutPreview;
};
export type AdminFeatureFlagBulkOverrideInput = {
readonly flagKey: string;
readonly tenantIds: readonly string[];
readonly value: boolean;
readonly note?: string | null;
readonly expiresAt?: Date | null;
readonly actorAdminUserId: string;
readonly reason: string;
readonly request?: Request;
};
export async function getAdminFeatureFlagRolloutView(flagKey: string, now = new Date()): Promise<AdminFeatureFlagRolloutView | null> {
const normalizedKey = normalizeKey(flagKey);
const flag = await db.featureFlag.findFirst({
where: { OR: [{ key: normalizedKey }, { name: normalizedKey }], archivedAt: null },
include: {
filters: { orderBy: [{ priority: "desc" }, { createdAt: "asc" }, { id: "asc" }] },
tenantOverrides: true,
},
});
if (!flag) return null;
const tenantRows = await db.tenant.findMany({
select: { id: true, name: true, slug: true, createdAt: true, active: true },
orderBy: { id: "asc" },
});
const tenants = await mapWithConcurrency(tenantRows, ROLLOUT_PREVIEW_TENANT_CONCURRENCY, async (tenant): Promise<AdminFeatureFlagRolloutTenant> => {
const details = await runWithRlsContext({ tenantId: tenant.id }, async () => {
const [memberCount, subscription] = await Promise.all([
db.tenantUser.count({ where: { tenantId: tenant.id } }),
db.tenantSubscription.findUnique({
where: { tenantId: tenant.id },
select: {
status: true,
products: { where: { cancelledAt: null }, select: { subscriptionProductId: true } },
},
}),
]);
return { memberCount, subscription };
});
return {
id: tenant.id,
name: tenant.name,
slug: tenant.slug,
createdAt: tenant.createdAt.toISOString(),
size: toTenantSize(details.memberCount),
industry: null,
status: details.subscription?.status ?? (tenant.active ? "active" : "inactive"),
subscriptionProductIds: details.subscription?.products.map((product) => product.subscriptionProductId) ?? [],
};
});
const filters: FeatureFlagRolloutFilter[] = flag.filters
.filter((filter) => filter.resultValue !== null)
.map((filter) => ({
id: filter.id,
name: filter.name,
priority: filter.priority,
value: filter.resultValue ?? false,
active: filter.active,
createdAt: filter.createdAt.toISOString(),
criteria: normalizeCriteria(filter.criteria),
}));
const overrides = flag.tenantOverrides.map((override) => ({
tenantId: override.tenantId,
value: override.value,
expiresAt: override.expiresAt?.toISOString() ?? null,
}));
return {
flag: {
id: flag.id,
key: flag.key ?? flag.name,
label: flag.description,
defaultValue: flag.defaultValue ?? flag.enabled,
lifecycleStage: flag.lifecycleStage,
},
tenants,
preview: buildFeatureFlagRolloutPreview({
tenants,
defaultValue: flag.defaultValue ?? flag.enabled,
filters,
overrides,
now,
}),
};
}
export async function applyAdminFeatureFlagBulkOverride(input: AdminFeatureFlagBulkOverrideInput): Promise<{ updated: number }> {
const reason = assertAdminActionReason(input.reason);
const flagKey = normalizeKey(input.flagKey);
const actorAdminUserId = normalizeIdentifier(input.actorAdminUserId, "actorAdminUserId");
const tenantIds = normalizeTenantIds(input.tenantIds);
const note = normalizeOptionalText(input.note, 1_000);
const expiresAt = normalizeExpiry(input.expiresAt);
return db.$transaction(async (transaction) => {
const flag = await transaction.featureFlag.findFirst({
where: { OR: [{ key: flagKey }, { name: flagKey }], archivedAt: null },
select: { id: true, key: true, name: true },
});
if (!flag) throw new AdminFeatureFlagRolloutError("FLAG_NOT_FOUND");
const tenants = await transaction.tenant.findMany({ where: { id: { in: tenantIds } }, select: { id: true } });
if (tenants.length !== tenantIds.length) throw new AdminFeatureFlagRolloutError("TENANT_NOT_FOUND");
const now = new Date();
for (const tenantId of tenantIds) {
await transaction.adminFeatureFlagOverride.upsert({
where: { admin_feature_flag_override_flag_tenant_key: { featureFlagId: flag.id, tenantId } },
create: { featureFlagId: flag.id, tenantId, value: input.value, note, expiresAt, setByAdminUserId: actorAdminUserId },
update: { value: input.value, note, expiresAt, setByAdminUserId: actorAdminUserId },
});
}
await transaction.featureFlagAudit.create({
data: {
flagId: flag.id,
actorUserId: actorAdminUserId,
actorType: "admin",
action: "bulk_override",
newValue: { value: input.value, tenantCount: tenantIds.length, expiresAt: expiresAt?.toISOString() ?? null },
metadata: { reason, tenantIds },
createdAt: now,
},
});
await recordAdminAction(
{
action: "featureFlag.bulkOverride",
actorUserId: actorAdminUserId,
targetKind: "FeatureFlag",
targetId: flag.id,
reason,
request: input.request,
after: { value: input.value, tenantCount: tenantIds.length, expiresAt: expiresAt?.toISOString() ?? null },
},
transaction as unknown as AuditEventWriterClient
);
return { updated: tenantIds.length };
});
}
export class AdminFeatureFlagRolloutError extends Error {
public override readonly name = "AdminFeatureFlagRolloutError";
public constructor(public readonly code: "FLAG_NOT_FOUND" | "TENANT_NOT_FOUND" | "INVALID_INPUT") {
super(code);
}
}
export function normalizeTenantIds(values: readonly string[]): string[] {
const normalized = [...new Set(values.map((value) => normalizeIdentifier(value, "tenantId")))].sort();
if (normalized.length === 0 || normalized.length > MAX_BULK_OVERRIDE_TENANTS) {
throw new AdminFeatureFlagRolloutError("INVALID_INPUT");
}
return normalized;
}
function normalizeCriteria(value: Prisma.JsonValue | null): FeatureFlagRolloutCriteria {
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
const criteria = value as Record<string, unknown>;
return {
...(isTenantSize(criteria.tenantSize) ? { tenantSize: criteria.tenantSize } : {}),
...(typeof criteria.tenantIndustry === "string" ? { tenantIndustry: criteria.tenantIndustry } : {}),
...(typeof criteria.tenantStatus === "string" ? { tenantStatus: criteria.tenantStatus } : {}),
...(typeof criteria.subscriptionProductId === "string" ? { subscriptionProductId: criteria.subscriptionProductId } : {}),
...(typeof criteria.tenantCreatedAfter === "string" ? { tenantCreatedAfter: criteria.tenantCreatedAfter } : {}),
...(typeof criteria.tenantCreatedBefore === "string" ? { tenantCreatedBefore: criteria.tenantCreatedBefore } : {}),
...(isStringArray(criteria.tenantIdIn) ? { tenantIdIn: criteria.tenantIdIn } : {}),
...(isStringArray(criteria.tenantIdNotIn) ? { tenantIdNotIn: criteria.tenantIdNotIn } : {}),
};
}
function toTenantSize(count: number): FeatureFlagTenantSize {
if (count <= 10) return "1-10";
if (count <= 25) return "11-25";
if (count <= 50) return "26-50";
if (count <= 100) return "51-100";
return "100+";
}
function isTenantSize(value: unknown): value is FeatureFlagTenantSize {
return value === "1-10" || value === "11-25" || value === "26-50" || value === "51-100" || value === "100+";
}
function isStringArray(value: unknown): value is string[] {
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
}
function normalizeKey(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_.-]{1,191}$/u.test(normalized)) throw new AdminFeatureFlagRolloutError("INVALID_INPUT");
return normalized;
}
function normalizeIdentifier(value: string, name: string): string {
const normalized = value.trim();
if (!normalized || normalized.length > 191 || normalized.includes("\u0000")) {
throw new AdminFeatureFlagRolloutError("INVALID_INPUT");
}
void name;
return normalized;
}
function normalizeOptionalText(value: string | null | undefined, maxLength: number): string | null {
if (value === null || value === undefined) return null;
const normalized = value.trim();
if (!normalized) return null;
if (normalized.length > maxLength) throw new AdminFeatureFlagRolloutError("INVALID_INPUT");
return normalized;
}
function normalizeExpiry(value: Date | null | undefined): Date | null {
if (value === null || value === undefined) return null;
if (!Number.isFinite(value.getTime())) throw new AdminFeatureFlagRolloutError("INVALID_INPUT");
return value;
}
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,98 @@
import { getDbClient } from "@hivegrid/db/client.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type {
KwpContractAlarmInput,
KwpContractDiffVM,
} from "@hivegrid/view-models";
import { KWP_PROJECT_CAPABILITY } from "@hivegrid/integrations/kwp-resource-client.server";
const MAX_DIFF_PATHS = 100;
function redactedDiff(value: unknown): KwpContractDiffVM | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const diff = (value as Record<string, unknown>).diff;
if (!diff || typeof diff !== "object" || Array.isArray(diff)) return null;
const row = diff as Record<string, unknown>;
const paths = (key: string) => Array.isArray(row[key])
? row[key]!.filter((item): item is string => typeof item === "string").slice(0, MAX_DIFF_PATHS)
: [];
return {
added: paths("added"),
removed: paths("removed"),
changed: paths("changed"),
truncated: row.truncated === true,
};
}
export async function getKwpContractAdminSnapshot(
actorUserId: string,
): Promise<readonly KwpContractAlarmInput[]> {
return runWithRlsContext({ userId: actorUserId }, async () => {
const db = getDbClient();
const states = await db.kwpCapabilityState.findMany({
where: { capability: KWP_PROJECT_CAPABILITY, status: "paused" },
orderBy: [{ pausedAt: "desc" }, { updatedAt: "desc" }],
take: 200,
});
if (states.length === 0) return [];
const tenantIds = [...new Set(states.map((row) => row.tenantId))];
const connectionPairs = states.map((row) => ({
tenantId: row.tenantId,
dataConnectionId: row.dataConnectionId,
}));
const [tenants, reports, snapshots] = await Promise.all([
db.tenant.findMany({
where: { id: { in: tenantIds } },
select: { id: true, name: true },
}),
db.kwpErrorReport.findMany({
where: {
capability: KWP_PROJECT_CAPABILITY,
resolvedAt: null,
OR: connectionPairs,
},
orderBy: { createdAt: "desc" },
}),
db.kwpApiContractSnapshot.findMany({
where: {
capability: KWP_PROJECT_CAPABILITY,
OR: connectionPairs,
},
orderBy: { validatedAt: "desc" },
}),
]);
const tenantNames = new Map(tenants.map((row) => [row.id, row.name]));
const pairKey = (tenantId: string, connectionId: string) => `${tenantId}\u0000${connectionId}`;
const latestReports = new Map<string, (typeof reports)[number]>();
for (const report of reports) {
const key = pairKey(report.tenantId, report.dataConnectionId);
if (!latestReports.has(key)) latestReports.set(key, report);
}
const latestSnapshots = new Map<string, (typeof snapshots)[number]>();
for (const snapshot of snapshots) {
const key = pairKey(snapshot.tenantId, snapshot.dataConnectionId);
if (!latestSnapshots.has(key)) latestSnapshots.set(key, snapshot);
}
return states.map((state) => {
const key = pairKey(state.tenantId, state.dataConnectionId);
const report = latestReports.get(key);
const snapshot = latestSnapshots.get(key);
return {
id: state.id,
tenantId: state.tenantId,
tenantName: tenantNames.get(state.tenantId) ?? state.tenantId,
connectionId: state.dataConnectionId,
reasonCode: state.reasonCode,
observedFingerprint: state.observedFingerprint,
adapterRevision: state.adapterRevision,
capabilityRevision: state.revision,
pausedAt: state.pausedAt?.toISOString() ?? null,
lastCheckedAt: state.lastCheckedAt?.toISOString() ?? null,
lastValidatedAt: snapshot?.validatedAt.toISOString() ?? null,
diff: redactedDiff(report?.redactedDetails),
};
});
});
}
@@ -0,0 +1,130 @@
/**
* Welle 4 · Deliverable 2 — Operator health aggregator.
*
* Composes the EXISTING admin snapshots (system-health, deploy, queue-monitor)
* plus a small `BillingWebhookLog` error read into the pure
* {@link buildOperatorHealthVM} input. Nothing here re-implements a snapshot;
* each source stays the single owner of its own diagnostics. Every source is
* wrapped defensively so one unreachable dependency (e.g. Redis down) degrades
* its own subsystem to `unknown`/`critical` instead of breaking the page.
*/
import {
buildDeployAdminVM,
buildQueueMonitorVM,
buildSystemHealthVM,
type OperatorHealthBillingError,
type OperatorHealthInput,
type OperatorHealthStatus,
type QueueCountsInput,
} from "@hivegrid/view-models";
import { db } from "~/utils/db.server";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { getDeployAdminSnapshot } from "./deploy-admin.server";
import { getQueueMonitorSnapshot } from "./queue-monitor.server";
import { getSystemHealthSnapshot } from "./system-health.server";
const BILLING_ERROR_MESSAGE_MAX = 500;
const RECENT_BILLING_ERROR_LIMIT = 5;
export type OperatorHealthDeps = {
readonly loadBillingWebhookErrors?: () => Promise<readonly OperatorHealthBillingError[]>;
readonly countWebhookFailures?: () => Promise<number>;
};
/** Maps the queue-monitor signal (ok/warn/paused) to the health status. */
function queueSignalToStatus(signal: "ok" | "warn" | "paused"): OperatorHealthStatus {
return signal === "ok" ? "ok" : "warning";
}
async function defaultLoadBillingWebhookErrors(): Promise<readonly OperatorHealthBillingError[]> {
const rows = await db.billingWebhookLog.findMany({
where: { error: { not: null } },
orderBy: { createdAt: "desc" },
take: RECENT_BILLING_ERROR_LIMIT,
select: { id: true, eventType: true, error: true, createdAt: true, relatedTenantId: true },
});
return rows.map((row) => ({
id: row.id,
eventType: row.eventType,
error: (row.error ?? "").slice(0, BILLING_ERROR_MESSAGE_MAX),
createdAt: row.createdAt.toISOString(),
relatedTenantId: row.relatedTenantId,
}));
}
async function defaultCountWebhookFailures(): Promise<number> {
return db.eventWebhookAttempt.count({ where: { success: false } });
}
export async function getOperatorHealthSnapshot(deps: OperatorHealthDeps = {}): Promise<OperatorHealthInput> {
const loadBillingWebhookErrors = deps.loadBillingWebhookErrors ?? defaultLoadBillingWebhookErrors;
const countWebhookFailures = deps.countWebhookFailures ?? defaultCountWebhookFailures;
// System health — self-contained, pings Postgres internally.
const systemVm = buildSystemHealthVM(await getSystemHealthSnapshot());
const systemStatus: OperatorHealthStatus = systemVm.status === "ready" ? systemVm.data.overallStatus : "unknown";
// Deploy / migrations — self-contained, catches migration-DB failures.
const deployVm = buildDeployAdminVM(await getDeployAdminSnapshot());
const deployStatus: OperatorHealthStatus = deployVm.status === "ready" ? deployVm.data.overallStatus : "unknown";
const deployMeta = deployVm.status === "ready" ? deployVm.data.metadata : null;
// Queues — requires Redis; a missing connection throws synchronously.
let queues: QueueCountsInput[] = [];
let queuesReachable = true;
try {
queues = await getQueueMonitorSnapshot();
} catch {
queuesReachable = false;
}
const queueVm = buildQueueMonitorVM({ queues });
const failedJobsTotal = queueVm.status === "ready" ? queueVm.data.failedTotal : 0;
const pausedQueues = queueVm.status === "ready" ? queueVm.data.pausedCount : 0;
const queuesStatus: OperatorHealthStatus = !queuesReachable ? "unknown" : queueVm.status === "ready" ? queueSignalToStatus(queueVm.data.overallSignal) : "ok";
// Webhook delivery failures (eventWebhookAttempt).
let webhookFailures = 0;
try {
webhookFailures = await countWebhookFailures();
} catch {
webhookFailures = 0;
}
const webhooksStatus: OperatorHealthStatus = webhookFailures > 0 ? "warning" : "ok";
// Billing sync failures (BillingWebhookLog.error) — previously invisible.
let billingErrors: readonly OperatorHealthBillingError[] = [];
try {
billingErrors = await loadBillingWebhookErrors();
} catch {
billingErrors = [];
}
const billingStatus: OperatorHealthStatus = billingErrors.length > 0 ? "warning" : "ok";
return {
subsystems: [
{ id: "system", status: systemStatus, href: adminPath("system/health", { mode: "host-aware" }) },
{ id: "deploy", status: deployStatus, href: adminPath("system/deploys", { mode: "host-aware" }) },
{ id: "queues", status: queuesStatus, href: adminPath("system/jobs", { mode: "host-aware" }) },
{ id: "webhooks", status: webhooksStatus, href: adminPath("system/webhooks", { mode: "host-aware" }) },
{ id: "billing", status: billingStatus, href: adminPath("system/billing", { mode: "host-aware" }) },
],
deploy: {
environment: deployMeta?.environment ?? "unknown",
release: deployMeta?.release ?? "unknown",
revision: deployMeta?.revision ?? "unknown",
branch: deployMeta?.branch ?? "unknown",
},
signals: {
failedJobsTotal,
pausedQueues,
webhookFailures,
billingErrors: billingErrors.length,
},
links: {
jobs: adminPath("system/jobs", { mode: "host-aware" }),
webhooks: adminPath("system/webhooks", { mode: "host-aware" }),
billing: adminPath("system/billing", { mode: "host-aware" }),
},
billingErrors,
};
}
@@ -0,0 +1,156 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
createService: vi.fn(() => ({ marker: "service" })),
getPermissions: vi.fn<() => Promise<string[]>>(),
getUserInfo: vi.fn(),
rlsContexts: [] as { userId?: string; tenantId?: string }[],
operatorFind: vi.fn(),
operatorList: vi.fn(),
}));
vi.mock("@hivegrid/db/platform-leads-admin.server", () => ({
createPrismaPlatformLeadService: mocks.createService,
}));
vi.mock("@hivegrid/db/rls-context.server", () => ({
runWithRlsContext: async <T>(context: { userId?: string; tenantId?: string }, callback: () => Promise<T>) => {
mocks.rlsContexts.push(context);
return callback();
},
}));
vi.mock("~/utils/db.server", () => ({
db: {
adminUser: {
findUnique: mocks.operatorFind,
findMany: mocks.operatorList,
},
},
}));
vi.mock("@hivegrid/db/admin-rbac.server", () => ({ listAdminPermissionNames: mocks.getPermissions }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: mocks.getUserInfo }));
vi.mock("~/utils/audit/withAuditContext", () => ({
extractWebActorIp: () => "203.0.113.8",
extractWebActorUserAgent: () => "test-agent",
extractWebRequestId: () => "request_1",
}));
import {
assertPlatformLeadVisibleToOperator,
listPlatformLeadAssignees,
requirePlatformLeadAdmin,
requirePlatformLeadRead,
requirePlatformLeadWrite,
runAsPlatformLeadOperator,
} from "./platform-leads.server";
async function expectNotFound(work: () => unknown | Promise<unknown>) {
try {
await work();
throw new Error("Expected a 404 Response");
} catch (error) {
expect(error).toBeInstanceOf(Response);
expect((error as Response).status).toBe(404);
}
}
describe("platform lead admin boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.rlsContexts.length = 0;
mocks.getUserInfo.mockResolvedValue({ userId: "operator_1" });
mocks.operatorFind.mockResolvedValue({ id: "operator_1", email: "operator@example.test", status: "active" });
mocks.getPermissions.mockResolvedValue([
"admin_sales.crm.read",
"admin_sales.crm.read_all",
"admin_sales.crm.write",
"admin_sales.crm.write_all",
"admin_sales.crm.assign",
"admin_sales.communication.read_all",
]);
});
it("returns 404 before touching the database for an unauthenticated request", async () => {
mocks.getUserInfo.mockResolvedValue({ userId: null });
await expectNotFound(() => runAsPlatformLeadOperator(new Request("https://admin.example.test/leads"), async () => null));
expect(mocks.operatorFind).not.toHaveBeenCalled();
});
it("revalidates AdminUser and keeps the whole callback inside user-bound RLS", async () => {
const result = await runAsPlatformLeadOperator(new Request("https://admin.example.test/leads"), async ({ access, service }) => {
expect(service).toEqual({ marker: "service" });
expect(access).toMatchObject({
actorAdminUserId: "operator_1",
canReadOwn: true,
canReadAll: true,
canWrite: true,
canAdmin: true,
});
expect(access.audit("A useful audit reason")).toEqual({
actorAdminUserId: "operator_1",
actorEmail: "operator@example.test",
actorIp: "203.0.113.8",
actorUserAgent: "test-agent",
requestId: "request_1",
reason: "A useful audit reason",
});
return "ok";
});
expect(result).toBe("ok");
expect(mocks.rlsContexts).toEqual([{ userId: "operator_1" }]);
expect(mocks.getPermissions).toHaveBeenCalledWith("operator_1");
expect(mocks.createService).toHaveBeenCalledWith(
expect.anything(),
{
adminUserId: "operator_1",
canReadAll: true,
canWriteAll: true,
canReadAllCommunication: true,
}
);
});
it("hides the surface when the bound user is not a platform operator", async () => {
mocks.operatorFind.mockResolvedValue(null);
await expectNotFound(() => runAsPlatformLeadOperator(new Request("https://admin.example.test/leads"), async () => null));
});
it("enforces read, write, admin and read-own visibility as 404", async () => {
const base = {
actorAdminUserId: "operator_1",
actorEmail: "operator@example.test",
canReadOwn: false,
canReadAll: false,
canWrite: false,
canAdmin: false,
audit: vi.fn(),
};
await expectNotFound(() => requirePlatformLeadRead(base));
await expectNotFound(() => requirePlatformLeadWrite({ ...base, canReadOwn: true }));
await expectNotFound(() => requirePlatformLeadAdmin({ ...base, canReadOwn: true }));
await expectNotFound(() => assertPlatformLeadVisibleToOperator({ assignedToAdminUserId: "operator_2" }, { ...base, canReadOwn: true }));
expect(() => assertPlatformLeadVisibleToOperator({ assignedToAdminUserId: "operator_2" }, { ...base, canReadAll: true })).not.toThrow();
});
it("exposes only operator ids and safe display labels to the VM layer", async () => {
mocks.operatorList.mockResolvedValue([
{ id: "operator_1", firstName: "Ada", lastName: "Lovelace", email: "ada@example.test" },
{ id: "operator_2", firstName: "", lastName: "", email: "fallback@example.test" },
]);
await expect(listPlatformLeadAssignees()).resolves.toEqual([
{ id: "operator_1", label: "Ada Lovelace" },
{ id: "operator_2", label: "fallback@example.test" },
]);
expect(mocks.operatorList).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
status: "active",
roles: expect.objectContaining({ some: expect.any(Object) }),
}),
})
);
});
});
@@ -0,0 +1,170 @@
import { createPrismaPlatformLeadService, type PlatformLeadService } from "@hivegrid/db/platform-leads-admin.server";
import {
createAdminSalesLeadService,
createPrismaAdminSalesLeadRepository,
} from "@hivegrid/db/admin-sales-leads.server";
import type { AdminPermissionName } from "@hivegrid/db/admin-permissions";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
import { extractWebActorIp, extractWebActorUserAgent, extractWebRequestId } from "~/utils/audit/withAuditContext";
import { db } from "~/utils/db.server";
import { getUserInfo } from "~/utils/session.server";
export const PLATFORM_LEAD_PERMISSIONS = Object.freeze({
readOwn: "admin_sales.crm.read",
readAll: "admin_sales.crm.read_all",
write: "admin_sales.crm.write",
writeAll: "admin_sales.crm.write_all",
admin: "admin_sales.crm.assign",
merge: "admin_sales.crm.merge",
} as const);
export type PlatformLeadOperatorAccess = {
readonly actorAdminUserId: string;
readonly actorEmail: string;
readonly canReadOwn: boolean;
readonly canReadAll: boolean;
readonly canWrite: boolean;
readonly canAdmin: boolean;
readonly canMerge: boolean;
readonly audit: (reason: string) => {
actorAdminUserId: string;
actorEmail: string;
actorIp: string | null;
actorUserAgent: string | null;
requestId: string | null;
reason: string;
};
};
export type PlatformLeadOperatorContext = {
readonly access: PlatformLeadOperatorAccess;
readonly service: PlatformLeadService;
readonly advancedService: ReturnType<typeof createAdminSalesLeadService>;
};
export type PlatformLeadAssigneeOption = {
readonly id: string;
readonly label: string;
};
export function platformLeadNotFound(): Response {
return new Response("Not Found", { status: 404 });
}
export function requirePlatformLeadRead(access: PlatformLeadOperatorAccess): void {
if (!access.canReadOwn && !access.canReadAll) throw platformLeadNotFound();
}
export function requirePlatformLeadWrite(access: PlatformLeadOperatorAccess): void {
requirePlatformLeadRead(access);
if (!access.canWrite) throw platformLeadNotFound();
}
export function requirePlatformLeadAdmin(access: PlatformLeadOperatorAccess): void {
requirePlatformLeadRead(access);
if (!access.canAdmin) throw platformLeadNotFound();
}
/**
* Binds the current operator identity for the complete read/write callback.
* This is deliberately callback-based: returning a client after the callback
* would lose the transaction-local RLS identity on staging and production.
*/
export async function runAsPlatformLeadOperator<T>(request: Request, callback: (context: PlatformLeadOperatorContext) => Promise<T>): Promise<T> {
const session = await getUserInfo(request);
if (!session.userId) throw platformLeadNotFound();
return runWithRlsContext({ userId: session.userId }, async () => {
const operator = await db.adminUser.findUnique({
where: { id: session.userId },
select: { id: true, email: true, status: true },
});
if (!operator || operator.status !== "active") throw platformLeadNotFound();
const permissionNames = new Set(await listAdminPermissionNames(operator.id));
const auditBase = {
actorAdminUserId: operator.id,
actorEmail: operator.email,
actorIp: extractWebActorIp(request),
actorUserAgent: extractWebActorUserAgent(request),
requestId: extractWebRequestId(request),
};
const access: PlatformLeadOperatorAccess = {
actorAdminUserId: operator.id,
actorEmail: operator.email,
canReadOwn: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.readOwn),
canReadAll: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.readAll),
canWrite: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.write),
canAdmin: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.admin),
canMerge: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.merge),
audit: (reason) => ({ ...auditBase, reason }),
};
const authorize = (permission: AdminPermissionName) => {
if (!permissionNames.has(permission)) throw platformLeadNotFound();
};
return callback({
access,
service: createPrismaPlatformLeadService(db, {
adminUserId: operator.id,
canReadAll: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.readAll),
canWriteAll: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.writeAll),
canReadAllCommunication: permissionNames.has(
"admin_sales.communication.read_all"
),
}),
advancedService: createAdminSalesLeadService({
repository: createPrismaAdminSalesLeadRepository(db, {
accessScope: {
adminUserId: operator.id,
canReadAll: permissionNames.has(PLATFORM_LEAD_PERMISSIONS.readAll),
canWriteAll: permissionNames.has(
PLATFORM_LEAD_PERMISSIONS.writeAll
),
canReadAllCommunication: permissionNames.has(
"admin_sales.communication.read_all"
),
},
}),
authorize,
}),
});
});
}
export async function listPlatformLeadAssignees(): Promise<PlatformLeadAssigneeOption[]> {
const operators = await db.adminUser.findMany({
where: {
status: "active",
roles: {
some: {
role: {
active: true,
permissions: {
some: {
permission: {
name: PLATFORM_LEAD_PERMISSIONS.readOwn,
},
},
},
},
},
},
},
orderBy: [{ firstName: "asc" }, { lastName: "asc" }, { id: "asc" }],
select: { id: true, firstName: true, lastName: true, email: true },
});
return operators.map((operator) => ({
id: operator.id,
label: [operator.firstName, operator.lastName].filter(Boolean).join(" ").trim() || operator.email,
}));
}
export function assertPlatformLeadVisibleToOperator(lead: { readonly assignedToAdminUserId: string | null }, access: PlatformLeadOperatorAccess): void {
requirePlatformLeadRead(access);
if (!access.canReadAll && lead.assignedToAdminUserId !== access.actorAdminUserId) {
throw platformLeadNotFound();
}
}
@@ -0,0 +1,95 @@
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AdminActionInputError } from "./admin-action-audit.server";
import {
PORTAL_DOMAIN_KILL_SWITCH_PERMISSION,
PortalDomainOperatorError,
setOperatorPortalDomainKillSwitch,
type PortalDomainOperatorDependencies,
} from "./portal-domain-operator.server";
describe("portal-domain operator kill switch", () => {
const findOperator = vi.fn();
const getPermissions = vi.fn();
const setKillSwitch = vi.fn();
const dependencies = {
findOperator,
getPermissions,
setKillSwitch,
} as unknown as PortalDomainOperatorDependencies;
beforeEach(() => {
vi.clearAllMocks();
findOperator.mockImplementation(async (userId: string) => {
expect(getRlsExecutionContext()).toMatchObject({ userId });
return { userId, email: "operator@example.test" };
});
getPermissions.mockResolvedValue([PORTAL_DOMAIN_KILL_SWITCH_PERMISSION]);
setKillSwitch.mockResolvedValue(undefined);
});
it("requires an AdminUser and destructive operator permission before enabling the switch", async () => {
await setOperatorPortalDomainKillSwitch(
{
tenantId: "tenant_1",
actorUserId: "operator_1",
enabled: true,
reason: "Compromised custom-domain routing",
},
dependencies,
);
expect(setKillSwitch).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
actorUserId: "operator_1",
enabled: true,
reason: "Compromised custom-domain routing",
operatorAudit: expect.objectContaining({
action: "admin.portalDomain.killSwitchEnabled",
actorId: "operator_1",
actorEmail: "operator@example.test",
targetType: "portal-domain-tenant",
targetId: "tenant_1",
tenantId: null,
}),
}),
);
});
it("rejects a tenant identity even if a caller invokes the service directly", async () => {
findOperator.mockResolvedValue(null);
await expect(
setOperatorPortalDomainKillSwitch(
{ tenantId: "tenant_1", actorUserId: "tenant_user_1", enabled: true, reason: "Emergency isolation" },
dependencies,
),
).rejects.toMatchObject({ code: "NOT_OPERATOR" } satisfies Partial<PortalDomainOperatorError>);
expect(setKillSwitch).not.toHaveBeenCalled();
});
it("rejects an operator without the destructive permission", async () => {
getPermissions.mockResolvedValue(["admin.metrics.view"]);
await expect(
setOperatorPortalDomainKillSwitch(
{ tenantId: "tenant_1", actorUserId: "operator_1", enabled: false, reason: "Incident resolved" },
dependencies,
),
).rejects.toMatchObject({ code: "PERMISSION_DENIED" } satisfies Partial<PortalDomainOperatorError>);
expect(setKillSwitch).not.toHaveBeenCalled();
});
it("requires a meaningful reason before any operator lookup or mutation", async () => {
await expect(
setOperatorPortalDomainKillSwitch(
{ tenantId: "tenant_1", actorUserId: "operator_1", enabled: true, reason: "no" },
dependencies,
),
).rejects.toBeInstanceOf(AdminActionInputError);
expect(findOperator).not.toHaveBeenCalled();
expect(setKillSwitch).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,106 @@
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { listAdminPermissionNames } from "@hivegrid/db/admin-rbac.server";
import { db } from "~/utils/db.server";
import { setPortalDomainKillSwitch } from "~/services/customer-portal/portal-domain.server";
import {
assertAdminActionReason,
buildAdminActionAuditInput,
type AdminActionAuditContext,
} from "./admin-action-audit.server";
export const PORTAL_DOMAIN_KILL_SWITCH_PERMISSION = "admin_identity.tenants.manage" as const;
export class PortalDomainOperatorError extends Error {
override readonly name = "PortalDomainOperatorError";
constructor(readonly code: "NOT_OPERATOR" | "PERMISSION_DENIED" | "TENANT_ID_INVALID") {
super(code);
}
}
type PortalDomainOperator = {
readonly userId: string;
readonly email: string;
};
export type PortalDomainOperatorDependencies = {
readonly findOperator: (userId: string) => Promise<PortalDomainOperator | null>;
readonly getPermissions: (userId: string) => Promise<readonly string[]>;
readonly setKillSwitch: typeof setPortalDomainKillSwitch;
};
function defaultDependencies(): PortalDomainOperatorDependencies {
return {
findOperator: async (userId) => {
const operator = await db.adminUser.findUnique({
where: { id: userId },
select: {
id: true,
email: true,
status: true,
},
});
return operator?.status === "active" ? { userId: operator.id, email: operator.email } : null;
},
getPermissions: (userId) => listAdminPermissionNames(userId),
setKillSwitch: setPortalDomainKillSwitch,
};
}
/**
* Platform-only boundary for the portal-domain kill switch.
*
* The workspace route deliberately has no mutation for this switch. Every
* caller of this boundary must resolve to an AdminUser with the destructive
* operator permission, and the cross-tenant action is reason-gated and
* recorded in the global operator audit log.
*/
export async function setOperatorPortalDomainKillSwitch(
input: {
readonly tenantId: string;
readonly actorUserId: string;
readonly enabled: boolean;
readonly reason: string;
readonly request?: Request;
},
dependencies: PortalDomainOperatorDependencies = defaultDependencies(),
): Promise<void> {
const tenantId = normalizeTenantId(input.tenantId);
const reason = assertAdminActionReason(input.reason);
await runWithRlsContext({ userId: input.actorUserId }, async () => {
const operator = await dependencies.findOperator(input.actorUserId);
if (!operator) throw new PortalDomainOperatorError("NOT_OPERATOR");
const permissions = new Set(await dependencies.getPermissions(operator.userId));
if (!permissions.has(PORTAL_DOMAIN_KILL_SWITCH_PERMISSION)) {
throw new PortalDomainOperatorError("PERMISSION_DENIED");
}
const auditContext: AdminActionAuditContext = {
action: input.enabled ? "portalDomain.killSwitchEnabled" : "portalDomain.killSwitchDisabled",
actorUserId: operator.userId,
actorEmail: operator.email,
targetKind: "portal-domain-tenant",
targetId: tenantId,
reason,
after: { tenantId, enabled: input.enabled },
request: input.request,
};
await dependencies.setKillSwitch({
tenantId,
actorUserId: operator.userId,
enabled: input.enabled,
reason,
operatorAudit: buildAdminActionAuditInput(auditContext),
});
});
}
function normalizeTenantId(value: string): string {
const normalized = value.trim();
if (!/^[A-Za-z0-9_-]{8,191}$/u.test(normalized)) {
throw new PortalDomainOperatorError("TENANT_ID_INVALID");
}
return normalized;
}
@@ -1,5 +1,7 @@
import { describe, expect, it, vi } from "vitest";
import {
getQueueFailedJobsSnapshot,
getQueueJobDetail,
getQueueMonitorSnapshot,
pauseQueue,
resumeQueue,
@@ -12,6 +14,16 @@ function makeInspector(): QueueInspector {
return {
getCounts: vi.fn(async () => ({ active: 1, waiting: 2, delayed: 0, failed: 3, completed: 4, paused: false })),
listFailedJobs: vi.fn(async () => []),
getJobDetail: vi.fn(async () => ({
id: "job_1",
name: "send-email",
failedReason: "SMTP timeout",
stacktrace: ["Error: SMTP timeout\n at send (mailer.ts:10:3)"],
attemptsMade: 2,
timestamp: 1,
processedOn: 2,
finishedOn: 3,
})),
pauseQueue: vi.fn(async () => {}),
resumeQueue: vi.fn(async () => {}),
retryJob: vi.fn(async () => {}),
@@ -37,12 +49,36 @@ describe("getQueueMonitorSnapshot", () => {
expect(inspector.getCounts).toHaveBeenCalledTimes(2);
});
it("falls back to the general group for an unknown queue name", async () => {
it("assigns the dedicated provider outbox queue to the general group", async () => {
const inspector = makeInspector();
const { deps } = makeDeps(inspector, ["totally.unknown.queue"]);
const { deps } = makeDeps(inspector, ["outbox.billing-product-provider"]);
const rows = await getQueueMonitorSnapshot(deps);
expect(rows[0].group).toBe("general");
});
it("rejects queue names outside the operational allowlist", async () => {
const inspector = makeInspector();
const { deps } = makeDeps(inspector, ["totally.unknown.queue"]);
await expect(getQueueMonitorSnapshot(deps)).rejects.toMatchObject({ code: "QUEUE_NOT_ALLOWED" });
expect(inspector.getCounts).not.toHaveBeenCalled();
});
});
describe("getQueueFailedJobsSnapshot", () => {
it("lists failed jobs per queue", async () => {
const inspector = makeInspector();
const { deps } = makeDeps(inspector, ["hivegrid.email", "hivegrid.imports"]);
const rows = await getQueueFailedJobsSnapshot(3, deps);
expect(rows).toEqual([
{ queueName: "hivegrid.email", jobs: [] },
{ queueName: "hivegrid.imports", jobs: [] },
]);
expect(inspector.listFailedJobs).toHaveBeenCalledWith("hivegrid.email", 3);
expect(inspector.listFailedJobs).toHaveBeenCalledWith("hivegrid.imports", 3);
});
});
describe("queue controls", () => {
@@ -69,4 +105,69 @@ describe("queue controls", () => {
expect(inspector.retryJob).toHaveBeenCalledWith("hivegrid.email", "job-7");
expect(recordAction.mock.calls[0][0]).toMatchObject({ action: "queue.jobRetried", after: { queueName: "hivegrid.email", jobId: "job-7" } });
});
it("blocks direct BullMQ retry for provider outbox jobs and points to generation-aware replay", async () => {
const inspector = makeInspector();
const { deps, recordAction } = makeDeps(inspector, ["outbox.billing-product-provider"]);
await expect(
retryQueueJob(
{ queueName: "outbox.billing-product-provider", jobId: "outbox-event-1-0", actorUserId: "a1" },
deps
)
).rejects.toMatchObject({
code: "DIRECT_OUTBOX_RETRY_FORBIDDEN",
message: expect.stringContaining("hivegrid-cli outbox requeue --tenant"),
});
expect(inspector.retryJob).not.toHaveBeenCalled();
expect(recordAction).not.toHaveBeenCalled();
});
it("rejects retry controls for queues outside the operational allowlist", async () => {
const inspector = makeInspector();
const { deps, recordAction } = makeDeps(inspector, ["hivegrid.email"]);
const promise = retryQueueJob({ queueName: "rogue.queue", jobId: "job-7", actorUserId: "a1" }, deps);
await expect(promise).rejects.toMatchObject({ name: "QueueMonitorControlError", code: "QUEUE_NOT_ALLOWED" });
expect(inspector.retryJob).not.toHaveBeenCalled();
expect(recordAction).not.toHaveBeenCalled();
});
it("rejects empty job ids before touching BullMQ", async () => {
const inspector = makeInspector();
const { deps, recordAction } = makeDeps(inspector, ["hivegrid.email"]);
await expect(
retryQueueJob({ queueName: "hivegrid.email", jobId: " ", actorUserId: "a1" }, deps)
).rejects.toMatchObject({ code: "JOB_ID_INVALID" });
expect(inspector.retryJob).not.toHaveBeenCalled();
expect(recordAction).not.toHaveBeenCalled();
});
});
describe("getQueueJobDetail", () => {
it("returns the full stacktrace for an allowed queue", async () => {
const inspector = makeInspector();
const { deps } = makeDeps(inspector, ["hivegrid.email"]);
const detail = await getQueueJobDetail("hivegrid.email", "job_1", deps);
expect(inspector.getJobDetail).toHaveBeenCalledWith("hivegrid.email", "job_1");
expect(detail).toMatchObject({
id: "job_1",
failedReason: "SMTP timeout",
stacktrace: ["Error: SMTP timeout\n at send (mailer.ts:10:3)"],
processedOn: 2,
finishedOn: 3,
});
});
it("rejects non-operational queues and invalid job ids", async () => {
const inspector = makeInspector();
const { deps } = makeDeps(inspector, ["hivegrid.email"]);
await expect(getQueueJobDetail("not-a-queue", "job_1", deps)).rejects.toMatchObject({ code: "QUEUE_NOT_ALLOWED" });
await expect(getQueueJobDetail("hivegrid.email", "", deps)).rejects.toMatchObject({ code: "JOB_ID_INVALID" });
expect(inspector.getJobDetail).not.toHaveBeenCalled();
});
});
@@ -10,8 +10,16 @@
* Pure presentation (counts -> health) lives in the queue-monitor VM; this
* module only gathers raw counts and performs the side-effecting controls.
*/
import { getGroupForQueue, queueNames, resolveRedisConnectionOptionsFromProcessEnv } from "@hivegrid/queue";
import { createQueue } from "@hivegrid/queue/runtime";
import {
getOperationalGroupForQueue,
fromBullMqJobId,
isOperationalQueueName,
operationalQueueNames,
productAcquisitionProviderOutboxQueueName,
queueNames,
resolveRedisConnectionOptionsFromProcessEnv,
type OperationalQueueName,
} from "@hivegrid/queue";
import type { QueueCountsInput } from "@hivegrid/view-models";
import { recordAdminAction, type AdminActionAuditContext, type AdminOperatorAction } from "./admin-action-audit.server";
@@ -25,17 +33,40 @@ export type QueueRawCounts = {
};
export type QueueFailedJobDetail = {
/** BullMQ wire id — the value every control action (retry, detail) must send. */
readonly id: string;
/** Same id with the BullMQ colon escaping reversed, for operator-facing text. */
readonly displayId: string;
readonly name: string;
readonly failedReason: string | null;
readonly attemptsMade: number;
readonly timestamp: number | null;
};
/**
* Full single-job view for the operator job detail (DoD #6): includes the
* complete BullMQ `stacktrace` (one string per failed attempt), not just
* the last `failedReason` line.
*/
export type QueueJobDetail = {
/** BullMQ wire id — the value every control action (retry, detail) must send. */
readonly id: string;
/** Same id with the BullMQ colon escaping reversed, for operator-facing text. */
readonly displayId: string;
readonly name: string;
readonly failedReason: string | null;
readonly stacktrace: readonly string[];
readonly attemptsMade: number;
readonly timestamp: number | null;
readonly processedOn: number | null;
readonly finishedOn: number | null;
};
/** Live-queue port. The production impl wraps BullMQ; tests pass a fake. */
export interface QueueInspector {
getCounts(queueName: string): Promise<QueueRawCounts>;
listFailedJobs(queueName: string, limit: number): Promise<readonly QueueFailedJobDetail[]>;
getJobDetail(queueName: string, jobId: string): Promise<QueueJobDetail | null>;
pauseQueue(queueName: string): Promise<void>;
resumeQueue(queueName: string): Promise<void>;
retryJob(queueName: string, jobId: string): Promise<void>;
@@ -47,7 +78,35 @@ export interface QueueMonitorDeps {
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
}
const ALL_QUEUE_NAMES: readonly string[] = Object.values(queueNames);
const ALL_QUEUE_NAMES: readonly OperationalQueueName[] = operationalQueueNames;
export class QueueMonitorControlError extends Error {
constructor(
readonly code: "QUEUE_NOT_ALLOWED" | "JOB_ID_INVALID" | "DIRECT_OUTBOX_RETRY_FORBIDDEN",
message: string
) {
super(message);
this.name = "QueueMonitorControlError";
}
}
function requireOperationalQueueName(value: string): OperationalQueueName {
if (!isOperationalQueueName(value)) {
throw new QueueMonitorControlError(
"QUEUE_NOT_ALLOWED",
"Diese Queue ist nicht für Operator-Aktionen freigegeben."
);
}
return value;
}
function requireJobId(value: string): string {
const normalized = value.trim();
if (normalized.length === 0 || normalized.length > 191 || normalized.includes("\u0000")) {
throw new QueueMonitorControlError("JOB_ID_INVALID", "Die Job-ID ist ungültig.");
}
return normalized;
}
function defaultQueueMonitorDeps(): QueueMonitorDeps {
return { inspector: createBullMqQueueInspector(), queueNames: ALL_QUEUE_NAMES, recordAction: recordAdminAction };
@@ -59,15 +118,42 @@ export async function getQueueMonitorSnapshot(
): Promise<QueueCountsInput[]> {
return Promise.all(
deps.queueNames.map(async (queueName) => {
const counts = await deps.inspector.getCounts(queueName);
const group = isKnownQueueName(queueName) ? getGroupForQueue(queueName) : "general";
return { queueName, group, ...counts } satisfies QueueCountsInput;
const allowedQueueName = requireOperationalQueueName(queueName);
const counts = await deps.inspector.getCounts(allowedQueueName);
const group = getOperationalGroupForQueue(allowedQueueName);
return { queueName: allowedQueueName, group, ...counts } satisfies QueueCountsInput;
})
);
}
function isKnownQueueName(value: string): value is (typeof queueNames)[keyof typeof queueNames] {
return (ALL_QUEUE_NAMES as readonly string[]).includes(value);
export type QueueFailedJobsSnapshot = {
readonly queueName: string;
readonly jobs: readonly QueueFailedJobDetail[];
};
export async function getQueueFailedJobsSnapshot(
limitPerQueue = 5,
deps: QueueMonitorDeps = defaultQueueMonitorDeps()
): Promise<QueueFailedJobsSnapshot[]> {
return Promise.all(
deps.queueNames.map(async (queueName) => {
const allowedQueueName = requireOperationalQueueName(queueName);
return {
queueName: allowedQueueName,
jobs: await deps.inspector.listFailedJobs(allowedQueueName, limitPerQueue),
};
})
);
}
/** Reads one job's full detail (error stack + timeline) for the detail dialog. */
export async function getQueueJobDetail(
queueName: string,
jobId: string,
deps: QueueMonitorDeps = defaultQueueMonitorDeps()
): Promise<QueueJobDetail | null> {
const allowedQueueName = requireOperationalQueueName(queueName);
return deps.inspector.getJobDetail(allowedQueueName, requireJobId(jobId));
}
export interface QueueControlInput {
@@ -97,22 +183,35 @@ async function auditQueueControl(
}
export async function pauseQueue(input: QueueControlInput, deps: QueueMonitorDeps = defaultQueueMonitorDeps()): Promise<void> {
await deps.inspector.pauseQueue(input.queueName);
await auditQueueControl(deps, "queue.paused", input, "Operator hat die Queue pausiert");
const queueName = requireOperationalQueueName(input.queueName);
const allowedInput = { ...input, queueName };
await deps.inspector.pauseQueue(queueName);
await auditQueueControl(deps, "queue.paused", allowedInput, "Operator hat die Queue pausiert");
}
export async function resumeQueue(input: QueueControlInput, deps: QueueMonitorDeps = defaultQueueMonitorDeps()): Promise<void> {
await deps.inspector.resumeQueue(input.queueName);
await auditQueueControl(deps, "queue.resumed", input, "Operator hat die Queue fortgesetzt");
const queueName = requireOperationalQueueName(input.queueName);
const allowedInput = { ...input, queueName };
await deps.inspector.resumeQueue(queueName);
await auditQueueControl(deps, "queue.resumed", allowedInput, "Operator hat die Queue fortgesetzt");
}
export async function retryQueueJob(
input: QueueControlInput & { readonly jobId: string },
deps: QueueMonitorDeps = defaultQueueMonitorDeps()
): Promise<void> {
await deps.inspector.retryJob(input.queueName, input.jobId);
await auditQueueControl(deps, "queue.jobRetried", input, "Operator hat einen fehlgeschlagenen Job erneut gestartet", {
jobId: input.jobId,
const queueName = requireOperationalQueueName(input.queueName);
if (queueName === productAcquisitionProviderOutboxQueueName) {
throw new QueueMonitorControlError(
"DIRECT_OUTBOX_RETRY_FORBIDDEN",
"Direktes BullMQ-Retry ist für diese Finanz-Queue gesperrt. Nutze `hivegrid-cli outbox requeue --tenant <tenant-id> --event-id <outbox-event-id>`, damit Tenant-Scope und Delivery-Generation atomar fortgeschrieben werden."
);
}
const jobId = requireJobId(input.jobId);
const allowedInput = { ...input, queueName };
await deps.inspector.retryJob(queueName, jobId);
await auditQueueControl(deps, "queue.jobRetried", allowedInput, "Operator hat einen fehlgeschlagenen Job erneut gestartet", {
jobId,
});
}
@@ -126,8 +225,11 @@ interface BullJobControl {
readonly id?: string | number;
readonly name: string;
readonly failedReason?: string;
readonly stacktrace?: readonly string[];
readonly attemptsMade: number;
readonly timestamp?: number;
readonly processedOn?: number;
readonly finishedOn?: number;
retry(): Promise<void>;
}
interface BullQueueReadControl {
@@ -149,7 +251,13 @@ export function createBullMqQueueInspector(): QueueInspector {
const connection = resolveRedisConnectionOptionsFromProcessEnv({ required: true });
async function withQueue<T>(queueName: string, fn: (queue: BullQueueReadControl) => Promise<T>): Promise<T> {
const queue = createQueue(queueName as (typeof queueNames)[keyof typeof queueNames], {
const allowedQueueName = requireOperationalQueueName(queueName);
// Lazy-load the BullMQ runtime through an indirect specifier so the web build
// never statically resolves the `@hivegrid/queue/runtime` -> /dev/null alias
// (see apps/web/vite.config.ts). Matches every other server-only queue producer.
const queueRuntimeModule = "@hivegrid/queue/runtime";
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@hivegrid/queue/runtime");
const queue = createQueue(allowedQueueName as (typeof queueNames)[keyof typeof queueNames], {
connection,
}) as unknown as BullQueueReadControl;
try {
@@ -179,13 +287,35 @@ export function createBullMqQueueInspector(): QueueInspector {
async listFailedJobs(queueName, limit) {
return withQueue(queueName, async (queue) => {
const jobs = await queue.getJobs(["failed"], 0, Math.max(0, limit - 1));
return jobs.map((job) => ({
id: String(job.id ?? ""),
return jobs.map((job) => {
const id = String(job.id ?? "");
return {
id,
displayId: fromBullMqJobId(id),
name: job.name,
failedReason: job.failedReason ?? null,
attemptsMade: job.attemptsMade,
timestamp: job.timestamp ?? null,
};
});
});
},
async getJobDetail(queueName, jobId) {
return withQueue(queueName, async (queue) => {
const job = await queue.getJob(jobId);
if (!job) return null;
const id = String(job.id ?? jobId);
return {
id,
displayId: fromBullMqJobId(id),
name: job.name,
failedReason: job.failedReason ?? null,
stacktrace: job.stacktrace ?? [],
attemptsMade: job.attemptsMade,
timestamp: job.timestamp ?? null,
}));
processedOn: job.processedOn ?? null,
finishedOn: job.finishedOn ?? null,
};
});
},
async pauseQueue(queueName) {
@@ -8,6 +8,7 @@ import {
type ConnectorServiceDeps,
} from "./subscription-assembly.server";
import { AdminActionInputError } from "./admin-action-audit.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
const FEATURES: readonly ProductBlueprintFeatureDefinition[] = [
{ featureKey: "crm-basic", defaultEnabled: true, tenantToggleable: false },
@@ -52,6 +53,10 @@ describe("buildConnectorInputRows", () => {
describe("getTenantConnectorRows", () => {
it("reads overrides and maps them onto the blueprint", async () => {
const { deps } = makeDeps([{ featureKey: "api", override: "enabled" }]);
vi.mocked(deps.db.tenantProductConfiguration.findUnique).mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("t1");
return { blueprintId: "crm-saas" };
});
const rows = await getTenantConnectorRows("t1", deps);
expect(rows.find((r) => r.featureKey === "api")?.overrideState).toBe("enabled");
});
@@ -82,6 +87,10 @@ describe("setTenantFeatureConnector", () => {
it("upserts the override, invalidates the cache and audits", async () => {
const { deps, upsert, invalidateCache, recordAction } = makeDeps();
upsert.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("t1");
return {};
});
await setTenantFeatureConnector(
{ tenantId: "t1", featureKey: "api", state: "enabled", reason: "Pilot freischalten", actorUserId: "a1" },
deps
@@ -18,6 +18,7 @@ import {
getProductBlueprint,
type ProductBlueprintFeatureDefinition,
} from "@hivegrid/entitlements";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type { AdminConnectorInputRow, ConnectorOverrideState } from "@hivegrid/view-models";
import { db } from "~/utils/db.server";
import { invalidateTenantModuleAccessCache } from "~/utils/connector/tenantConnector.server";
@@ -83,6 +84,10 @@ export async function getTenantConnectorRows(
tenantId: string,
deps: ConnectorServiceDeps = defaultDeps()
): Promise<AdminConnectorInputRow[]> {
return runWithRlsContext({ tenantId }, () => getTenantConnectorRowsInContext(tenantId, deps));
}
async function getTenantConnectorRowsInContext(tenantId: string, deps: ConnectorServiceDeps): Promise<AdminConnectorInputRow[]> {
const [configuration, overrides] = await Promise.all([
deps.db.tenantProductConfiguration.findUnique({ where: { tenantId }, select: { blueprintId: true } }),
deps.db.tenantFeatureOverride.findMany({ where: { tenantId }, select: { featureKey: true, override: true } }),
@@ -111,6 +116,10 @@ export async function setTenantFeatureConnector(
input: SetTenantFeatureConnectorInput,
deps: ConnectorServiceDeps = defaultDeps()
): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => setTenantFeatureConnectorInContext(input, deps));
}
async function setTenantFeatureConnectorInContext(input: SetTenantFeatureConnectorInput, deps: ConnectorServiceDeps): Promise<void> {
const reason = assertAdminActionReason(input.reason);
const configuration = await deps.db.tenantProductConfiguration.findUnique({
@@ -0,0 +1,72 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { getSystemHealthSnapshot } from "./system-health.server";
describe("admin system health service", () => {
it("collects runtime configuration without exposing secret values", async () => {
const snapshot = await getSystemHealthSnapshot({
env: {
NODE_ENV: "production",
SENTRY_ENVIRONMENT: "staging",
SENTRY_RELEASE: "abc123",
DATABASE_URL: "postgres://secret@example/db",
BULLMQ_REDIS_URL: "redis://secret@redis/0",
MEILI_URL: "http://meili.local",
MEILI_API_KEY: "meili-secret",
STORAGE_PROVIDER: "s3",
STORAGE_ENDPOINT: "https://storage.example",
STORAGE_REGION: "fsn1",
STORAGE_BUCKET: "hivegrid-staging",
STORAGE_ACCESS_KEY_ID: "access-secret",
STORAGE_SECRET_ACCESS_KEY: "secret-secret",
LAGO_API_URL: "https://lago.example",
LAGO_API_KEY: "lago-secret",
MOLLIE_API_KEY: "mollie-secret",
MOLLIE_PROFILE_ID: "profile",
MAILJET_API_KEY: "mailjet-key",
MAILJET_SECRET_KEY: "mailjet-secret",
MAILJET_FROM_EMAIL: "billing@hivegrid.de",
SENTRY_DSN_WEB: "https://dsn@example/1",
MCP_RESOURCE_URL: "https://mcp.hivegrid.de",
},
pingDatabase: async () => true,
});
expect(snapshot.deploy).toEqual({ environment: "staging", release: "abc123", nodeEnv: "production" });
expect(snapshot.services.find((service) => service.id === "postgres")).toMatchObject({ configured: true, reachable: true });
expect(snapshot.services.find((service) => service.id === "mollie")).toMatchObject({ configured: true });
expect(JSON.stringify(snapshot)).not.toContain("mollie-secret");
expect(JSON.stringify(snapshot)).not.toContain("secret-secret");
});
it("skips blank release variables instead of rendering an empty release", async () => {
// Regression guard: the local `??` chain accepted an empty SENTRY_RELEASE,
// so the /system header read "Release: " while /deploys showed the commit.
const snapshot = await getSystemHealthSnapshot({
env: { NODE_ENV: "production", SENTRY_ENVIRONMENT: "staging", SENTRY_RELEASE: " ", GIT_SHA: "b05b699" },
pingDatabase: async () => true,
});
expect(snapshot.deploy.release).toBe("b05b699");
});
it("falls back to a readable placeholder when no release variable is set", async () => {
const snapshot = await getSystemHealthSnapshot({
env: { NODE_ENV: "production", SENTRY_RELEASE: "" },
pingDatabase: async () => true,
});
expect(snapshot.deploy.release).toBe("local");
});
it("marks missing optional integrations as warnings for the VM", async () => {
const snapshot = await getSystemHealthSnapshot({
env: { NODE_ENV: "development" },
pingDatabase: async () => false,
});
expect(snapshot.services.find((service) => service.id === "postgres")).toMatchObject({ configured: false, reachable: false });
expect(snapshot.services.find((service) => service.id === "lago")).toMatchObject({ configured: false, reachable: null });
expect(snapshot.services.find((service) => service.id === "web")).toMatchObject({ configured: true, reachable: true });
});
});
@@ -0,0 +1,159 @@
import { getDbClient } from "@hivegrid/db/client.server";
import type { SystemHealthDeploy, SystemHealthServiceInput } from "@hivegrid/view-models";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { buildDeployMetadata } from "./deploy-admin.server";
export type SystemHealthSnapshot = {
readonly services: readonly SystemHealthServiceInput[];
readonly deploy: SystemHealthDeploy;
};
export type SystemHealthDeps = {
readonly env?: NodeJS.ProcessEnv;
readonly pingDatabase?: () => Promise<boolean>;
};
export async function getSystemHealthSnapshot(deps: SystemHealthDeps = {}): Promise<SystemHealthSnapshot> {
const env = deps.env ?? process.env;
const pingDatabase = deps.pingDatabase ?? defaultDatabasePing;
const databaseReachable = await pingDatabase().catch(() => false);
const deploy = buildDeployInfo(env);
return {
deploy,
services: [
{
id: "web",
labelKey: "admin.system.services.web.label",
category: "runtime",
configured: true,
reachable: true,
detailKey: "admin.system.services.web.detail",
detailValue: deploy.release,
},
{
id: "api",
labelKey: "admin.system.services.api.label",
category: "runtime",
configured: hasAny(env, ["API_HOST", "API_BASE_URL", "API_RESOURCE_URL"]),
reachable: null,
detailKey: "admin.system.services.api.detail",
detailValue: firstPresent(env, ["API_HOST", "API_BASE_URL", "API_RESOURCE_URL"]) ?? "api.hivegrid.de",
},
{
id: "mcp",
labelKey: "admin.system.services.mcp.label",
category: "runtime",
configured: hasAny(env, ["MCP_RESOURCE_URL", "MCP_HOST"]),
reachable: null,
detailKey: "admin.system.services.mcp.detail",
detailValue: firstPresent(env, ["MCP_RESOURCE_URL", "MCP_HOST"]) ?? "mcp.hivegrid.de",
},
{
id: "postgres",
labelKey: "admin.system.services.postgres.label",
category: "database",
configured: hasAny(env, ["DATABASE_URL", "DIRECT_URL"]),
reachable: databaseReachable,
detailKey: databaseReachable ? "admin.system.services.postgres.detailOk" : "admin.system.services.postgres.detailFailed",
},
{
id: "redis",
labelKey: "admin.system.services.redis.label",
category: "queue",
configured: hasAny(env, ["BULLMQ_REDIS_URL", "REDIS_URL"]),
reachable: null,
detailKey: "admin.system.services.redis.detail",
href: adminPath("system/jobs", { mode: "host-aware" }),
},
{
id: "meili",
labelKey: "admin.system.services.meili.label",
category: "integration",
configured: hasAll(env, ["MEILI_URL", "MEILI_API_KEY"]),
reachable: null,
detailKey: "admin.system.services.meili.detail",
},
{
id: "storage",
labelKey: "admin.system.services.storage.label",
category: "storage",
configured: storageConfigured(env),
reachable: null,
detailKey: "admin.system.services.storage.detail",
detailValue: firstPresent(env, ["STORAGE_BUCKET", "STORAGE_LOCAL_ROOT"]) ?? "",
},
{
id: "lago",
labelKey: "admin.system.services.lago.label",
category: "integration",
configured: hasAll(env, ["LAGO_API_URL", "LAGO_API_KEY"]),
reachable: null,
detailKey: "admin.system.services.lago.detail",
},
{
id: "mollie",
labelKey: "admin.system.services.mollie.label",
category: "integration",
configured: hasAll(env, ["MOLLIE_API_KEY", "MOLLIE_PROFILE_ID"]),
reachable: null,
detailKey: "admin.system.services.mollie.detail",
},
{
id: "mailjet",
labelKey: "admin.system.services.mailjet.label",
category: "integration",
configured: hasAll(env, ["MAILJET_API_KEY", "MAILJET_SECRET_KEY", "MAILJET_FROM_EMAIL"]),
reachable: null,
detailKey: "admin.system.services.mailjet.detail",
},
{
id: "sentry",
labelKey: "admin.system.services.sentry.label",
category: "observability",
configured: hasAny(env, ["SENTRY_DSN", "SENTRY_DSN_WEB", "VITE_SENTRY_DSN_WEB"]),
reachable: null,
detailKey: "admin.system.services.sentry.detail",
},
],
};
}
async function defaultDatabasePing(): Promise<boolean> {
const db = getDbClient();
await db.$queryRaw`SELECT 1`;
return true;
}
function buildDeployInfo(env: NodeJS.ProcessEnv): SystemHealthDeploy {
// Reuses the `/deploys` resolution instead of a second, weaker one. The local
// variant used `??`, which only skips null/undefined: a deploy target that
// sets SENTRY_RELEASE to an empty string won the chain and the header read
// "Release: " with nothing behind it, while /deploys showed the value
// (admin audit 2026-07-26, P0-11).
const metadata = buildDeployMetadata(env);
return {
environment: metadata.environment,
release: metadata.release,
nodeEnv: metadata.nodeEnv,
};
}
function hasAny(env: NodeJS.ProcessEnv, names: readonly string[]): boolean {
return names.some((name) => Boolean(env[name]?.trim()));
}
function hasAll(env: NodeJS.ProcessEnv, names: readonly string[]): boolean {
return names.every((name) => Boolean(env[name]?.trim()));
}
function firstPresent(env: NodeJS.ProcessEnv, names: readonly string[]): string | undefined {
return names.map((name) => env[name]?.trim()).find((value): value is string => Boolean(value));
}
function storageConfigured(env: NodeJS.ProcessEnv): boolean {
if (env.STORAGE_PROVIDER?.trim() === "local") {
return hasAny(env, ["STORAGE_LOCAL_ROOT"]);
}
return hasAll(env, ["STORAGE_ENDPOINT", "STORAGE_REGION", "STORAGE_BUCKET", "STORAGE_ACCESS_KEY_ID", "STORAGE_SECRET_ACCESS_KEY"]);
}
@@ -0,0 +1,191 @@
import { describe, expect, it, vi } from "vitest";
import { forgetTenantTrustedDevice, getTenantSecuritySnapshot, revokeTenantUserSession, TenantSecurityError, type TenantSecurityDeps } from "./tenant-security.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
function makeDb() {
return {
tenant: {
findUnique: vi.fn(async () => ({
id: "tenant_1",
name: "Acme",
slug: "acme",
active: true,
users: [
{
status: 1,
user: {
id: "user_1",
email: "owner@example.test",
firstName: "Owner",
lastName: "Example",
active: true,
totpEnabledAt: new Date("2026-07-01T00:00:00.000Z"),
totpPendingCreatedAt: null,
mfaRecoveryCodeHashes: [{ hash: "x" }],
},
},
],
})),
},
userSession: {
findMany: vi.fn(async () => [
{
id: "session_1",
userId: "user_1",
deviceLabel: "MacBook",
userAgent: "Safari",
approxLocation: "DE",
createdAt: new Date("2026-07-09T08:00:00.000Z"),
lastSeenAt: new Date("2026-07-09T09:00:00.000Z"),
expiresAt: new Date("2026-07-10T09:00:00.000Z"),
revokedAt: null,
trustedAt: null,
user: { email: "owner@example.test" },
},
]),
findFirst: vi.fn(async () => ({ id: "session_1", revokedAt: null, userId: "user_1", user: { email: "owner@example.test" } })),
update: vi.fn(async () => ({})),
},
trustedDevice: {
findMany: vi.fn(async () => [
{
id: "device_1",
userId: "user_1",
deviceLabel: "Safari",
approxLocation: "DE",
lastUsedAt: new Date("2026-07-09T08:00:00.000Z"),
expiresAt: new Date("2026-08-09T08:00:00.000Z"),
revokedAt: null,
user: { email: "owner@example.test" },
},
]),
findFirst: vi.fn(async () => ({ id: "device_1", revokedAt: null, userId: "user_1", user: { email: "owner@example.test" } })),
update: vi.fn(async () => ({})),
},
magicLinkToken: {
findMany: vi.fn(async () => []),
},
tenantIpAddress: {
findMany: vi.fn(async () => [
{
id: "ip_1",
ip: "192.168.10.25",
fromUrl: "/login",
createdAt: new Date("2026-07-09T08:00:00.000Z"),
user: { email: "owner@example.test" },
apiKey: null,
},
]),
},
};
}
function makeDeps(db = makeDb()) {
return {
db,
now: () => new Date("2026-07-09T10:00:00.000Z"),
listAuditEvents: vi.fn(async () => ({
rows: [
{
id: "audit_1",
createdAt: new Date("2026-07-09T09:00:00.000Z"),
action: "auth.login.success",
outcome: "success",
actorEmail: "owner@example.test",
actorId: "user_1",
summaryText: "Login erfolgreich",
},
],
total: 1,
take: 25,
skip: 0,
})),
recordAdminAction: vi.fn(async () => {}),
} as unknown as TenantSecurityDeps & { db: ReturnType<typeof makeDb>; recordAdminAction: ReturnType<typeof vi.fn>; listAuditEvents: ReturnType<typeof vi.fn> };
}
describe("getTenantSecuritySnapshot", () => {
it("loads security diagnostics for one tenant", async () => {
const deps = makeDeps();
deps.db.tenant.findUnique.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
return makeDb().tenant.findUnique();
});
const snapshot = await getTenantSecuritySnapshot("tenant_1", deps);
expect(deps.db.tenant.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "tenant_1" } }));
expect(deps.db.userSession.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { userId: { in: ["user_1"] } } }));
expect(deps.listAuditEvents).toHaveBeenCalledWith(expect.objectContaining({ take: 25 }));
expect(snapshot.users[0]).toMatchObject({ email: "owner@example.test", mfaEnabled: true, recoveryCodesConfigured: true });
expect(snapshot.sessions[0]).toMatchObject({ id: "session_1", userEmail: "owner@example.test" });
expect(snapshot.ipLogs[0]).toMatchObject({ ip: "192.168.10.25" });
});
it("raises a typed error when the tenant does not exist", async () => {
const db = makeDb();
db.tenant.findUnique.mockResolvedValueOnce(null);
await expect(getTenantSecuritySnapshot("missing", makeDeps(db))).rejects.toMatchObject({ code: "TENANT_NOT_FOUND" });
});
});
describe("tenant security operator actions", () => {
it("revokes a session and records an admin audit event", async () => {
const deps = makeDeps();
deps.db.userSession.update.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
return {};
});
await revokeTenantUserSession(
{
tenantId: "tenant_1",
sessionId: "session_1",
reason: "Supportfall MFA Reset",
actorUserId: "admin_1",
actorEmail: "admin@hivegrid.de",
},
deps
);
expect(deps.db.userSession.update).toHaveBeenCalledWith({
where: { id: "session_1" },
data: { revokedAt: new Date("2026-07-09T10:00:00.000Z") },
});
expect(deps.recordAdminAction).toHaveBeenCalledWith(expect.objectContaining({ action: "security.sessionRevoked", targetId: "session_1" }));
});
it("forgets a trusted device and records an admin audit event", async () => {
const deps = makeDeps();
deps.db.trustedDevice.update.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()?.tenantId).toBe("tenant_1");
return {};
});
await forgetTenantTrustedDevice(
{
tenantId: "tenant_1",
trustedDeviceId: "device_1",
reason: "Geraet verloren",
actorUserId: "admin_1",
},
deps
);
expect(deps.db.trustedDevice.update).toHaveBeenCalledWith({
where: { id: "device_1" },
data: { revokedAt: new Date("2026-07-09T10:00:00.000Z") },
});
expect(deps.recordAdminAction).toHaveBeenCalledWith(expect.objectContaining({ action: "security.trustedDeviceForgotten", targetId: "device_1" }));
});
it("returns a typed error for unknown sessions", async () => {
const db = makeDb();
db.userSession.findFirst.mockResolvedValueOnce(null);
await expect(
revokeTenantUserSession({ tenantId: "tenant_1", sessionId: "missing", reason: "Supportfall MFA Reset", actorUserId: "admin_1" }, makeDeps(db))
).rejects.toBeInstanceOf(TenantSecurityError);
});
});
@@ -0,0 +1,298 @@
import { getDbClient } from "@hivegrid/db/client.server";
import { listAuditEvents } from "@hivegrid/db/audit-events-query.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import type {
TenantSecurityAuditInput,
TenantSecurityInput,
TenantSecurityIpLogInput,
TenantSecurityMagicLinkInput,
TenantSecuritySessionInput,
TenantSecurityTrustedDeviceInput,
TenantSecurityUserInput,
} from "@hivegrid/view-models";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { assertAdminActionReason, recordAdminAction } from "./admin-action-audit.server";
export type TenantSecurityDeps = {
readonly db?: ReturnType<typeof getDbClient>;
readonly now?: () => Date;
readonly listAuditEvents?: typeof listAuditEvents;
readonly recordAdminAction?: typeof recordAdminAction;
};
export class TenantSecurityError extends Error {
override readonly name = "TenantSecurityError";
readonly code: "TENANT_NOT_FOUND" | "SESSION_NOT_FOUND" | "TRUSTED_DEVICE_NOT_FOUND";
constructor(code: TenantSecurityError["code"]) {
super(code);
this.code = code;
}
}
export async function getTenantSecuritySnapshot(tenantId: string, deps: TenantSecurityDeps = {}): Promise<TenantSecurityInput> {
return runWithRlsContext({ tenantId }, () => getTenantSecuritySnapshotInContext(tenantId, deps));
}
async function getTenantSecuritySnapshotInContext(tenantId: string, deps: TenantSecurityDeps): Promise<TenantSecurityInput> {
const db = deps.db ?? getDbClient();
const now = deps.now?.() ?? new Date();
const auditEvents = deps.listAuditEvents ?? listAuditEvents;
const tenant = await db.tenant.findUnique({
where: { id: tenantId },
select: {
id: true,
name: true,
slug: true,
active: true,
users: {
select: {
status: true,
user: {
select: {
id: true,
email: true,
firstName: true,
lastName: true,
active: true,
totpEnabledAt: true,
totpPendingCreatedAt: true,
mfaRecoveryCodeHashes: true,
},
},
},
},
},
});
if (!tenant) throw new TenantSecurityError("TENANT_NOT_FOUND");
const userIds = tenant.users.map((item) => item.user.id);
const [sessions, trustedDevices, magicLinks, ipLogs, audit] = await Promise.all([
db.userSession.findMany({
where: { userId: { in: userIds } },
orderBy: { lastSeenAt: "desc" },
take: 50,
select: {
id: true,
userId: true,
deviceLabel: true,
userAgent: true,
approxLocation: true,
createdAt: true,
lastSeenAt: true,
expiresAt: true,
revokedAt: true,
trustedAt: true,
user: { select: { email: true } },
},
}),
db.trustedDevice.findMany({
where: { userId: { in: userIds } },
orderBy: { lastUsedAt: "desc" },
take: 50,
select: {
id: true,
userId: true,
deviceLabel: true,
approxLocation: true,
lastUsedAt: true,
expiresAt: true,
revokedAt: true,
user: { select: { email: true } },
},
}),
db.magicLinkToken.findMany({
where: { userId: { in: userIds } },
orderBy: { createdAt: "desc" },
take: 25,
select: {
id: true,
userId: true,
createdAt: true,
expiresAt: true,
consumedAt: true,
user: { select: { email: true } },
},
}),
db.tenantIpAddress.findMany({
where: { tenantId },
orderBy: { createdAt: "desc" },
take: 25,
select: {
id: true,
ip: true,
fromUrl: true,
createdAt: true,
user: { select: { email: true } },
apiKey: { select: { alias: true } },
},
}),
auditEvents({
where: {
tenantId,
OR: [
{ outcome: { in: ["failure", "blocked"] } },
{ action: { contains: "login", mode: "insensitive" } },
{ action: { contains: "mfa", mode: "insensitive" } },
{ action: { contains: "magic", mode: "insensitive" } },
{ action: { contains: "session", mode: "insensitive" } },
],
},
take: 25,
skip: 0,
}),
]);
return {
now: now.toISOString(),
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug, active: tenant.active },
users: tenant.users.map<TenantSecurityUserInput>((item) => ({
id: item.user.id,
email: item.user.email,
name: `${item.user.firstName} ${item.user.lastName}`.trim() || item.user.email,
active: item.user.active,
membershipStatus: item.status === TenantUserStatus.ACTIVE ? "active" : "inactive",
mfaEnabled: item.user.totpEnabledAt !== null,
mfaPending: item.user.totpPendingCreatedAt !== null,
recoveryCodesConfigured: hasRecoveryCodes(item.user.mfaRecoveryCodeHashes),
})),
sessions: sessions.map<TenantSecuritySessionInput>((session) => ({
id: session.id,
userId: session.userId,
userEmail: session.user.email,
deviceLabel: session.deviceLabel,
userAgent: session.userAgent,
approxLocation: session.approxLocation,
createdAt: session.createdAt.toISOString(),
lastSeenAt: session.lastSeenAt.toISOString(),
expiresAt: session.expiresAt.toISOString(),
revokedAt: session.revokedAt?.toISOString() ?? null,
trustedAt: session.trustedAt?.toISOString() ?? null,
})),
trustedDevices: trustedDevices.map<TenantSecurityTrustedDeviceInput>((device) => ({
id: device.id,
userId: device.userId,
userEmail: device.user.email,
deviceLabel: device.deviceLabel,
approxLocation: device.approxLocation,
lastUsedAt: device.lastUsedAt.toISOString(),
expiresAt: device.expiresAt.toISOString(),
revokedAt: device.revokedAt?.toISOString() ?? null,
})),
magicLinks: magicLinks.map<TenantSecurityMagicLinkInput>((link) => ({
id: link.id,
userId: link.userId,
userEmail: link.user.email,
createdAt: link.createdAt.toISOString(),
expiresAt: link.expiresAt.toISOString(),
consumedAt: link.consumedAt?.toISOString() ?? null,
})),
ipLogs: ipLogs.map<TenantSecurityIpLogInput>((log) => ({
id: log.id,
ip: log.ip,
fromUrl: log.fromUrl,
createdAt: log.createdAt.toISOString(),
userEmail: log.user?.email ?? null,
apiKeyAlias: log.apiKey?.alias ?? null,
})),
auditEvents: audit.rows.map<TenantSecurityAuditInput>((event) => ({
id: event.id,
createdAt: event.createdAt.toISOString(),
action: event.action,
outcome: event.outcome,
actorEmail: event.actorEmail,
actorId: event.actorId,
summaryText: event.summaryText,
})),
};
}
export async function revokeTenantUserSession(input: {
readonly tenantId: string;
readonly sessionId: string;
readonly reason: string;
readonly actorUserId: string | null;
readonly actorEmail?: string | null;
readonly request?: Request;
}, deps: TenantSecurityDeps = {}): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => revokeTenantUserSessionInContext(input, deps));
}
async function revokeTenantUserSessionInContext(input: {
readonly tenantId: string;
readonly sessionId: string;
readonly reason: string;
readonly actorUserId: string | null;
readonly actorEmail?: string | null;
readonly request?: Request;
}, deps: TenantSecurityDeps): Promise<void> {
const db = deps.db ?? getDbClient();
const recordAction = deps.recordAdminAction ?? recordAdminAction;
const now = deps.now?.() ?? new Date();
const reason = assertAdminActionReason(input.reason);
const session = await db.userSession.findFirst({
where: { id: input.sessionId, user: { tenants: { some: { tenantId: input.tenantId } } } },
select: { id: true, revokedAt: true, userId: true, user: { select: { email: true } } },
});
if (!session) throw new TenantSecurityError("SESSION_NOT_FOUND");
await db.userSession.update({ where: { id: session.id }, data: { revokedAt: now } });
await recordAction({
action: "security.sessionRevoked",
actorUserId: input.actorUserId,
actorEmail: input.actorEmail,
targetKind: "user_session",
targetId: session.id,
reason,
request: input.request,
extraMeta: { tenantId: input.tenantId, userId: session.userId, userEmail: session.user.email },
});
}
export async function forgetTenantTrustedDevice(input: {
readonly tenantId: string;
readonly trustedDeviceId: string;
readonly reason: string;
readonly actorUserId: string | null;
readonly actorEmail?: string | null;
readonly request?: Request;
}, deps: TenantSecurityDeps = {}): Promise<void> {
return runWithRlsContext({ tenantId: input.tenantId }, () => forgetTenantTrustedDeviceInContext(input, deps));
}
async function forgetTenantTrustedDeviceInContext(input: {
readonly tenantId: string;
readonly trustedDeviceId: string;
readonly reason: string;
readonly actorUserId: string | null;
readonly actorEmail?: string | null;
readonly request?: Request;
}, deps: TenantSecurityDeps): Promise<void> {
const db = deps.db ?? getDbClient();
const recordAction = deps.recordAdminAction ?? recordAdminAction;
const now = deps.now?.() ?? new Date();
const reason = assertAdminActionReason(input.reason);
const device = await db.trustedDevice.findFirst({
where: { id: input.trustedDeviceId, user: { tenants: { some: { tenantId: input.tenantId } } } },
select: { id: true, revokedAt: true, userId: true, user: { select: { email: true } } },
});
if (!device) throw new TenantSecurityError("TRUSTED_DEVICE_NOT_FOUND");
await db.trustedDevice.update({ where: { id: device.id }, data: { revokedAt: now } });
await recordAction({
action: "security.trustedDeviceForgotten",
actorUserId: input.actorUserId,
actorEmail: input.actorEmail,
targetKind: "trusted_device",
targetId: device.id,
reason,
request: input.request,
extraMeta: { tenantId: input.tenantId, userId: device.userId, userEmail: device.user.email },
});
}
function hasRecoveryCodes(value: unknown): boolean {
return Array.isArray(value) ? value.length > 0 : Boolean(value);
}
@@ -0,0 +1,112 @@
import { describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { AdminWebhookInboxError, requestWebhookReplay, type AdminWebhookInboxDeps } from "./webhook-inbox.server";
function makeAttempt(overrides: Record<string, unknown> = {}) {
return {
id: "attempt_old",
endpoint: "https://example.test/webhook",
success: false,
status: 500,
eventId: "event_1",
event: {
id: "event_1",
name: "billing.mollie.webhook.failed",
data: JSON.stringify({ paymentId: "tr_123", status: "failed" }),
resource: "billing",
tenantId: "tenant_1",
},
...overrides,
};
}
function makeDeps(attempt = makeAttempt(), queue: { add: ReturnType<typeof vi.fn>; close: ReturnType<typeof vi.fn> } | null = { add: vi.fn(async () => ({ id: "job_1" })), close: vi.fn(async () => {}) }) {
const recordAction = vi.fn(async () => {});
const createdAttempts: unknown[] = [];
const db = {
eventWebhookAttempt: {
findUnique: vi.fn(async () => attempt),
create: vi.fn(async (args) => {
createdAttempts.push(args.data);
return { id: "attempt_replay" };
}),
update: vi.fn(async () => ({})),
},
};
const deps = {
db,
now: vi.fn(() => new Date("2026-07-09T10:00:00.000Z")),
createQueue: vi.fn(async () => queue),
enqueue: vi.fn(async (targetQueue, descriptor, options) => {
await targetQueue.add(descriptor.jobName, descriptor.payload, {});
return { id: options?.idempotencyKey ?? "job_1" };
}),
recordAction,
} as unknown as AdminWebhookInboxDeps;
return { deps, db, queue, recordAction, createdAttempts };
}
describe("requestWebhookReplay", () => {
it("creates a fresh attempt, enqueues webhook delivery, and audits the replay request", async () => {
const { deps, db, queue, recordAction, createdAttempts } = makeDeps();
db.eventWebhookAttempt.create.mockImplementationOnce(async (args) => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
createdAttempts.push(args.data);
return { id: "attempt_replay" };
});
await expect(
requestWebhookReplay({
attemptId: "attempt_old",
reason: "Provider Timeout erneut ausliefern",
actorUserId: "admin_1",
actorEmail: "admin@hivegrid.de",
}, deps)
).resolves.toEqual({ replayAttemptId: "attempt_replay" });
expect(db.eventWebhookAttempt.findUnique).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "attempt_old" } }));
expect(createdAttempts[0]).toMatchObject({
eventId: "event_1",
endpoint: "https://example.test/webhook",
message: "admin.webhooks.messages.replayRequested",
});
expect(deps.enqueue).toHaveBeenCalledWith(
queue,
expect.objectContaining({
jobName: "deliver-webhook",
payload: expect.objectContaining({
url: "https://example.test/webhook",
tenantId: "tenant_1",
body: { paymentId: "tr_123", status: "failed" },
metadata: expect.objectContaining({ legacyAttemptId: "attempt_replay", adminReplayOfAttemptId: "attempt_old" }),
}),
}),
expect.objectContaining({ idempotencyKey: "attempt_replay", tenantId: "tenant_1" })
);
expect(queue?.close).toHaveBeenCalledOnce();
expect(recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "webhook.replayRequested", targetId: "attempt_old" }));
});
it("rejects delivered attempts so operators cannot duplicate successful webhooks", async () => {
const { deps } = makeDeps(makeAttempt({ success: true, status: 204 }));
await expect(
requestWebhookReplay({ attemptId: "attempt_old", reason: "Bitte erneut senden", actorUserId: "admin_1" }, deps)
).rejects.toMatchObject({ code: "REPLAY_NOT_ALLOWED" });
});
it("marks the fresh attempt failed when the queue is unavailable", async () => {
const { deps, db } = makeDeps(makeAttempt(), null);
await expect(
requestWebhookReplay({ attemptId: "attempt_old", reason: "Provider Timeout erneut ausliefern", actorUserId: "admin_1" }, deps)
).rejects.toBeInstanceOf(AdminWebhookInboxError);
expect(db.eventWebhookAttempt.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: "attempt_replay" },
data: expect.objectContaining({ success: false, status: 503, message: "admin.webhooks.messages.queueUnavailable" }),
})
);
});
});
@@ -0,0 +1,231 @@
import { buildWebhookDeliveryJob, enqueueJob, queueNames, resolveRedisConnectionOptionsFromProcessEnv, type TypedQueue } from "@hivegrid/queue";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
import { assertAdminActionReason, recordAdminAction, type AdminActionAuditContext } from "./admin-action-audit.server";
type EmailQueue = TypedQueue<typeof queueNames.email>;
const WEBHOOK_REPLAY_REQUESTED_MESSAGE_KEY = "admin.webhooks.messages.replayRequested";
const WEBHOOK_QUEUE_UNAVAILABLE_MESSAGE_KEY = "admin.webhooks.messages.queueUnavailable";
type WebhookAttemptForReplay = {
id: string;
endpoint: string;
success: boolean | null;
status: number | null;
eventId: string;
event: {
id: string;
name: string;
data: string;
resource: string | null;
tenantId: string | null;
};
};
export type AdminWebhookInboxDb = {
eventWebhookAttempt: {
findUnique(args: {
where: { id: string };
select: {
id: true;
endpoint: true;
success: true;
status: true;
eventId: true;
event: {
select: {
id: true;
name: true;
data: true;
resource: true;
tenantId: true;
};
};
};
}): Promise<WebhookAttemptForReplay | null>;
create(args: {
data: {
eventId: string;
endpoint: string;
startedAt: Date;
message: string;
};
}): Promise<{ id: string }>;
update(args: {
where: { id: string };
data: {
finishedAt: Date;
success: boolean;
status: number;
message: string;
};
}): Promise<unknown>;
};
};
export type AdminWebhookInboxDeps = {
readonly db: AdminWebhookInboxDb;
readonly now: () => Date;
readonly createQueue: () => Promise<EmailQueue | null>;
readonly enqueue: typeof enqueueJob;
readonly recordAction: (context: AdminActionAuditContext) => Promise<void>;
};
export class AdminWebhookInboxError extends Error {
override readonly name = "AdminWebhookInboxError";
readonly i18nKey: string;
constructor(readonly code: "ATTEMPT_NOT_FOUND" | "REPLAY_NOT_ALLOWED" | "INVALID_EVENT_DATA" | "QUEUE_UNAVAILABLE") {
super(code);
this.i18nKey = `admin.webhooks.errors.${code}`;
}
}
async function createConfiguredEmailQueue(): Promise<EmailQueue | null> {
const connection = resolveRedisConnectionOptionsFromProcessEnv();
if (!connection) return null;
// Lazy-load the BullMQ runtime through an indirect specifier so the web build
// never statically resolves the `@hivegrid/queue/runtime` -> /dev/null alias
// (see apps/web/vite.config.ts). Matches the pattern used by every other
// server-only queue producer in the web app.
const queueRuntimeModule = "@hivegrid/queue/runtime";
const { createQueue } = (await import(/* @vite-ignore */ queueRuntimeModule)) as typeof import("@hivegrid/queue/runtime");
return createQueue(queueNames.email, { connection });
}
function defaultDeps(): AdminWebhookInboxDeps {
return {
db: db as unknown as AdminWebhookInboxDb,
now: () => new Date(),
createQueue: createConfiguredEmailQueue,
enqueue: enqueueJob,
recordAction: recordAdminAction,
};
}
function parseEventPayload(data: string): unknown {
try {
return JSON.parse(data);
} catch {
throw new AdminWebhookInboxError("INVALID_EVENT_DATA");
}
}
function assertReplayAllowed(attempt: Pick<WebhookAttemptForReplay, "success" | "status">): void {
if (attempt.success === false || (attempt.status !== null && attempt.status >= 400)) return;
throw new AdminWebhookInboxError("REPLAY_NOT_ALLOWED");
}
export type RequestWebhookReplayInput = {
readonly attemptId: string;
readonly reason: string;
readonly actorUserId: string | null;
readonly actorEmail?: string | null;
readonly request?: Request;
};
export async function requestWebhookReplay(input: RequestWebhookReplayInput, deps: AdminWebhookInboxDeps = defaultDeps()): Promise<{ replayAttemptId: string }> {
const reason = assertAdminActionReason(input.reason);
const attempt = await deps.db.eventWebhookAttempt.findUnique({
where: { id: input.attemptId },
select: {
id: true,
endpoint: true,
success: true,
status: true,
eventId: true,
event: { select: { id: true, name: true, data: true, resource: true, tenantId: true } },
},
});
if (!attempt) throw new AdminWebhookInboxError("ATTEMPT_NOT_FOUND");
assertReplayAllowed(attempt);
const execute = () => executeWebhookReplay(input, reason, attempt, deps);
return attempt.event.tenantId ? runWithRlsContext({ tenantId: attempt.event.tenantId }, execute) : execute();
}
async function executeWebhookReplay(
input: RequestWebhookReplayInput,
reason: string,
attempt: WebhookAttemptForReplay,
deps: AdminWebhookInboxDeps,
): Promise<{ replayAttemptId: string }> {
const now = deps.now();
const replayAttempt = await deps.db.eventWebhookAttempt.create({
data: {
eventId: attempt.eventId,
endpoint: attempt.endpoint,
startedAt: now,
message: WEBHOOK_REPLAY_REQUESTED_MESSAGE_KEY,
},
});
const queue = await deps.createQueue();
if (!queue) {
await deps.db.eventWebhookAttempt.update({
where: { id: replayAttempt.id },
data: {
finishedAt: deps.now(),
success: false,
status: 503,
message: WEBHOOK_QUEUE_UNAVAILABLE_MESSAGE_KEY,
},
});
throw new AdminWebhookInboxError("QUEUE_UNAVAILABLE");
}
try {
const descriptor = buildWebhookDeliveryJob({
url: attempt.endpoint,
method: "POST",
eventName: attempt.event.name,
body: parseEventPayload(attempt.event.data),
...(attempt.event.tenantId ? { tenantId: attempt.event.tenantId } : {}),
metadata: {
legacyAttemptId: replayAttempt.id,
legacyAttemptTenantId: attempt.event.tenantId,
adminReplayOfAttemptId: attempt.id,
actorUserId: input.actorUserId ?? null,
},
});
await deps.enqueue(queue, descriptor, {
idempotencyKey: replayAttempt.id,
tenantId: attempt.event.tenantId,
});
} catch {
await deps.db.eventWebhookAttempt.update({
where: { id: replayAttempt.id },
data: {
finishedAt: deps.now(),
success: false,
status: 503,
message: WEBHOOK_QUEUE_UNAVAILABLE_MESSAGE_KEY,
},
});
throw new AdminWebhookInboxError("QUEUE_UNAVAILABLE");
} finally {
await queue.close();
}
await deps.recordAction({
action: "webhook.replayRequested",
actorUserId: input.actorUserId,
actorEmail: input.actorEmail ?? null,
targetKind: "eventWebhookAttempt",
targetId: attempt.id,
reason,
after: {
replayAttemptId: replayAttempt.id,
eventId: attempt.eventId,
eventName: attempt.event.name,
eventResource: attempt.event.resource,
tenantId: attempt.event.tenantId,
},
request: input.request,
});
return { replayAttemptId: replayAttempt.id };
}
@@ -2,11 +2,20 @@ import { describe, expect, it } from "vitest";
import {
AdminFallbackLoginRejected,
assertAdminFallbackLoginAllowed,
assertAdminFallbackLoginAllowedForIdentity,
evaluateAdminFallbackLogin,
isCompletedAdminFallbackLoginResponse,
isAdminFallbackUiVisible,
readAdminFallbackPolicy,
} from "./admin-fallback.server";
const localFallbackEnv = {
NODE_ENV: "development",
LOCAL_DEV_CREDENTIALS: "1",
ADMIN_APP_HOST: "admin.localhost:3000",
DATABASE_URL: "postgresql://postgres:postgres@127.0.0.1:5432/hivegrid",
};
describe("readAdminFallbackPolicy", () => {
it("returns disabled+empty by default", () => {
expect(readAdminFallbackPolicy({})).toEqual({ enabled: false, allowlist: [] });
@@ -15,6 +24,7 @@ describe("readAdminFallbackPolicy", () => {
it("parses ADMIN_FALLBACK_LOGIN_EMAILS comma-separated, lowercased", () => {
expect(
readAdminFallbackPolicy({
...localFallbackEnv,
ADMIN_FALLBACK_LOGIN_ENABLED: "true",
ADMIN_FALLBACK_LOGIN_EMAILS: " Bootstrap@example.test , ops@example.test , ",
})
@@ -26,10 +36,20 @@ describe("readAdminFallbackPolicy", () => {
it("accepts common truthy values", () => {
for (const value of ["1", "true", "yes", "on", "TRUE"]) {
expect(readAdminFallbackPolicy({ ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(true);
expect(readAdminFallbackPolicy({ ...localFallbackEnv, ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(true);
}
});
it("fails closed outside the disposable local development contract", () => {
expect(
readAdminFallbackPolicy({
...localFallbackEnv,
NODE_ENV: "production",
ADMIN_FALLBACK_LOGIN_ENABLED: "true",
}).enabled
).toBe(false);
});
it("rejects non-truthy values", () => {
for (const value of ["0", "false", "no", "", "off", "maybe"]) {
expect(readAdminFallbackPolicy({ ADMIN_FALLBACK_LOGIN_ENABLED: value }).enabled).toBe(false);
@@ -71,7 +91,9 @@ describe("assertAdminFallbackLoginAllowed", () => {
});
it("throws AdminFallbackLoginRejected when not in allowlist", () => {
expect(() => assertAdminFallbackLoginAllowed("nobody@example.test", { enabled: true, allowlist: ["other@example.test"] })).toThrowError(AdminFallbackLoginRejected);
expect(() => assertAdminFallbackLoginAllowed("nobody@example.test", { enabled: true, allowlist: ["other@example.test"] })).toThrowError(
AdminFallbackLoginRejected
);
});
it("passes silently when both conditions are met", () => {
@@ -79,10 +101,62 @@ describe("assertAdminFallbackLoginAllowed", () => {
});
});
describe("assertAdminFallbackLoginAllowedForIdentity", () => {
it("does not apply the emergency admin policy to tenant identities", () => {
expect(() => assertAdminFallbackLoginAllowedForIdentity({ email: "tenant@example.test", admin: null }, { enabled: false, allowlist: [] })).not.toThrow();
});
it("requires both emergency gates for an AdminUser on every host", () => {
expect(() =>
assertAdminFallbackLoginAllowedForIdentity(
{ email: "admin@example.test", admin: { userId: "admin_1" } },
{ enabled: false, allowlist: ["admin@example.test"] }
)
).toThrowError(AdminFallbackLoginRejected);
expect(() =>
assertAdminFallbackLoginAllowedForIdentity(
{ email: "admin@example.test", admin: { userId: "admin_1" } },
{ enabled: true, allowlist: ["admin@example.test"] }
)
).not.toThrow();
});
});
describe("isAdminFallbackUiVisible", () => {
it("reflects enabled flag only (allowlist intentionally ignored at UI layer)", () => {
expect(isAdminFallbackUiVisible({ ADMIN_FALLBACK_LOGIN_ENABLED: "true" })).toBe(true);
expect(isAdminFallbackUiVisible({ ADMIN_FALLBACK_LOGIN_ENABLED: "false" })).toBe(false);
expect(isAdminFallbackUiVisible({ ...localFallbackEnv, ADMIN_FALLBACK_LOGIN_ENABLED: "true" })).toBe(true);
expect(isAdminFallbackUiVisible({ ...localFallbackEnv, ADMIN_FALLBACK_LOGIN_ENABLED: "false" })).toBe(false);
expect(isAdminFallbackUiVisible({})).toBe(false);
});
});
describe("isCompletedAdminFallbackLoginResponse", () => {
it("accepts only a redirect carrying the completed login session cookie", () => {
expect(
isCompletedAdminFallbackLoginResponse(
new Response(null, {
status: 302,
headers: { Location: "/dashboard", "Set-Cookie": "__Host-hivegrid_admin_session=signed; Path=/; HttpOnly; Secure" },
})
)
).toBe(true);
});
it("rejects credential errors, MFA-pending responses, and redirects without a session", () => {
expect(isCompletedAdminFallbackLoginResponse(Response.json({ error: "invalid" }, { status: 400 }))).toBe(false);
expect(
isCompletedAdminFallbackLoginResponse(
Response.json({ requiresMfa: true }, { status: 200, headers: { "Set-Cookie": "hivegrid_session=pending; Path=/; HttpOnly" } })
)
).toBe(false);
expect(isCompletedAdminFallbackLoginResponse(new Response(null, { status: 302, headers: { Location: "/login" } }))).toBe(false);
expect(
isCompletedAdminFallbackLoginResponse(
new Response(null, { status: 302, headers: { "Set-Cookie": "__Host-hivegrid_app_session=signed; Path=/; Secure" } })
)
).toBe(false);
expect(
isCompletedAdminFallbackLoginResponse(new Response(null, { status: 302, headers: { "Set-Cookie": "hivegrid_session=legacy-parent-domain; Path=/" } }))
).toBe(false);
});
});
@@ -11,6 +11,7 @@
* invoke `assertAdminFallbackLoginAllowed` before validating credentials
* and audit-log every fallback attempt via the admin-sso audit helper.
*/
import { assertLocalCredentialsEnvironment } from "~/utils/db/seed/localCredentialsEnvironment.server";
const TRUE_VALUES = new Set(["1", "true", "yes", "on"]);
@@ -21,7 +22,14 @@ export type AdminFallbackPolicy = {
export function readAdminFallbackPolicy(env: Record<string, string | undefined> = process.env): AdminFallbackPolicy {
const rawEnabled = (env.ADMIN_FALLBACK_LOGIN_ENABLED ?? "").trim().toLowerCase();
const enabled = TRUE_VALUES.has(rawEnabled);
let localEnvironmentAllowed = false;
try {
assertLocalCredentialsEnvironment(env);
localEnvironmentAllowed = true;
} catch {
localEnvironmentAllowed = false;
}
const enabled = TRUE_VALUES.has(rawEnabled) && localEnvironmentAllowed;
const rawList = env.ADMIN_FALLBACK_LOGIN_EMAILS ?? "";
const allowlist = rawList
.split(",")
@@ -34,10 +42,7 @@ export type FallbackEvaluation =
| { readonly ok: true; readonly policy: AdminFallbackPolicy }
| { readonly ok: false; readonly reason: "disabled" | "email-not-allowlisted" };
export function evaluateAdminFallbackLogin(
email: string,
policy: AdminFallbackPolicy = readAdminFallbackPolicy()
): FallbackEvaluation {
export function evaluateAdminFallbackLogin(email: string, policy: AdminFallbackPolicy = readAdminFallbackPolicy()): FallbackEvaluation {
if (!policy.enabled) {
return { ok: false, reason: "disabled" };
}
@@ -68,6 +73,20 @@ export function assertAdminFallbackLoginAllowed(email: string, policy?: AdminFal
}
}
/**
* Enforce the emergency fallback policy only when the resolved identity is an
* admin. Keeping this identity-aware guard in one place prevents app-host
* login paths from accidentally bypassing the explicit emergency policy.
*/
export function assertAdminFallbackLoginAllowedForIdentity(
identity: { readonly email: string; readonly admin?: unknown | null },
policy?: AdminFallbackPolicy
): void {
if (identity.admin) {
assertAdminFallbackLoginAllowed(identity.email, policy);
}
}
/**
* UI-side helper: true iff the admin login page should reveal the
* fallback toggle at all. The actual email-allowlist check happens
@@ -76,3 +95,11 @@ export function assertAdminFallbackLoginAllowed(email: string, policy?: AdminFal
export function isAdminFallbackUiVisible(env: Record<string, string | undefined> = process.env): boolean {
return readAdminFallbackPolicy(env).enabled;
}
export function isCompletedAdminFallbackLoginResponse(response: Response): boolean {
if (response.status < 300 || response.status >= 400) {
return false;
}
const setCookie = response.headers.get("set-cookie") ?? "";
return ["__Host-hivegrid_admin_session=", "hivegrid_admin_session="].some((name) => setCookie.includes(name));
}
@@ -1,150 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
import { getUserSession } from "~/utils/session.server";
import { getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
import {
requireAdminMfaForAction,
SENSITIVE_ADMIN_ACTIONS,
isSensitiveAdminAction,
} from "./admin-mfa-gate.server";
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: vi.fn(() => ({ routing: { appUrl: "https://app.example.test" } })),
}));
vi.mock("~/utils/auth/mfa/enforcement.server", () => ({
enforceAdminMfa: vi.fn(),
}));
vi.mock("~/utils/auth/mfa/step-up.server", () => ({
checkMfaStepUpState: vi.fn(),
}));
vi.mock("~/utils/app/CrossHostUrls", () => ({
absoluteAppRootPath: vi.fn(() => "https://app.example.test"),
}));
vi.mock("~/utils/session.server", () => ({
getUserSession: vi.fn(),
}));
vi.mock("~/utils/db/users.db.server", () => ({
getUser: vi.fn(),
getUserTotpStatus: vi.fn(),
}));
vi.mock("~/modules/admin-sso/audit.server", () => ({
writeAdminSsoAuditEvent: vi.fn(),
}));
const enforceAdminMfaMock = vi.mocked(enforceAdminMfa);
const checkMfaStepUpStateMock = vi.mocked(checkMfaStepUpState);
const getUserSessionMock = vi.mocked(getUserSession);
const getUserMock = vi.mocked(getUser);
const getUserTotpStatusMock = vi.mocked(getUserTotpStatus);
const writeAdminSsoAuditEventMock = vi.mocked(writeAdminSsoAuditEvent);
beforeEach(() => {
vi.clearAllMocks();
getUserSessionMock.mockResolvedValue({ get: vi.fn() } as never);
getUserMock.mockResolvedValue({ id: "user_1", admin: true } as never);
getUserTotpStatusMock.mockResolvedValue({ enabled: true } as never);
checkMfaStepUpStateMock.mockReturnValue({
verified: true,
state: { userId: "user_1", method: "totp", verifiedAt: "2026-05-25T12:00:00.000Z" },
ageMs: 1000,
});
enforceAdminMfaMock.mockReturnValue({ allowed: true, reason: "allowed", redirectTo: "/admin" });
writeAdminSsoAuditEventMock.mockResolvedValue(undefined);
});
describe("SENSITIVE_ADMIN_ACTIONS taxonomy", () => {
it("includes the spec-required actions", () => {
expect(SENSITIVE_ADMIN_ACTIONS).toContain("impersonation.start");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("tenant.delete");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("permission.grant");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("audit.export");
expect(SENSITIVE_ADMIN_ACTIONS).toContain("data.export");
});
it("typeguard accepts known actions and rejects unknown", () => {
expect(isSensitiveAdminAction("impersonation.start")).toBe(true);
expect(isSensitiveAdminAction("tenant.delete")).toBe(true);
expect(isSensitiveAdminAction("totally-random")).toBe(false);
expect(isSensitiveAdminAction("")).toBe(false);
});
});
describe("requireAdminMfaForAction", () => {
it("returns the actor and writes success audit when MFA enforcement allows the action", async () => {
const request = new Request("https://admin.example.test/admin/accounts");
await expect(requireAdminMfaForAction(request, "tenant.delete", "user_1")).resolves.toEqual({
userId: "user_1",
action: "tenant.delete",
});
expect(getUserSessionMock).toHaveBeenCalledWith(request);
expect(getUserMock).toHaveBeenCalledWith("user_1");
expect(getUserTotpStatusMock).toHaveBeenCalledWith("user_1");
expect(enforceAdminMfaMock).toHaveBeenCalledWith(
expect.objectContaining({
requestUrl: request.url,
userId: "user_1",
isAdmin: true,
redirectMode: "host-aware",
appFallbackPath: "https://app.example.test",
}),
);
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.mfa.app.challenge.success",
actorAdminUserId: "user_1",
request,
meta: { action: "tenant.delete" },
}),
);
});
it("audits and throws a redirect response when enforcement returns a Response", async () => {
const request = new Request("https://admin.example.test/admin/accounts");
const redirectResponse = new Response(null, {
status: 302,
headers: { Location: "/admin/security/mfa-challenge" },
});
enforceAdminMfaMock.mockReturnValue(redirectResponse as never);
await expect(requireAdminMfaForAction(request, "audit.export", "user_1")).rejects.toBe(redirectResponse);
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: "user_1",
request,
meta: { action: "audit.export", reason: "redirect-response" },
}),
);
});
it("audits denied enforcement and throws a redirect to the challenge path", async () => {
const request = new Request("https://admin.example.test/admin/accounts");
enforceAdminMfaMock.mockReturnValue({
allowed: false,
reason: "step-up-missing",
redirectTo: "/admin/security/mfa-challenge?redirectTo=%2Fadmin%2Faccounts",
});
await expect(requireAdminMfaForAction(request, "permission.grant", "user_1")).rejects.toMatchObject({
status: 302,
});
expect(writeAdminSsoAuditEventMock).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: "user_1",
request,
meta: { action: "permission.grant", reason: "step-up-missing" },
}),
);
});
});
@@ -1,94 +0,0 @@
/**
* Phase 09 Task #82 — App-MFA gate for sensitive admin actions.
*
* Wrapper on top of the existing `enforceAdminMfa` helper (Phase 01 #26
* consolidated otpauth TOTP). Adds an action-keyed taxonomy so callers
* inside admin route handlers can declare intent without re-implementing
* the step-up plumbing.
*
* The wrapper itself does NOT touch the database or generate new TOTP
* secrets — that is owned by the existing /admin/security/mfa-* routes.
* Calling it just (a) checks the step-up cache, (b) throws a Response
* redirect when challenge is required.
*/
import { redirect } from "react-router";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { enforceAdminMfa } from "~/utils/auth/mfa/enforcement.server";
import { checkMfaStepUpState } from "~/utils/auth/mfa/step-up.server";
import { absoluteAppRootPath } from "~/utils/app/CrossHostUrls";
import { getUserSession } from "~/utils/session.server";
import { getUser, getUserTotpStatus } from "~/utils/db/users.db.server";
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
/**
* Canonical taxonomy of sensitive admin actions. Kept as a closed union
* so a typo in a caller surfaces as a TS error rather than silently
* skipping the gate.
*/
export const SENSITIVE_ADMIN_ACTIONS = [
"impersonation.start",
"tenant.delete",
"permission.grant",
"audit.export",
"data.export",
] as const;
export type SensitiveAdminAction = (typeof SENSITIVE_ADMIN_ACTIONS)[number];
export function isSensitiveAdminAction(value: string): value is SensitiveAdminAction {
return (SENSITIVE_ADMIN_ACTIONS as readonly string[]).includes(value);
}
export type AdminMfaGateResult = {
readonly userId: string;
readonly action: SensitiveAdminAction;
};
/**
* Throws a Response (redirect to /admin/security/mfa-challenge or to
* /admin/security/mfa-enroll) when step-up is missing/stale; otherwise
* returns the actor user id for downstream audit logging.
*/
export async function requireAdminMfaForAction(
request: Request,
action: SensitiveAdminAction,
actorUserId: string,
): Promise<AdminMfaGateResult> {
const session = await getUserSession(request);
const actor = await getUser(actorUserId);
const totpStatus = actor ? await getUserTotpStatus(actor.id) : null;
const enforcement = enforceAdminMfa({
requestUrl: request.url,
userId: actor?.id,
isAdmin: Boolean(actor?.admin),
totpStatus,
stepUp: actor ? checkMfaStepUpState(session, actor.id) : { verified: false, reason: "missing" },
redirectMode: "host-aware",
appFallbackPath: absoluteAppRootPath(loadRequiredWebConfig().routing),
});
if (enforcement instanceof Response) {
await writeAdminSsoAuditEvent({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: actorUserId,
request,
meta: { action, reason: "redirect-response" },
});
throw enforcement;
}
if (!enforcement.allowed) {
await writeAdminSsoAuditEvent({
action: "admin.mfa.app.challenge.failure",
actorAdminUserId: actorUserId,
request,
meta: { action, reason: enforcement.reason ?? "denied" },
});
throw redirect(enforcement.redirectTo);
}
await writeAdminSsoAuditEvent({
action: "admin.mfa.app.challenge.success",
actorAdminUserId: actorUserId,
request,
meta: { action },
});
return { userId: actorUserId, action };
}
@@ -0,0 +1,50 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db/users.db.server", () => ({ getUserTotpStatus: vi.fn() }));
vi.mock("~/utils/session.server", () => ({ commitPendingMfaLoginCookie: vi.fn() }));
import { getUserTotpStatus } from "~/utils/db/users.db.server";
import { commitPendingMfaLoginCookie } from "~/utils/session.server";
import { beginAlternativeLoginMfa } from "./alternative-login-mfa.server";
const request = new Request("https://app.example.test/auth/callback");
describe("alternative login MFA transition", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(commitPendingMfaLoginCookie).mockResolvedValue("hivegrid_session=pending; HttpOnly");
});
it("creates pending state whenever TOTP is enabled", async () => {
vi.mocked(getUserTotpStatus).mockResolvedValue({ enabled: true } as never);
await expect(
beginAlternativeLoginMfa({ request, userId: "user_1", redirectTo: "/acme/dashboard", primaryMethod: "magic-link" }),
).resolves.toEqual({ required: true, setCookie: "hivegrid_session=pending; HttpOnly" });
expect(commitPendingMfaLoginCookie).toHaveBeenCalledWith(request, {
userId: "user_1",
redirectTo: "/acme/dashboard",
primaryMethod: "magic-link",
});
});
it("allows the primary flow to finish only when TOTP is explicitly disabled", async () => {
vi.mocked(getUserTotpStatus).mockResolvedValue({ enabled: false } as never);
await expect(
beginAlternativeLoginMfa({ request, userId: "user_1", redirectTo: "/", primaryMethod: "admin-sso" }),
).resolves.toEqual({ required: false });
expect(commitPendingMfaLoginCookie).not.toHaveBeenCalled();
});
it("fails closed when MFA status cannot be resolved", async () => {
vi.mocked(getUserTotpStatus).mockResolvedValue(null);
await expect(
beginAlternativeLoginMfa({ request, userId: "user_1", redirectTo: "/", primaryMethod: "invitation" }),
).rejects.toThrow("MFA status is unavailable");
expect(commitPendingMfaLoginCookie).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,38 @@
import { getUserTotpStatus } from "~/utils/db/users.db.server";
import { commitPendingMfaLoginCookie, type PendingMfaPrimaryMethod } from "~/utils/session.server";
export const LOGIN_MFA_CHALLENGE_PATH = "/login-mfa";
export type AlternativeLoginMfaResult =
| { required: false }
| { required: true; setCookie: string };
/**
* Alternative primary factors without a separately verified upstream MFA
* assurance must not silently satisfy a configured second factor. Trusted
* device bypass is intentionally excluded from these flows: an enabled TOTP
* configuration always transitions to the pending MFA state.
*/
export async function beginAlternativeLoginMfa({
request,
userId,
redirectTo,
primaryMethod,
}: {
request: Request;
userId: string;
redirectTo: string;
primaryMethod: PendingMfaPrimaryMethod;
}): Promise<AlternativeLoginMfaResult> {
const status = await getUserTotpStatus(userId);
if (!status) {
throw new Error("MFA status is unavailable for the authenticated identity");
}
if (!status.enabled) {
return { required: false };
}
return {
required: true,
setCookie: await commitPendingMfaLoginCookie(request, { userId, redirectTo, primaryMethod }),
};
}
@@ -0,0 +1,57 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { getTrustedClientIp, loadRequiredWebConfig } = vi.hoisted(() => ({
getTrustedClientIp: vi.fn(),
loadRequiredWebConfig: vi.fn(),
}));
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig }));
vi.mock("~/utils/server/IpUtils", () => ({ getTrustedClientIp }));
import { getPseudonymousAuthBucketKey } from "./auth-rate-limit-key.server";
describe("pseudonymous auth rate-limit keys", () => {
beforeEach(() => {
vi.clearAllMocks();
loadRequiredWebConfig.mockReturnValue({ cryptoSecret: "crypto-secret", sessionSecret: "session-secret" });
getTrustedClientIp.mockReturnValue("203.0.113.10");
});
it("normalizes identifiers and keeps the pair bucket pseudonymous", () => {
const request = new Request("https://app.example.test/login");
const first = getPseudonymousAuthBucketKey({ request, action: "login", identifier: " Ada@Example.test " });
const second = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "ada@example.test" });
expect(first).toBe(second);
expect(first).toMatch(/^[a-f0-9]{64}$/);
expect(first).not.toContain("ada@example.test");
expect(first).not.toContain("203.0.113.10");
});
it("separates client-only and identifier-only dimensions", () => {
const request = new Request("https://app.example.test/login");
const client = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "ada@example.test", scope: "client" });
const clientWithOtherIdentifier = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "other@example.test", scope: "client" });
const identifier = getPseudonymousAuthBucketKey({ request, action: "login", identifier: "ada@example.test", scope: "identifier" });
getTrustedClientIp.mockReturnValue(null);
const identifierFromUnknownClient = getPseudonymousAuthBucketKey({
request,
action: "login",
identifier: "ada@example.test",
scope: "identifier",
});
expect(client).toBe(clientWithOtherIdentifier);
expect(identifier).toBe(identifierFromUnknownClient);
expect(client).not.toBe(identifier);
});
it("falls back to the session secret and rejects a missing key", () => {
const request = new Request("https://app.example.test/login");
loadRequiredWebConfig.mockReturnValueOnce({ cryptoSecret: "", sessionSecret: "session-secret" });
expect(getPseudonymousAuthBucketKey({ request, action: "login" })).toMatch(/^[a-f0-9]{64}$/);
loadRequiredWebConfig.mockReturnValueOnce({ cryptoSecret: "", sessionSecret: "" });
expect(() => getPseudonymousAuthBucketKey({ request, action: "login" })).toThrow("Auth rate-limit key secret is unavailable.");
});
});
@@ -0,0 +1,53 @@
import { createHmac } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getTrustedClientIp } from "~/utils/server/IpUtils";
export type AuthThrottleAction =
| "login"
| "forgot-password"
| "reset-password"
| "mfa"
| "register"
| "registration-resend"
| "registration-verify"
| "invitation-view"
| "invitation-accept"
| "workspace-create-attempt"
| "workspace-create"
| "workspace-create-replay"
| "booking-submit"
| "lead-capture"
| "form-submit"
| "plugin-install"
| "plugin-settings"
| "oauth-register"
| "oauth-token"
| "oauth-revoke";
export type AuthThrottleKeyScope = "client" | "identifier" | "pair";
function getKeySecret(): string {
const { cryptoSecret, sessionSecret } = loadRequiredWebConfig();
const secret = cryptoSecret || sessionSecret;
if (!secret) {
throw new Error("Auth rate-limit key secret is unavailable.");
}
return secret;
}
/**
* Produces a stable HMAC bucket key without exposing enumerable identifiers or
* client addresses in Redis keys, metrics, or diagnostic snapshots.
*/
export function getPseudonymousAuthBucketKey(input: {
request: Request;
action: AuthThrottleAction;
identifier?: string | null;
scope?: AuthThrottleKeyScope;
}): string {
const scope = input.scope ?? "pair";
const ipAddress = scope === "identifier" ? "" : getTrustedClientIp(input.request) || "unknown";
const identifier = scope === "client" ? "" : input.identifier;
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
return createHmac("sha256", getKeySecret()).update(`v1\0${input.action}\0${scope}\0${ipAddress}\0${normalizedIdentifier}`).digest("hex");
}
@@ -1,65 +1,266 @@
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cache } from "~/utils/cache.server";
import { checkAuthRateLimit, getAuthRateLimitKey } from "./auth-rate-limit.server";
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => ({ cryptoSecret: "test-auth-rate-limit-secret", sessionSecret: "test-session-secret" }),
};
});
import { __resetAuthRateLimitStoreForTests, __setAuthRateLimitStoreForTests, checkAuthRateLimit, getAuthRateLimitKey } from "./auth-rate-limit.server";
function cloudflareHeaders(clientIp: string) {
return { "cf-connecting-ip": clientIp, "x-forwarded-for": `${clientIp}, 173.245.48.10` };
}
describe("auth rate limiting", () => {
let adapter: MemoryAdapter;
beforeEach(() => {
cache.clear();
vi.spyOn(Date, "now").mockReturnValue(new Date("2026-05-25T12:00:00.000Z").getTime());
adapter = new MemoryAdapter();
__setAuthRateLimitStoreForTests(createSharedStore({ namespace: "auth-rate-test", adapter }));
});
afterEach(() => {
__resetAuthRateLimitStoreForTests();
vi.restoreAllMocks();
cache.clear();
});
it("builds stable keys from action, client ip, and normalized identifier", () => {
it("builds stable pseudonymous keys from action, trusted client ip, and normalized identifier", () => {
const request = new Request("https://example.test/login", {
headers: { "cf-connecting-ip": "203.0.113.10" },
headers: cloudflareHeaders("203.0.113.10"),
});
expect(getAuthRateLimitKey({ request, action: "login", identifier: " Ada@Example.COM " })).toBe(
getAuthRateLimitKey({ request, action: "login", identifier: "ada@example.com" })
);
expect(getAuthRateLimitKey({ request, action: "login", identifier: "ada@example.com" })).not.toBe(
getAuthRateLimitKey({ request, action: "forgot-password", identifier: "ada@example.com" })
const normalized = getAuthRateLimitKey({ request, action: "login", identifier: "ada@example.com" });
expect(getAuthRateLimitKey({ request, action: "login", identifier: " Ada@Example.COM " })).toBe(normalized);
expect(getAuthRateLimitKey({ request, action: "forgot-password", identifier: "ada@example.com" })).not.toBe(normalized);
expect(normalized).toMatch(/^[a-f0-9]{64}$/);
expect(normalized).not.toContain("ada@example.com");
expect(normalized).not.toContain("203.0.113.10");
});
it("keeps registration verification capabilities and client IPs out of rate-limit keys", () => {
const verificationToken = "raw-registration-verification-capability";
const clientIp = "203.0.113.27";
const request = new Request("https://example.test/verify/token", {
headers: cloudflareHeaders(clientIp),
});
const key = getAuthRateLimitKey({ request, action: "registration-verify", identifier: verificationToken });
expect(key).toMatch(/^[a-f0-9]{64}$/u);
expect(key).not.toContain(verificationToken);
expect(key).not.toContain(clientIp);
});
it("keeps invitation capabilities out of view and acceptance bucket keys", async () => {
const invitationToken = "raw-workspace-invitation-capability";
const request = new Request(`https://example.test/invitation/${invitationToken}`, {
headers: cloudflareHeaders("203.0.113.41"),
});
for (const action of ["invitation-view", "invitation-accept"] as const) {
const key = getAuthRateLimitKey({ request, action, identifier: invitationToken });
expect(key).toMatch(/^[a-f0-9]{64}$/u);
expect(key).not.toContain(invitationToken);
await expect(checkAuthRateLimit({ request, action, identifier: invitationToken, limit: 2, windowMs: 30_000 })).resolves.toEqual({ allowed: true });
}
const storedKeys = [];
for await (const key of adapter.scan("*")) storedKeys.push(key);
expect(JSON.stringify(storedKeys)).not.toContain(invitationToken);
});
it("does not key on a spoofed leftmost X-Forwarded-For or X-Client-IP", () => {
const first = new Request("https://example.test/login", {
headers: { "x-forwarded-for": "9.9.9.9, 198.51.100.7", "x-client-ip": "8.8.8.8" },
});
const rotated = new Request("https://example.test/login", {
headers: { "x-forwarded-for": "4.4.4.4, 198.51.100.7", "x-client-ip": "1.1.1.1" },
});
expect(getAuthRateLimitKey({ request: first, action: "login", identifier: "ada@example.com" })).toBe(
getAuthRateLimitKey({ request: rotated, action: "login", identifier: "ada@example.com" }),
);
});
it("does not key on a spoofable X-Forwarded-For / X-Client-IP", () => {
// Both spoofable headers must be ignored, so a forged value cannot move the
// request into a fresh rate-limit bucket. Both requests collapse to the same
// (untrusted -> "unknown") key.
const forged = new Request("https://example.test/login", { headers: { "x-forwarded-for": "9.9.9.9", "x-client-ip": "8.8.8.8" } });
const bare = new Request("https://example.test/login", {});
expect(getAuthRateLimitKey({ request: forged, action: "login", identifier: "ada@example.com" })).toBe(
getAuthRateLimitKey({ request: bare, action: "login", identifier: "ada@example.com" })
);
});
it("allows requests up to the limit and returns retry timing after the limit", () => {
it("allows requests up to the atomic limit and returns retry timing after the limit", async () => {
const request = new Request("https://example.test/login", {
headers: { "cf-connecting-ip": "203.0.113.10" },
headers: cloudflareHeaders("203.0.113.10"),
});
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 2, windowMs: 30_000 };
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
expect(checkAuthRateLimit(options)).toEqual({ allowed: false, retryAfterSeconds: 30 });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
});
it("starts a new window after the cached counter expires", () => {
it("shares reservations between replicas using the same backing adapter", async () => {
const request = new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") });
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 1, windowMs: 30_000 };
const replicaA = createSharedStore({ namespace: "auth-rate-replicas", adapter });
const replicaB = createSharedStore({ namespace: "auth-rate-replicas", adapter });
__setAuthRateLimitStoreForTests(replicaA);
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
__setAuthRateLimitStoreForTests(replicaB);
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
});
it("permits exactly the configured number during a parallel burst", async () => {
const request = new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") });
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 5, windowMs: 30_000 };
const decisions = await Promise.all(Array.from({ length: 20 }, () => checkAuthRateLimit(options)));
expect(decisions.filter((decision) => decision.allowed)).toHaveLength(5);
expect(decisions.filter((decision) => !decision.allowed)).toHaveLength(15);
});
it("bounds one identifier across rotating trusted client addresses", async () => {
const decisions = [];
for (let index = 1; index <= 4; index += 1) {
decisions.push(
await checkAuthRateLimit({
request: new Request("https://example.test/login", { headers: cloudflareHeaders(`203.0.113.${index}`) }),
action: "login",
identifier: "ada@example.com",
limit: 1,
windowMs: 30_000,
})
);
}
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, true, false]);
});
it("honors an explicit global identifier cap across rotating trusted client addresses", async () => {
const decisions = [];
for (let index = 1; index <= 3; index += 1) {
decisions.push(
await checkAuthRateLimit({
request: new Request("https://example.test/register", { headers: cloudflareHeaders(`203.0.113.${index}`) }),
action: "register",
identifier: " Ada@Example.COM ",
limit: 5,
identifierLimit: 2,
windowMs: 60 * 60 * 1000,
})
);
}
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, false]);
const storedKeys = [];
for await (const key of adapter.scan("*")) storedKeys.push(key);
expect(JSON.stringify(storedKeys)).not.toContain("ada@example.com");
});
it("can disable the global identifier bucket while retaining client and pair limits", async () => {
const requestFor = (lastOctet: number) =>
new Request("https://example.test/register", {
headers: cloudflareHeaders(`203.0.113.${lastOctet}`),
});
const baseOptions = {
action: "register" as const,
identifier: "victim@example.test",
limit: 1,
identifierLimit: null,
windowMs: 60 * 60 * 1000,
};
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(1) })).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(2) })).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(3) })).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(1) })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 60 * 60,
});
const storedKeys = [];
for await (const key of adapter.scan("*")) storedKeys.push(key);
expect(storedKeys.some((key) => key.includes(":identifier:"))).toBe(false);
});
it("caps identifier churn per trusted client to bound live Redis keys", async () => {
const decisions = [];
for (let index = 1; index <= 11; index += 1) {
decisions.push(
await checkAuthRateLimit({
request: new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") }),
action: "login",
identifier: `generated-${index}@example.com`,
limit: 1,
windowMs: 30_000,
})
);
}
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, true, true, true, true, true, true, true, true, false]);
});
it("starts a new window after the shared counter expires", async () => {
const request = new Request("https://example.test/mfa", {
headers: { "cf-connecting-ip": "203.0.113.10" },
headers: cloudflareHeaders("203.0.113.10"),
});
const options = { request, action: "mfa" as const, identifier: "ada@example.com", limit: 1, windowMs: 10_000 };
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
expect(checkAuthRateLimit(options)).toEqual({ allowed: false, retryAfterSeconds: 10 });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 10 });
vi.mocked(Date.now).mockReturnValue(new Date("2026-05-25T12:00:11.000Z").getTime());
expect(checkAuthRateLimit(options)).toEqual({ allowed: true });
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
});
it("fails closed with a bounded retry interval when the shared store fails", async () => {
vi.spyOn(adapter, "eval").mockRejectedValueOnce(new Error("redis unavailable"));
const request = new Request("https://example.test/login");
await expect(checkAuthRateLimit({ request, action: "login", identifier: "ada@example.com", limit: 2, windowMs: 30_000 })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 30,
});
});
it("fails closed before an invitation lookup when the shared throttle store is unavailable", async () => {
vi.spyOn(adapter, "eval").mockRejectedValueOnce(new Error("redis unavailable"));
const invitationToken = "raw-workspace-invitation-capability";
const request = new Request(`https://example.test/invitation/${invitationToken}`);
await expect(
checkAuthRateLimit({
request,
action: "invitation-view",
identifier: invitationToken,
limit: 30,
windowMs: 15 * 60 * 1000,
})
).resolves.toEqual({ allowed: false, retryAfterSeconds: 15 * 60 });
});
it("fails closed for invalid limits and windows with bounded retry values", async () => {
const request = new Request("https://example.test/login");
await expect(checkAuthRateLimit({ request, action: "login", limit: 0, windowMs: 30_000 })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 30,
});
await expect(checkAuthRateLimit({ request, action: "login", limit: 1, windowMs: Number.NaN })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 1,
});
await expect(checkAuthRateLimit({ request, action: "login", limit: 10_001, windowMs: 24 * 60 * 60 * 1000 + 1 })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 86_400,
});
});
it("uses the configured window when the store returns an invalid TTL", async () => {
vi.spyOn(adapter, "eval").mockResolvedValueOnce([0, 0, 3]);
await expect(
checkAuthRateLimit({ request: new Request("https://example.test/login"), action: "login", identifier: null, limit: 2, windowMs: 30_000 })
).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
});
});
@@ -1,41 +1,167 @@
import { createHash } from "node:crypto";
import { cache } from "~/utils/cache.server";
import { getTrustedClientIp } from "~/utils/server/IpUtils";
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
import { getPseudonymousAuthBucketKey, type AuthThrottleAction } from "~/services/auth/auth-rate-limit-key.server";
import { getSharedStore } from "~/shared-store.server";
import { createScopedLogger } from "~/utils/logger.server";
type AuthRateLimitOptions = {
request: Request;
action: "login" | "forgot-password" | "reset-password" | "mfa";
action: AuthThrottleAction;
identifier?: string | null;
limit: number;
windowMs: number;
/** Optional hard cap shared by all trusted clients for one identifier. Null
* keeps the per-client and client/identifier pair buckets while disabling
* the globally poisonable identifier bucket for unauthenticated input. */
identifierLimit?: number | null;
/** Optional hard cap for one trusted client across identifier churn. */
clientLimit?: number;
};
type AuthRateLimitResult =
| { allowed: true }
| { allowed: false; retryAfterSeconds: number };
type AuthRateLimitResult = { allowed: true } | { allowed: false; retryAfterSeconds: number };
export function getAuthRateLimitKey({ request, action, identifier }: Omit<AuthRateLimitOptions, "limit" | "windowMs">) {
// Trusted proxy-set header only; leftmost X-Forwarded-For / X-Client-IP are
// client-spoofable and would let an attacker reset this per-IP auth throttle.
const ipAddress = getTrustedClientIp(request) || "unknown";
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
const digest = createHash("sha256").update(`${action}:${ipAddress}:${normalizedIdentifier}`).digest("hex");
return `auth-rate-limit:${action}:${digest}`;
}
const authRateLimitLogger = createScopedLogger("auth-rate-limit");
const MAX_WINDOW_MS = 24 * 60 * 60 * 1000;
const MAX_LIMIT = 10_000;
const PER_CLIENT_LIMIT_FACTOR = 10;
const PER_IDENTIFIER_LIMIT_FACTOR = 3;
export function checkAuthRateLimit(options: AuthRateLimitOptions): AuthRateLimitResult {
const key = getAuthRateLimitKey(options);
const now = Date.now();
const entry = cache.get(key)?.value as { count: number; resetAt: number } | undefined;
const current = entry && entry.resetAt > now ? entry : { count: 0, resetAt: now + options.windowMs };
const count = current.count + 1;
const AUTH_RATE_LIMIT_SCRIPT = `
local window = tonumber(ARGV[1])
local clientMax = tonumber(ARGV[2])
local identifierMax = tonumber(ARGV[3])
local pairMax = tonumber(ARGV[4])
local hasIdentifier = ARGV[5] == '1'
cache.set(key, { value: { count, resetAt: current.resetAt }, metadata: { createdTime: now } }, { ttl: Math.max(1, current.resetAt - now) });
local function reserve(key)
local current = redis.call('INCR', key)
if current == 1 then
redis.call('EXPIRE', key, window)
end
local ttl = redis.call('TTL', key)
if ttl <= 0 then ttl = window end
return current, ttl
end
if (count > options.limit) {
return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000)) };
local clientCurrent, clientTtl = reserve(KEYS[1])
if clientCurrent > clientMax then
return { 0, clientTtl, 1 }
end
if hasIdentifier then
local identifierCurrent, identifierTtl = reserve(KEYS[2])
if identifierCurrent > identifierMax then
return { 0, identifierTtl, 2 }
end
end
local pairCurrent, pairTtl = reserve(KEYS[3])
if pairCurrent > pairMax then
return { 0, pairTtl, 3 }
end
return { 1, pairTtl, 0 }
`;
MemoryAdapter.registerScript(AUTH_RATE_LIMIT_SCRIPT, async (adapter, keys, args) => {
const windowSeconds = Number.parseInt(args[0] ?? "0", 10);
const clientMax = Number.parseInt(args[1] ?? "0", 10);
const identifierMax = Number.parseInt(args[2] ?? "0", 10);
const pairMax = Number.parseInt(args[3] ?? "0", 10);
const hasIdentifier = args[4] === "1";
const reserve = async (key: string) => {
const current = await adapter.incr(key);
if (current === 1) await adapter.expire(key, windowSeconds);
return current;
};
const clientCurrent = await reserve(keys[0]);
if (clientCurrent > clientMax) return [0, windowSeconds, 1];
if (hasIdentifier) {
const identifierCurrent = await reserve(keys[1]);
if (identifierCurrent > identifierMax) return [0, windowSeconds, 2];
}
const pairCurrent = await reserve(keys[2]);
if (pairCurrent > pairMax) return [0, windowSeconds, 3];
return [1, windowSeconds, 0];
});
return { allowed: true };
let storeFactory: () => SharedStore = () => getSharedStore();
function normalizeWindowSeconds(windowMs: number): number {
if (!Number.isSafeInteger(windowMs) || windowMs <= 0 || windowMs > MAX_WINDOW_MS) {
throw new Error("Auth rate-limit window is outside the supported range.");
}
return Math.ceil(windowMs / 1000);
}
function validateLimit(limit: number): void {
if (!Number.isSafeInteger(limit) || limit <= 0 || limit > MAX_LIMIT) {
throw new Error("Auth rate-limit maximum is outside the supported range.");
}
}
/**
* Returns a stable, pseudonymous bucket key. The HMAC keeps enumerable email
* addresses and client IPs out of Redis keys and diagnostic snapshots.
*/
export function getAuthRateLimitKey({ request, action, identifier }: Omit<AuthRateLimitOptions, "limit" | "windowMs">) {
return getPseudonymousAuthBucketKey({ request, action, identifier });
}
/**
* Atomically reserves an auth attempt in the shared store. Store and
* configuration failures deny the request: losing the distributed throttle
* must never silently turn into an unlimited authentication endpoint.
*/
export async function checkAuthRateLimit(options: AuthRateLimitOptions): Promise<AuthRateLimitResult> {
const safeRetryAfterSeconds = Math.max(1, Math.ceil(Math.min(Math.max(options.windowMs || 0, 1000), MAX_WINDOW_MS) / 1000));
try {
validateLimit(options.limit);
if (options.identifierLimit !== undefined && options.identifierLimit !== null) validateLimit(options.identifierLimit);
if (options.clientLimit !== undefined) validateLimit(options.clientLimit);
const windowSeconds = normalizeWindowSeconds(options.windowMs);
const store = storeFactory();
const normalizedIdentifier = options.identifier?.trim().toLowerCase() ?? "";
const keyPrefix = `rl:auth:v1:${options.action}:${options.limit}:${windowSeconds}`;
const clientKey = getPseudonymousAuthBucketKey({ ...options, scope: "client" });
const identifierKey = getPseudonymousAuthBucketKey({ ...options, scope: "identifier" });
const pairKey = getPseudonymousAuthBucketKey({ ...options, scope: "pair" });
const clientLimit = options.clientLimit ?? Math.min(MAX_LIMIT, options.limit * PER_CLIENT_LIMIT_FACTOR);
const identifierLimit = options.identifierLimit ?? Math.min(MAX_LIMIT, options.limit * PER_IDENTIFIER_LIMIT_FACTOR);
const reserveIdentifierBucket = normalizedIdentifier.length > 0 && options.identifierLimit !== null;
const result = (await store.eval(
AUTH_RATE_LIMIT_SCRIPT,
[`${keyPrefix}:client:${clientKey}`, `${keyPrefix}:identifier:${identifierKey}`, `${keyPrefix}:pair:${pairKey}`],
[String(windowSeconds), String(clientLimit), String(identifierLimit), String(options.limit), reserveIdentifierBucket ? "1" : "0"]
)) as [number | string, number | string, number | string] | undefined;
const allowed = Number(result?.[0]) === 1;
const ttl = Number(result?.[1]);
if (!allowed) {
return {
allowed: false,
retryAfterSeconds: Number.isFinite(ttl) && ttl > 0 ? Math.ceil(ttl) : windowSeconds,
};
}
return { allowed: true };
} catch (error) {
authRateLimitLogger.error(
{
event: "auth.rate_limit.store_unavailable",
action: options.action,
errorName: error instanceof Error ? error.name : "UnknownError",
},
"Auth rate-limit reservation failed; request denied"
);
return { allowed: false, retryAfterSeconds: safeRetryAfterSeconds };
}
}
export function __setAuthRateLimitStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetAuthRateLimitStoreForTests(): void {
storeFactory = () => getSharedStore();
}
@@ -1,7 +1,9 @@
import { beforeEach, describe, expect, it } from "vitest";
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cache } from "~/utils/cache.server";
import {
__resetLoginCaptchaGateStoreForTests,
__setLoginCaptchaGateStoreForTests,
clearFailedLogins,
getFailedLoginCount,
LOGIN_CAPTCHA_AFTER_FAILURES,
@@ -10,20 +12,35 @@ import {
} from "./login-captcha-gate.server";
function req() {
return new Request("https://example.test/login");
return new Request("https://example.test/login", { headers: { "cf-connecting-ip": "203.0.113.10" } });
}
describe("login-captcha-gate", () => {
let adapter: MemoryAdapter;
beforeEach(() => {
cache.clear();
adapter = new MemoryAdapter();
__setLoginCaptchaGateStoreForTests(createSharedStore({ namespace: "login-captcha-test", adapter }));
});
it("starts at zero and increments per recorded failure", () => {
afterEach(() => {
__resetLoginCaptchaGateStoreForTests();
vi.restoreAllMocks();
});
it("starts at zero and atomically increments each recorded failure", async () => {
const request = req();
expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(0);
expect(recordFailedLogin({ request, identifier: "ada@example.test" })).toBe(1);
expect(recordFailedLogin({ request, identifier: "ada@example.test" })).toBe(2);
expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(2);
await expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).resolves.toBe(0);
await expect(recordFailedLogin({ request, identifier: "ada@example.test" })).resolves.toBe(1);
await expect(recordFailedLogin({ request, identifier: "ada@example.test" })).resolves.toBe(2);
await expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).resolves.toBe(2);
});
it("serializes concurrent failure reservations without losing increments", async () => {
const args = { request: req(), identifier: "ada@example.test" };
const counts = await Promise.all(Array.from({ length: 12 }, () => recordFailedLogin(args)));
expect([...counts].sort((a, b) => a - b)).toEqual(Array.from({ length: 12 }, (_, index) => index + 1));
await expect(getFailedLoginCount(args)).resolves.toBe(12);
});
it("requires a captcha only from the configured failure threshold", () => {
@@ -33,21 +50,74 @@ describe("login-captcha-gate", () => {
expect(loginRequiresCaptcha(LOGIN_CAPTCHA_AFTER_FAILURES + 2)).toBe(true);
});
it("clears the counter on a successful login", () => {
const request = req();
recordFailedLogin({ request, identifier: "ada@example.test" });
recordFailedLogin({ request, identifier: "ada@example.test" });
clearFailedLogins({ request, identifier: "ada@example.test" });
expect(getFailedLoginCount({ request, identifier: "ada@example.test" })).toBe(0);
it("shares failures and successful reset across replicas", async () => {
const args = { request: req(), identifier: "ada@example.test" };
const replicaA = createSharedStore({ namespace: "login-captcha-replicas", adapter });
const replicaB = createSharedStore({ namespace: "login-captcha-replicas", adapter });
__setLoginCaptchaGateStoreForTests(replicaA);
await recordFailedLogin(args);
await recordFailedLogin(args);
await recordFailedLogin(args);
__setLoginCaptchaGateStoreForTests(replicaB);
await expect(getFailedLoginCount(args)).resolves.toBe(3);
await clearFailedLogins(args);
__setLoginCaptchaGateStoreForTests(replicaA);
await expect(getFailedLoginCount(args)).resolves.toBe(0);
});
it("keys per identifier so a different email does not inherit the captcha gate", () => {
it("expires the bounded failure state after its fixed window", async () => {
const startedAt = new Date("2026-05-25T12:00:00.000Z").getTime();
vi.spyOn(Date, "now").mockReturnValue(startedAt);
adapter = new MemoryAdapter();
__setLoginCaptchaGateStoreForTests(createSharedStore({ namespace: "login-captcha-expiry", adapter }));
const args = { request: req(), identifier: "ada@example.test" };
await recordFailedLogin(args);
vi.mocked(Date.now).mockReturnValue(startedAt + 15 * 60 * 1000 + 1);
await expect(getFailedLoginCount(args)).resolves.toBe(0);
});
it("keys per identifier so a different email does not inherit the captcha gate", async () => {
const request = req();
recordFailedLogin({ request, identifier: "ada@example.test" });
recordFailedLogin({ request, identifier: "ada@example.test" });
recordFailedLogin({ request, identifier: "ada@example.test" });
expect(loginRequiresCaptcha(getFailedLoginCount({ request, identifier: "ada@example.test" }))).toBe(true);
expect(getFailedLoginCount({ request, identifier: "mallory@example.test" })).toBe(0);
expect(loginRequiresCaptcha(getFailedLoginCount({ request, identifier: "mallory@example.test" }))).toBe(false);
await recordFailedLogin({ request, identifier: "ada@example.test" });
await recordFailedLogin({ request, identifier: "ada@example.test" });
await recordFailedLogin({ request, identifier: "ada@example.test" });
expect(loginRequiresCaptcha(await getFailedLoginCount({ request, identifier: "ada@example.test" }))).toBe(true);
await expect(getFailedLoginCount({ request, identifier: "mallory@example.test" })).resolves.toBe(0);
});
it("fails closed by requiring captcha when the shared count cannot be read", async () => {
vi.spyOn(adapter, "get").mockRejectedValueOnce(new Error("redis unavailable"));
const count = await getFailedLoginCount({ request: req(), identifier: "ada@example.test" });
expect(loginRequiresCaptcha(count)).toBe(true);
});
it("fails closed when the persisted counter is malformed or negative", async () => {
vi.spyOn(adapter, "get").mockResolvedValueOnce("not-a-number").mockResolvedValueOnce("-1");
await expect(getFailedLoginCount({ request: req(), identifier: "ada@example.test" })).resolves.toBe(LOGIN_CAPTCHA_AFTER_FAILURES);
await expect(getFailedLoginCount({ request: req(), identifier: "ada@example.test" })).resolves.toBe(LOGIN_CAPTCHA_AFTER_FAILURES);
});
it("handles non-Error read failures without leaking the store payload", async () => {
vi.spyOn(adapter, "get").mockRejectedValueOnce("redis-secret");
await expect(getFailedLoginCount({ request: req(), identifier: "ada@example.test" })).resolves.toBe(LOGIN_CAPTCHA_AFTER_FAILURES);
});
it("propagates failed atomic writes so login cannot continue unthrottled", async () => {
vi.spyOn(adapter, "eval").mockRejectedValueOnce("write-secret");
await expect(recordFailedLogin({ request: req(), identifier: "ada@example.test" })).rejects.toBe("write-secret");
});
it("propagates failed resets so a successful login cannot claim the gate was cleared", async () => {
vi.spyOn(adapter, "del").mockRejectedValueOnce("reset-secret");
await expect(clearFailedLogins({ request: req(), identifier: "ada@example.test" })).rejects.toBe("reset-secret");
});
});
@@ -1,50 +1,119 @@
import { createHash } from "node:crypto";
import { createFixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
import { getPseudonymousAuthBucketKey } from "~/services/auth/auth-rate-limit-key.server";
import { getSharedStore } from "~/shared-store.server";
import { createScopedLogger } from "~/utils/logger.server";
import { cache } from "~/utils/cache.server";
import { getClientIPAddress } from "~/utils/server/IpUtils";
// Brute-Force-Soft-Gate fuer den Login (R-P2a): ab dem N-ten FEHLversuch (pro IP+Email)
// wird ein mCaptcha verlangt, bevor der Passwort-Check ueberhaupt laeuft. Freundlicher als
// ein harter Lockout und bremst automatisierte Versuche. Der separate Failure-Counter
// (nur Hochzaehlen bei Fehlschlag, Reset bei Erfolg) ergaenzt den generischen Rate-Limiter,
// der weiterhin als harter Backstop dient.
// Require the self-hosted CAPTCHA after this many failed password attempts for
// the same trusted-IP/identifier pair. The hard auth limiter remains the
// authoritative backstop when CAPTCHA is not configured.
export const LOGIN_CAPTCHA_AFTER_FAILURES = 3;
// Zeitfenster, in dem Fehlversuche zusammengezaehlt werden (gleitend, Reset bei Erfolg).
const FAILED_LOGIN_WINDOW_MS = 15 * 60 * 1000;
const FAILED_LOGIN_WINDOW_SECONDS = 15 * 60;
const FAILURE_COUNTER_PREFIX = "auth-login-failures";
// This ceiling protects integer arithmetic but is unreachable behind the hard
// login limiter. It also avoids an unbounded numeric counter during abuse.
const MAX_FAILURE_COUNT = 1_000_000;
type FailedLoginEntry = { count: number; resetAt: number };
type Identified = { request: Request; identifier?: string | null };
function failedLoginKey({ request, identifier }: Identified) {
const ipAddress = getClientIPAddress(request.headers)?.toString() ?? "unknown";
const normalizedIdentifier = identifier?.trim().toLowerCase() ?? "";
const digest = createHash("sha256").update(`login-failures:${ipAddress}:${normalizedIdentifier}`).digest("hex");
return `auth-login-failures:${digest}`;
const captchaGateLogger = createScopedLogger("login-captcha-gate");
let storeFactory: () => SharedStore = () => getSharedStore();
function failedLoginKey({ request, identifier }: Identified): string {
return getPseudonymousAuthBucketKey({ request, action: "login", identifier });
}
export function getFailedLoginCount(args: Identified): number {
const entry = cache.get(failedLoginKey(args))?.value as FailedLoginEntry | undefined;
if (!entry || entry.resetAt <= Date.now()) {
return 0;
function getCounter() {
const store = storeFactory();
const limiter = createFixedWindowRateLimiter({
store,
prefix: FAILURE_COUNTER_PREFIX,
windowSeconds: FAILED_LOGIN_WINDOW_SECONDS,
max: MAX_FAILURE_COUNT,
});
return { store, limiter };
}
function storageKey(key: string): string {
return `rl:fixed:${FAILURE_COUNTER_PREFIX}:${key}`;
}
/**
* Reads the replica-shared failure count. A store/configuration failure
* requires CAPTCHA instead of silently weakening the gate.
*/
export async function getFailedLoginCount(args: Identified): Promise<number> {
try {
const key = failedLoginKey(args);
const { store } = getCounter();
const raw = await store.get(storageKey(key));
if (raw === null) return 0;
const count = Number.parseInt(raw, 10);
if (!Number.isSafeInteger(count) || count < 0) {
captchaGateLogger.error(
{ event: "auth.captcha_failure_counter.invalid" },
"Login CAPTCHA failure counter was invalid; CAPTCHA required",
);
return LOGIN_CAPTCHA_AFTER_FAILURES;
}
return Math.min(count, MAX_FAILURE_COUNT);
} catch (error) {
captchaGateLogger.error(
{
event: "auth.captcha_failure_counter.read_failed",
errorName: error instanceof Error ? error.name : "UnknownError",
},
"Login CAPTCHA failure counter could not be read; CAPTCHA required",
);
return LOGIN_CAPTCHA_AFTER_FAILURES;
}
return entry.count;
}
export function recordFailedLogin(args: Identified): number {
const key = failedLoginKey(args);
const now = Date.now();
const entry = cache.get(key)?.value as FailedLoginEntry | undefined;
const current = entry && entry.resetAt > now ? entry : { count: 0, resetAt: now + FAILED_LOGIN_WINDOW_MS };
const count = current.count + 1;
cache.set(key, { value: { count, resetAt: current.resetAt }, metadata: { createdTime: now } }, { ttl: Math.max(1, current.resetAt - now) });
return count;
/** Atomically records a failed login and starts the bounded expiry window. */
export async function recordFailedLogin(args: Identified): Promise<number> {
try {
const key = failedLoginKey(args);
const { limiter } = getCounter();
const decision = await limiter.consume(key);
return decision.allowed ? MAX_FAILURE_COUNT - decision.remaining : MAX_FAILURE_COUNT;
} catch (error) {
captchaGateLogger.error(
{
event: "auth.captcha_failure_counter.write_failed",
errorName: error instanceof Error ? error.name : "UnknownError",
},
"Login CAPTCHA failure counter could not be updated; login denied",
);
throw error;
}
}
export function clearFailedLogins(args: Identified): void {
cache.delete(failedLoginKey(args));
/** Clears the shared gate after a successful primary authentication. */
export async function clearFailedLogins(args: Identified): Promise<void> {
try {
const key = failedLoginKey(args);
const { limiter } = getCounter();
await limiter.reset(key);
} catch (error) {
captchaGateLogger.error(
{
event: "auth.captcha_failure_counter.reset_failed",
errorName: error instanceof Error ? error.name : "UnknownError",
},
"Login CAPTCHA failure counter could not be reset; login denied",
);
throw error;
}
}
export function loginRequiresCaptcha(failedCount: number): boolean {
return failedCount >= LOGIN_CAPTCHA_AFTER_FAILURES;
}
export function __setLoginCaptchaGateStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetLoginCaptchaGateStoreForTests(): void {
storeFactory = () => getSharedStore();
}
@@ -0,0 +1,70 @@
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getAuthUserWithoutPasswordById, getLoginUserByEmail } from "@hivegrid/db/auth-boundary.server";
import { getTranslations } from "~/locale/i18next.server";
import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server";
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
import { AdminFallbackLoginRejected, assertAdminFallbackLoginAllowedForIdentity } from "~/services/auth/admin-fallback.server";
import { issueMagicLink } from "~/services/auth/magic-link.server";
import { validateCSRFToken } from "~/utils/session.server";
import { createScopedLogger } from "~/utils/logger.server";
const MAGIC_LINK_RESPONSE_FLOOR_MS = 1200;
const magicLinkLogger = createScopedLogger("auth.magic-link");
async function waitForMagicLinkResponseFloor(startedAt: number): Promise<void> {
const remaining = MAGIC_LINK_RESPONSE_FLOOR_MS - (Date.now() - startedAt);
if (remaining > 0) {
await new Promise((resolve) => setTimeout(resolve, remaining));
}
}
export async function handleMagicLinkLogin(request: Request, form: FormData): Promise<Response> {
await validateCSRFToken(request, { formData: form });
const email = (form.get("email") ?? "").toString().toLowerCase().trim();
if (!email) {
const { t } = await getTranslations(request);
return Response.json({ magicLinkRequest: true, fieldErrors: { email: t("account.login.magicLinkEmailRequired"), password: undefined } }, { status: 400 });
}
const rateLimit = await checkAuthRateLimit({ request, action: "login", identifier: email, limit: 5, windowMs: 15 * 60 * 1000 });
if (!rateLimit.allowed) {
return Response.json({ magicLinkSent: true, magicLinkEmail: email }, { headers: { "Retry-After": String(rateLimit.retryAfterSeconds) } });
}
const startedAt = Date.now();
if (loadRequiredWebConfig().magicLink.enabled) {
const loginUser = await getLoginUserByEmail(email);
const user = loginUser ? await getAuthUserWithoutPasswordById(loginUser.id) : null;
let identityAllowed = Boolean(user);
if (user) {
try {
assertAdminFallbackLoginAllowedForIdentity(user);
} catch (error) {
if (!(error instanceof AdminFallbackLoginRejected)) {
throw error;
}
identityAllowed = false;
await writeAdminSsoAuditEvent({
action: "admin.login.fallback.failure",
actorAdminUserId: user.admin?.userId,
request,
meta: { reason: error.reason, email, method: "magic-link", stage: "issue" },
});
}
}
if (loginUser && identityAllowed) {
try {
await issueMagicLink({ request, userId: loginUser.id, email, purpose: "login" });
} catch (error) {
// Token issuance and mail delivery are best-effort here. The generic
// response must not reveal whether the account exists.
magicLinkLogger.error({ errorName: error instanceof Error ? error.name : "UnknownError" }, "magic-link issuance failed");
}
}
}
// Apply the same minimum response time to disabled, unknown, denied, and
// successful identities so neither account nor AdminUser status leaks.
await waitForMagicLinkResponseFloor(startedAt);
return Response.json({ magicLinkSent: true, magicLinkEmail: email });
}
@@ -1,12 +1,24 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { consumeMagicLinkToken, createSignedMagicLinkToken, issueMagicLink, verifySignedMagicLinkToken } from "./magic-link.server";
import {
consumeMagicLinkToken,
createSignedMagicLinkToken,
issueMagicLink,
MagicLinkDisabledError,
verifySignedMagicLinkToken,
} from "./magic-link.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { getMailTranslator, getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import { db } from "~/utils/db.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
vi.mock("@hivegrid/config", () => ({
loadRequiredWebConfig: vi.fn(() => ({ cryptoSecret: "test-secret", sessionSecret: "session-secret" })),
loadRequiredWebConfig: vi.fn(() => ({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: true },
})),
}));
vi.mock("~/utils/db.server", () => ({
@@ -14,7 +26,7 @@ vi.mock("~/utils/db.server", () => ({
magicLinkToken: {
create: vi.fn(),
findUnique: vi.fn(),
update: vi.fn(),
updateMany: vi.fn(),
},
user: {
findUnique: vi.fn(),
@@ -45,11 +57,17 @@ const getMailTranslatorFromRequestMock = vi.mocked(getMailTranslatorFromRequest)
const queueTransactionalEmailMock = vi.mocked(queueTransactionalEmail);
const magicLinkTokenCreateMock = vi.mocked(db.magicLinkToken.create);
const magicLinkTokenFindUniqueMock = vi.mocked(db.magicLinkToken.findUnique);
const magicLinkTokenUpdateMock = vi.mocked(db.magicLinkToken.update);
const magicLinkTokenUpdateManyMock = vi.mocked(db.magicLinkToken.updateMany);
const userFindUniqueMock = vi.mocked(db.user.findUnique);
const loadRequiredWebConfigMock = vi.mocked(loadRequiredWebConfig);
beforeEach(() => {
vi.clearAllMocks();
loadRequiredWebConfigMock.mockReturnValue({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: true },
} as ReturnType<typeof loadRequiredWebConfig>);
getAppConfigurationMock.mockResolvedValue({
app: { name: "Acme Portal" },
email: { fromName: "Acme Support", supportEmail: "support@acme.test" },
@@ -57,7 +75,28 @@ beforeEach(() => {
} as Awaited<ReturnType<typeof getAppConfiguration>>);
getMailTranslatorMock.mockResolvedValue({
locale: "de",
t: (key, vars) => (key === "magicLink.subject" ? `Dein Anmeldelink für ${vars?.productName}` : key),
t: (key, vars) => {
const copy: Record<string, string> = {
"magicLink.subject": `Dein Anmeldelink für ${vars?.productName}`,
"magicLink.previewText": `Sicher bei ${vars?.productName} anmelden`,
"magicLink.eyebrow": "Anmeldelink",
"magicLink.title_named": `Hallo, ${vars?.name}!`,
"magicLink.title": "Hallo!",
"magicLink.intro": `Nutze diesen Link, um dich bei deinem ${vars?.productName}-Konto anzumelden.`,
"magicLink.actionLabel": "Anmelden",
"magicLink.ignoreIfUnrequested": "Wenn du diesen Anmeldelink nicht angefordert hast, kannst du diese E-Mail ignorieren.",
"magicLink.outro": `Dieser Link läuft in ${vars?.expiresInMinutes} Minuten ab und kann nur einmal verwendet werden.`,
"common.signoff.thanks": "Danke,",
"common.legal.privacyLabel": "Datenschutz",
"common.legal.termsLabel": "AGB",
"common.legal.imprintLabel": "Impressum",
"common.legal.unsubscribeLabel": "Abmelden",
"common.support.htmlBefore": "Bei Fragen kannst du uns gerne",
"common.support.emailLinkLabel": "eine E-Mail schreiben",
"common.support.htmlAfter": ".",
};
return copy[key] ?? key;
},
});
getMailTranslatorFromRequestMock.mockResolvedValue({
locale: "en",
@@ -66,11 +105,30 @@ beforeEach(() => {
queueTransactionalEmailMock.mockResolvedValue({ enqueued: true, jobId: "job_1" });
magicLinkTokenCreateMock.mockResolvedValue({ id: "token_1" } as Awaited<ReturnType<typeof db.magicLinkToken.create>>);
magicLinkTokenFindUniqueMock.mockResolvedValue(null);
magicLinkTokenUpdateMock.mockResolvedValue({ id: "token_1" } as Awaited<ReturnType<typeof db.magicLinkToken.update>>);
magicLinkTokenUpdateManyMock.mockResolvedValue({ count: 1 });
userFindUniqueMock.mockResolvedValue({ locale: "de" } as Awaited<ReturnType<typeof db.user.findUnique>>);
});
describe("issueMagicLink", () => {
it("does not persist or send a token while the provider is disabled", async () => {
loadRequiredWebConfigMock.mockReturnValue({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: false },
} as ReturnType<typeof loadRequiredWebConfig>);
await expect(
issueMagicLink({
request: new Request("https://example.com/login"),
userId: "user_1",
email: "ada@example.com",
})
).rejects.toBeInstanceOf(MagicLinkDisabledError);
expect(magicLinkTokenCreateMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).not.toHaveBeenCalled();
});
it("queues a magic-link mail rendered through the React-Email pipeline", async () => {
const result = await issueMagicLink({
request: new Request("https://example.com/forgot-password"),
@@ -81,7 +139,7 @@ describe("issueMagicLink", () => {
});
expect(result.token).toMatch(/\./);
// Translator is resolved against the user's locale for the subject.
// Translator is resolved against the user's locale for the complete mail.
expect(getMailTranslatorMock).toHaveBeenCalledWith("de");
expect(getMailTranslatorFromRequestMock).not.toHaveBeenCalled();
expect(queueTransactionalEmailMock).toHaveBeenCalledOnce();
@@ -101,11 +159,32 @@ describe("issueMagicLink", () => {
);
const queued = queueTransactionalEmailMock.mock.calls[0]?.[0];
expect(queued?.body).toContain("Click the button below to sign in to your Acme Portal account. No password required.");
expect(queued?.body).toContain("Sign in");
expect(queued?.body).toContain("This link expires in 15 minutes");
expect(queued?.body).toContain("Nutze diesen Link, um dich bei deinem Acme Portal-Konto anzumelden.");
expect(queued?.body).toContain("Anmelden");
expect(queued?.body).toContain("Dieser Link läuft in 15 Minuten ab");
expect(queued?.body).toContain("Datenschutz");
expect(queued?.body).toContain('<html lang="de">');
expect(queued?.body).not.toContain("Click the button below");
expect(queued?.body).not.toContain("This link expires");
expect(queued?.body).not.toContain("{i18nT(");
});
it("reuses an already-bound matching user RLS context", async () => {
magicLinkTokenCreateMock.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toEqual({ userId: "user_1" });
return { id: "token_1" } as Awaited<ReturnType<typeof db.magicLinkToken.create>>;
});
await runWithRlsContext({ userId: "user_1" }, () =>
issueMagicLink({
request: new Request("https://example.com/login"),
userId: "user_1",
email: "ada@example.com",
}),
);
expect(getRlsExecutionContext()).toBeNull();
});
});
describe("signed magic-link tokens", () => {
@@ -130,6 +209,19 @@ describe("signed magic-link tokens", () => {
});
describe("consumeMagicLinkToken", () => {
it("does not read or consume outstanding tokens while the provider is disabled", async () => {
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1" });
loadRequiredWebConfigMock.mockReturnValue({
cryptoSecret: "test-secret",
sessionSecret: "session-secret",
magicLink: { enabled: false },
} as ReturnType<typeof loadRequiredWebConfig>);
await expect(consumeMagicLinkToken(issued.token, { expectedPurpose: "login" })).resolves.toEqual({ ok: false, reason: "invalid" });
expect(magicLinkTokenFindUniqueMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("consumes a valid matching token exactly once", async () => {
const now = new Date("2026-05-19T12:00:00.000Z");
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now, purpose: "login" });
@@ -147,19 +239,47 @@ describe("consumeMagicLinkToken", () => {
tokenId: "token_1",
purpose: "login",
});
expect(magicLinkTokenUpdateMock).toHaveBeenCalledWith({
where: { id: "token_1" },
expect(magicLinkTokenUpdateManyMock).toHaveBeenCalledWith({
where: {
id: "token_1",
userId: "user_1",
tokenHash: issued.tokenHash,
consumedAt: null,
expiresAt: { gt: now },
},
data: { consumedAt: now },
});
});
it("allows only one winner when concurrent requests race to consume the same token", async () => {
const now = new Date("2026-05-19T12:00:00.000Z");
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now });
magicLinkTokenFindUniqueMock.mockResolvedValue({
id: "token_1",
userId: "user_1",
tokenHash: issued.tokenHash,
expiresAt: issued.expiresAt,
consumedAt: null,
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
magicLinkTokenUpdateManyMock.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 });
const results = await Promise.all([consumeMagicLinkToken(issued.token, { now }), consumeMagicLinkToken(issued.token, { now })]);
expect(results).toEqual(
expect.arrayContaining([
{ ok: true, userId: "user_1", tokenId: "token_1", purpose: "login" },
{ ok: false, reason: "replayed" },
])
);
});
it("rejects unknown or mismatched stored tokens without consuming them", async () => {
const now = new Date("2026-05-19T12:00:00.000Z");
const issued = createSignedMagicLinkToken({ userId: "user_1", tokenId: "token_1", now });
magicLinkTokenFindUniqueMock.mockResolvedValue(null);
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "not-found" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects expired signed payloads before reading the database", async () => {
@@ -169,7 +289,7 @@ describe("consumeMagicLinkToken", () => {
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "expired" });
expect(magicLinkTokenFindUniqueMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects stored tokens that expired after a valid signed payload was issued", async () => {
@@ -189,7 +309,7 @@ describe("consumeMagicLinkToken", () => {
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "expired" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects replayed tokens before writing a new consumedAt", async () => {
@@ -204,7 +324,7 @@ describe("consumeMagicLinkToken", () => {
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
await expect(consumeMagicLinkToken(issued.token, { now })).resolves.toEqual({ ok: false, reason: "replayed" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
it("rejects purpose mismatches without consuming the token", async () => {
@@ -219,6 +339,6 @@ describe("consumeMagicLinkToken", () => {
} as Awaited<ReturnType<typeof db.magicLinkToken.findUnique>>);
await expect(consumeMagicLinkToken(issued.token, { now, expectedPurpose: "login" })).resolves.toEqual({ ok: false, reason: "purpose-mismatch" });
expect(magicLinkTokenUpdateMock).not.toHaveBeenCalled();
expect(magicLinkTokenUpdateManyMock).not.toHaveBeenCalled();
});
});
@@ -7,10 +7,25 @@ import { getAbsoluteUrl } from "~/utils/url.server";
import { queueTransactionalEmail } from "~/modules/emails/services/TransactionalEmailQueue.server";
import { getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import { getMailTranslator, getMailTranslatorFromRequest } from "~/locale/mail-translator.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { localizedMailChrome } from "~/modules/emails/utils/LocalizedMailChrome";
export const MAGIC_LINK_TOKEN_TTL_MINUTES = 15;
const MAGIC_LINK_TOKEN_VERSION = "v1";
export class MagicLinkDisabledError extends Error {
constructor() {
super("Magic-link authentication is disabled.");
this.name = "MagicLinkDisabledError";
}
}
function assertMagicLinkEnabled(): void {
if (!loadRequiredWebConfig().magicLink.enabled) {
throw new MagicLinkDisabledError();
}
}
export type MagicLinkPurpose = "login" | "invitation" | "reset";
type MagicLinkPayload = {
@@ -158,6 +173,29 @@ export async function issueMagicLink({
redirectPath?: string;
now?: Date;
purpose?: MagicLinkPurpose;
}) {
// Keep the provider flag at the side-effect boundary as defense in depth:
// no caller can create a token or enqueue mail while the provider is off.
assertMagicLinkEnabled();
return withUserRlsContext(userId, () => issueMagicLinkScoped({ request, userId, email, name, redirectPath, now, purpose }));
}
async function issueMagicLinkScoped({
request,
userId,
email,
name,
redirectPath,
now,
purpose,
}: {
request: Request;
userId: string;
email: string;
name?: string | null;
redirectPath: string;
now: Date;
purpose: MagicLinkPurpose;
}) {
const token = createSignedMagicLinkToken({ userId, now, purpose });
await db.magicLinkToken.create({
@@ -174,19 +212,35 @@ export async function issueMagicLink({
const mailTranslator = await getMagicLinkMailTranslator(request, userId);
const appConfiguration = await getAppConfiguration({ request });
const brand = buildBrand(resolveTransactionalBrandTokens(toBrandConfiguration(appConfiguration)));
const { html } = renderTransactionalEmail("magic-link", {
const copyVariables = {
productName: brand.productName,
name: name ?? "",
expiresInMinutes: MAGIC_LINK_TOKEN_TTL_MINUTES,
};
const { html, text } = renderTransactionalEmail("magic-link", {
brand,
...localizedMailChrome(mailTranslator.t, mailTranslator.locale),
recipientName: name ?? undefined,
actionUrl,
expiresInMinutes: MAGIC_LINK_TOKEN_TTL_MINUTES,
subject: mailTranslator.t("magicLink.subject", copyVariables),
previewText: mailTranslator.t("magicLink.previewText", copyVariables),
eyebrow: mailTranslator.t("magicLink.eyebrow", copyVariables),
title: mailTranslator.t(name ? "magicLink.title_named" : "magicLink.title", copyVariables),
intro: mailTranslator.t("magicLink.intro", copyVariables),
actionLabel: mailTranslator.t("magicLink.actionLabel", copyVariables),
outro: mailTranslator.t("magicLink.ignoreIfUnrequested", copyVariables),
expiresText: mailTranslator.t("magicLink.outro", copyVariables),
signoffThanks: mailTranslator.t("common.signoff.thanks"),
});
const subject = mailTranslator.t("magicLink.subject", { productName: brand.productName });
const subject = mailTranslator.t("magicLink.subject", copyVariables);
await queueTransactionalEmail({
to: email,
alias: "magic-link",
subject,
body: html,
text,
userId,
data: emailData,
priorityOverride: "critical",
@@ -199,6 +253,11 @@ export async function issueMagicLink({
}
export async function consumeMagicLinkToken(token: string, options: { now?: Date; expectedPurpose?: MagicLinkPurpose } = {}): Promise<MagicLinkConsumeResult> {
// Disabled providers must not consume outstanding tokens. Returning the
// generic invalid reason avoids leaking runtime configuration to clients.
if (!loadRequiredWebConfig().magicLink.enabled) {
return { ok: false, reason: "invalid" };
}
const now = options.now ?? new Date();
const payload = verifySignedMagicLinkToken(token);
if (!payload) {
@@ -208,6 +267,15 @@ export async function consumeMagicLinkToken(token: string, options: { now?: Date
return { ok: false, reason: "expired" };
}
return runWithRlsContext({ userId: payload.sub }, () => consumeMagicLinkTokenScoped(token, payload, now, options));
}
async function consumeMagicLinkTokenScoped(
token: string,
payload: MagicLinkPayload,
now: Date,
options: { expectedPurpose?: MagicLinkPurpose }
): Promise<MagicLinkConsumeResult> {
const tokenHash = hashToken(token);
const storedToken = await db.magicLinkToken.findUnique({ where: { id: payload.jti } });
if (!storedToken || storedToken.userId !== payload.sub || storedToken.tokenHash !== tokenHash) {
@@ -227,10 +295,26 @@ export async function consumeMagicLinkToken(token: string, options: { now?: Date
return { ok: false, reason: "purpose-mismatch" };
}
await db.magicLinkToken.update({
where: { id: payload.jti },
const consumed = await db.magicLinkToken.updateMany({
where: {
id: payload.jti,
userId: payload.sub,
tokenHash,
consumedAt: null,
expiresAt: { gt: now },
},
data: { consumedAt: now },
});
if (consumed.count !== 1) {
return { ok: false, reason: "replayed" };
}
return { ok: true, userId: payload.sub, tokenId: payload.jti, purpose: actualPurpose };
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}
@@ -12,7 +12,7 @@
// AuthService.loginFromRequest after validatePassword runs in
// non-throwing mode against the plaintext the user just submitted.
// 2. A cookie `pwPolicyRemindAfter=<unix-millis>` that the "Remind me
// in 7 days" button sets via the api.password-policy-remind resource
// in 7 days" button sets via the auth.password-policy-remind resource
// route. While the timestamp is still in the future the banner stays
// hidden even when the session flag is on.
//
@@ -1,13 +1,7 @@
// @vitest-environment node
import { createHash } from "node:crypto";
import { describe, expect, test, vi } from "vitest";
import {
assertPasswordPolicy,
isPasswordPwned,
loadPasswordPolicy,
validatePassword,
validatePasswordPolicy,
} from "./password-policy.server.js";
import { assertPasswordPolicy, isPasswordPwned, loadPasswordPolicy, validatePassword, validatePasswordPolicy } from "./password-policy.server.js";
function sha1Upper(value: string): string {
return createHash("sha1").update(value).digest("hex").toUpperCase();
@@ -123,6 +117,19 @@ describe("validatePassword", () => {
expect(result.hibpBypassed).toBe(true);
});
test("HIBP requests have a real abort signal, reject redirects and bound response bodies", async () => {
const fetcher = vi.fn<typeof fetch>(async () => new Response("x".repeat(128 * 1024 + 1)));
const policy = { ...ALL_FLAGS_OFF, hibpCheck: true };
const result = await validatePassword("Long-Enough-Password", {}, { policy, fetcher });
expect(result.hibpBypassed).toBe(true);
expect(fetcher).toHaveBeenCalledWith(
expect.stringMatching(/^https:\/\/api\.pwnedpasswords\.com\/range\//u),
expect.objectContaining({ redirect: "error", signal: expect.any(AbortSignal) })
);
});
test("Unicode passwords are length-counted by JS string length (sufficient for the policy)", async () => {
const policy = { ...ALL_FLAGS_OFF, minLength: 8 };
const result = await validatePassword("Pässwört✓123", {}, { policy });
@@ -10,7 +10,8 @@ import { createHash } from "node:crypto";
const HIBP_API_BASE = "https://api.pwnedpasswords.com/range/";
const HIBP_TIMEOUT_MS = 3000;
const ABSOLUTE_MAX_LENGTH = 1024;
const HIBP_RESPONSE_MAX_BYTES = 128 * 1024;
export const PASSWORD_ABSOLUTE_MAX_LENGTH = 1024;
export type PasswordPolicyConfig = {
minLength: number;
@@ -88,8 +89,8 @@ export async function validatePassword(
if (plain.length < policy.minLength) {
errors.push({ code: "auth.password.errors.tooShort", args: { minLength: policy.minLength } });
}
if (plain.length > ABSOLUTE_MAX_LENGTH) {
errors.push({ code: "auth.password.errors.tooLong", args: { maxLength: ABSOLUTE_MAX_LENGTH } });
if (plain.length > PASSWORD_ABSOLUTE_MAX_LENGTH) {
errors.push({ code: "auth.password.errors.tooLong", args: { maxLength: PASSWORD_ABSOLUTE_MAX_LENGTH } });
}
if (policy.requireUpper && !/[A-Z]/.test(plain)) {
errors.push({ code: "auth.password.errors.missingUpper" });
@@ -136,7 +137,14 @@ async function checkHibp(plain: string, maxOccurrences: number, fetcher?: typeof
let response: Response;
try {
response = await withTimeout(usedFetcher(url, { headers: { "Add-Padding": "true" } }), HIBP_TIMEOUT_MS);
response = await withTimeout(
usedFetcher(url, {
headers: { "Add-Padding": "true" },
redirect: "error",
signal: AbortSignal.timeout(HIBP_TIMEOUT_MS),
}),
HIBP_TIMEOUT_MS
);
} catch {
return "bypassed";
}
@@ -144,7 +152,7 @@ async function checkHibp(plain: string, maxOccurrences: number, fetcher?: typeof
let body: string;
try {
body = await response.text();
body = await readLimitedText(response, HIBP_RESPONSE_MAX_BYTES);
} catch {
return "bypassed";
}
@@ -159,6 +167,37 @@ async function checkHibp(plain: string, maxOccurrences: number, fetcher?: typeof
return "clean";
}
async function readLimitedText(response: Response, maxBytes: number): Promise<string> {
const contentLength = response.headers.get("content-length");
if (contentLength && /^\d+$/u.test(contentLength) && Number(contentLength) > maxBytes) {
await response.body?.cancel().catch(() => undefined);
throw new Error("hibp_response_too_large");
}
if (!response.body) return "";
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let totalBytes = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
totalBytes += chunk.value.byteLength;
if (totalBytes > maxBytes) {
await reader.cancel().catch(() => undefined);
throw new Error("hibp_response_too_large");
}
chunks.push(chunk.value);
}
const bytes = new Uint8Array(totalBytes);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
return new TextDecoder().decode(bytes);
}
async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<T>((_, reject) => {
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const config = {
nodeEnv: "test",
routing: { appBaseDomain: "example.test", protocol: "https" },
sessionSecret: "registration-recovery-test-secret-0123456789",
};
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return { ...actual, loadRequiredWebConfig: () => config };
});
import {
clearRegistrationResendRecovery,
commitRegistrationResendRecovery,
readRegistrationResendRecovery,
REGISTRATION_RESEND_RECOVERY_COOKIE,
REGISTRATION_RESEND_RECOVERY_TTL_MS,
} from "./registration-resend-recovery.server";
const CREATION_REQUEST_KEY = "d7077797-054b-497a-b1ce-8e4f36257a96";
const NOW = Date.parse("2026-07-15T12:00:00.000Z");
describe("registration resend recovery cookie", () => {
beforeEach(() => {
config.sessionSecret = "registration-recovery-test-secret-0123456789";
});
it("survives reloads and tabs as a signed HttpOnly host-only 24-hour binding", async () => {
const setCookie = await commitRegistrationResendRecovery({ email: " Ada@Example.TEST ", creationRequestKey: CREATION_REQUEST_KEY }, NOW);
const cookie = setCookie.split(";", 1)[0];
const request = new Request("https://example.test/register", { headers: { Cookie: cookie } });
await expect(readRegistrationResendRecovery(request, NOW + 1_000)).resolves.toEqual({
email: "ada@example.test",
creationRequestKey: CREATION_REQUEST_KEY,
issuedAt: NOW,
});
expect(setCookie).toContain(`${REGISTRATION_RESEND_RECOVERY_COOKIE}=`);
expect(setCookie).toContain("HttpOnly");
expect(setCookie).toContain("SameSite=Lax");
expect(setCookie).toContain("Secure");
expect(setCookie).toContain("Path=/");
expect(setCookie).toContain("Max-Age=86400");
});
it("rejects tampering, another signing key, and an expired server-side timestamp", async () => {
const setCookie = await commitRegistrationResendRecovery({ email: "ada@example.test", creationRequestKey: CREATION_REQUEST_KEY }, NOW);
const cookie = setCookie.split(";", 1)[0]!;
const tampered = `${cookie.slice(0, -1)}${cookie.endsWith("a") ? "b" : "a"}`;
await expect(readRegistrationResendRecovery(new Request("https://example.test/register", { headers: { Cookie: tampered } }), NOW)).resolves.toBeNull();
config.sessionSecret = "another-registration-recovery-secret-012345678";
await expect(readRegistrationResendRecovery(new Request("https://example.test/register", { headers: { Cookie: cookie } }), NOW)).resolves.toBeNull();
config.sessionSecret = "registration-recovery-test-secret-0123456789";
await expect(
readRegistrationResendRecovery(new Request("https://example.test/register", { headers: { Cookie: cookie } }), NOW + REGISTRATION_RESEND_RECOVERY_TTL_MS)
).resolves.toBeNull();
});
it("expires the same host-only cookie when recovery completes or restarts", async () => {
const cleared = await clearRegistrationResendRecovery();
expect(cleared).toContain(`${REGISTRATION_RESEND_RECOVERY_COOKIE}=`);
expect(cleared).toContain("Max-Age=0");
expect(cleared).toContain("HttpOnly");
expect(cleared).toContain("SameSite=Lax");
expect(cleared).toContain("Secure");
expect(cleared).toContain("Path=/");
});
});
@@ -0,0 +1,94 @@
import { createCookie } from "react-router";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { isSignupCreationRequestKey } from "~/domain/tenant-bootstrap/signupCreationRequestKey.server";
export const REGISTRATION_RESEND_RECOVERY_TTL_MS = 24 * 60 * 60 * 1000;
export const REGISTRATION_RESEND_RECOVERY_COOKIE = "__Host-hivegrid_registration_resend";
export const LOCAL_REGISTRATION_RESEND_RECOVERY_COOKIE = "hivegrid_registration_resend";
const CLOCK_SKEW_MS = 60 * 1000;
const MAX_EMAIL_LENGTH = 320;
export type RegistrationResendRecovery = {
email: string;
creationRequestKey: string;
issuedAt: number;
};
function getRecoveryCookie() {
const config = loadRequiredWebConfig();
if (!config.sessionSecret) {
throw new Error("SESSION_SECRET is required for registration resend recovery cookies");
}
const policy = resolveHostOnlyCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
secureName: REGISTRATION_RESEND_RECOVERY_COOKIE,
localName: LOCAL_REGISTRATION_RESEND_RECOVERY_COOKIE,
maxAge: Math.ceil(REGISTRATION_RESEND_RECOVERY_TTL_MS / 1000),
});
return createCookie(policy.name, {
httpOnly: policy.httpOnly,
sameSite: policy.sameSite,
path: policy.path,
secure: policy.secure,
maxAge: policy.maxAge,
secrets: [config.sessionSecret],
});
}
export async function readRegistrationResendRecovery(request: Request, now = Date.now()): Promise<RegistrationResendRecovery | null> {
try {
const parsed: unknown = await getRecoveryCookie().parse(request.headers.get("Cookie"));
if (!isRecoveryPayload(parsed, now)) return null;
return {
email: normalizeEmail(parsed.email),
creationRequestKey: parsed.creationRequestKey,
issuedAt: parsed.issuedAt,
};
} catch {
return null;
}
}
export async function commitRegistrationResendRecovery(
input: Pick<RegistrationResendRecovery, "email" | "creationRequestKey">,
now = Date.now()
): Promise<string> {
const email = normalizeEmail(input.email);
if (!isValidEmailBinding(email) || !isSignupCreationRequestKey(input.creationRequestKey)) {
throw new Error("Registration resend recovery payload is invalid");
}
return await getRecoveryCookie().serialize({
email,
creationRequestKey: input.creationRequestKey,
issuedAt: now,
} satisfies RegistrationResendRecovery);
}
export async function clearRegistrationResendRecovery(): Promise<string> {
return await getRecoveryCookie().serialize("", { maxAge: 0 });
}
function isRecoveryPayload(value: unknown, now: number): value is RegistrationResendRecovery {
if (!value || typeof value !== "object") return false;
const payload = value as Partial<RegistrationResendRecovery>;
const email = typeof payload.email === "string" ? normalizeEmail(payload.email) : "";
return (
isValidEmailBinding(email) &&
typeof payload.creationRequestKey === "string" &&
isSignupCreationRequestKey(payload.creationRequestKey) &&
typeof payload.issuedAt === "number" &&
Number.isFinite(payload.issuedAt) &&
payload.issuedAt <= now + CLOCK_SKEW_MS &&
now - payload.issuedAt < REGISTRATION_RESEND_RECOVERY_TTL_MS
);
}
function normalizeEmail(value: string): string {
return value.trim().toLowerCase();
}
function isValidEmailBinding(value: string): boolean {
return value.length > 0 && value.length <= MAX_EMAIL_LENGTH && value.includes("@");
}
@@ -0,0 +1,200 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createSharedStore, MemoryAdapter } from "@hivegrid/shared-store";
import { createHash } from "node:crypto";
vi.mock("@hivegrid/config", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/config")>();
return {
...actual,
loadRequiredWebConfig: vi.fn(() => ({
routing: {
protocol: "https",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
appBaseDomain: "example.test",
},
})),
};
});
vi.mock("~/shared-store.server", () => ({ getSharedStore: vi.fn() }));
vi.mock("~/utils/session.server", () => ({ createUserSession: vi.fn() }));
import { createUserSession } from "~/utils/session.server";
import {
__resetSessionHandoffStoreForTests,
__setSessionHandoffStoreForTests,
consumeSessionHandoff,
createSessionHandoffRedirect,
} from "./session-handoff.server";
const userAgent = "HiveGrid security test browser";
const session = {
userId: "target-user-1",
lightOrDarkMode: "dark",
lng: "de",
cookies: [],
impersonatingFromAdminUserId: "admin-user-1",
impersonatingFromAdminEmail: "admin@example.test",
impersonatingStartedAt: "2026-07-12T06:00:00.000Z",
};
let store: ReturnType<typeof createSharedStore>;
function request(url: string, agent = userAgent) {
return new Request(url, { headers: { "user-agent": agent } });
}
function codeFrom(response: Response) {
return new URL(response.headers.get("Location")!).searchParams.get("code")!;
}
beforeEach(() => {
vi.clearAllMocks();
store = createSharedStore({ namespace: "session-handoff-test", adapter: new MemoryAdapter() });
__setSessionHandoffStoreForTests(store);
vi.mocked(createUserSession).mockResolvedValue(
new Response(null, {
status: 302,
headers: {
Location: "https://app.example.test/acme/dashboard",
"Set-Cookie": "__Host-hivegrid_app_session=signed; Path=/; Secure; HttpOnly",
},
}) as never
);
});
afterEach(() => {
vi.useRealTimers();
__resetSessionHandoffStoreForTests();
});
describe("cross-host session handoff", () => {
it("uses a short opaque code and consumes it once on the app host", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const location = issued.headers.get("Location")!;
const code = codeFrom(issued);
expect(location).toMatch(/^https:\/\/app\.example\.test\/auth\/session-handoff\?code=[A-Za-z0-9_-]{43}$/);
expect(location).not.toContain(session.userId);
expect(location).not.toContain(session.impersonatingFromAdminUserId);
expect(location).not.toContain(session.impersonatingFromAdminEmail);
expect(issued.headers.get("Cache-Control")).toBe("no-store");
expect(issued.headers.get("Referrer-Policy")).toBe("no-referrer");
const completed = await consumeSessionHandoff(request(`https://app.example.test/auth/session-handoff?code=${code}`), code);
expect(completed?.headers.get("Set-Cookie")).toContain("__Host-hivegrid_app_session=");
expect(completed?.headers.get("Cache-Control")).toBe("no-store");
expect(completed?.headers.get("Referrer-Policy")).toBe("no-referrer");
expect(createUserSession).toHaveBeenCalledWith(
expect.objectContaining({
userId: "target-user-1",
impersonatingFromAdminUserId: "admin-user-1",
impersonatingFromAdminEmail: "admin@example.test",
}),
"https://app.example.test/acme/dashboard",
{ request: expect.any(Request), rotate: true }
);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
});
it("allows exactly one winner under concurrent consumption", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
const results = await Promise.all([
consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code),
consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code),
]);
expect(results.filter(Boolean)).toHaveLength(1);
expect(createUserSession).toHaveBeenCalledTimes(1);
});
it("consumes and rejects a code presented by a different browser", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff", "different-browser"), code)).resolves.toBeNull();
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
expect(createUserSession).not.toHaveBeenCalled();
});
it("binds consumption to the canonical app origin without burning the code on another host", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
await expect(consumeSessionHandoff(request("https://admin.example.test/auth/session-handoff"), code)).resolves.toBeNull();
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeInstanceOf(Response);
expect(createUserSession).toHaveBeenCalledTimes(1);
});
it("rejects a Redis payload whose HMAC envelope was tampered with", async () => {
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
const hash = createHash("sha256").update(code).digest("hex");
await store.set(
`auth:session-handoff:${hash}`,
JSON.stringify({
payload: JSON.stringify({ ...session, userId: "attacker-selected-user" }),
signature: "forged-signature",
}),
{ ttlSeconds: 60 }
);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
expect(createUserSession).not.toHaveBeenCalled();
});
it("fails closed for expired codes and non-app redirect targets", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-07-12T06:00:00.000Z"));
const issued = await createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
});
const code = codeFrom(issued);
vi.advanceTimersByTime(60_000);
await expect(consumeSessionHandoff(request("https://app.example.test/auth/session-handoff"), code)).resolves.toBeNull();
await expect(
createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://evil.example/phish",
})
).rejects.toThrow("canonical app-host redirect");
});
it("fails closed without emitting a redirect when the shared store is unavailable", async () => {
vi.spyOn(store, "set").mockRejectedValueOnce(new Error("redis unavailable"));
await expect(
createSessionHandoffRedirect({
request: request("https://admin.example.test/accounts/users"),
session,
redirectTo: "https://app.example.test/acme/dashboard",
})
).rejects.toThrow("redis unavailable");
expect(createUserSession).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,192 @@
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
import { redirect } from "react-router";
import { getSharedStore } from "~/shared-store.server";
import { absolutePublicAppPath } from "~/utils/app/CrossHostUrls";
import { safeSessionRedirectTarget } from "~/utils/app/SessionRedirectSafety.server";
import { getHostRoutingContext, getRequestRoutingHost } from "~/utils/app/HostRouting.server";
import { createUserSession, type UserSession } from "~/utils/session.server";
import { loadRequiredWebConfig } from "@hivegrid/config";
export const SESSION_HANDOFF_TTL_SECONDS = 60;
export const SESSION_HANDOFF_PATH = "/auth/session-handoff";
const CONSUME_SCRIPT = `
local value = redis.call('GET', KEYS[1])
if value then
redis.call('DEL', KEYS[1])
end
return value
`;
MemoryAdapter.registerScript(CONSUME_SCRIPT, async (adapter, keys) => {
const key = keys[0];
if (!key) return null;
const value = await adapter.get(key);
if (value !== null) await adapter.del(key);
return value;
});
type SessionHandoffPayload = {
createdAt: number;
userAgentHash: string;
redirectTo: string;
session: UserSession;
};
let storeFactory: () => SharedStore = () => getSharedStore();
let memoryConsumeQueue: Promise<void> = Promise.resolve();
function codeKey(code: string) {
return `auth:session-handoff:${createHash("sha256").update(code).digest("hex")}`;
}
function signPayload(code: string, payload: string) {
return createHmac("sha256", code).update(payload).digest("base64url");
}
function safeSignatureMatch(actual: string, expected: string) {
const actualBytes = Buffer.from(actual);
const expectedBytes = Buffer.from(expected);
return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
}
function userAgentHash(request: Request) {
return createHash("sha256")
.update(request.headers.get("user-agent") ?? "")
.digest("hex");
}
function transferableSession(session: UserSession): UserSession {
return {
userId: session.userId,
lightOrDarkMode: session.lightOrDarkMode,
lng: session.lng,
// The destination host receives a fresh CSRF token from its root loader;
// never carry the admin-host token across the trust boundary.
csrf: undefined,
cookies: session.cookies,
metrics: session.metrics,
impersonatingFromUserId: session.impersonatingFromUserId,
impersonatingFromAdminUserId: session.impersonatingFromAdminUserId,
impersonatingFromAdminEmail: session.impersonatingFromAdminEmail,
impersonatingStartedAt: session.impersonatingStartedAt,
theme: session.theme,
passwordPolicyOutdated: session.passwordPolicyOutdated,
};
}
export async function createSessionHandoffRedirect({
request,
session,
redirectTo,
}: {
request: Request;
session: UserSession;
redirectTo: string;
}): Promise<Response> {
const routing = loadRequiredWebConfig().routing;
const safeRedirectTo = safeSessionRedirectTarget(redirectTo, routing);
const appOrigin = new URL(`${routing.protocol}://${routing.webAppHost}`).origin;
if (!safeRedirectTo.startsWith(`${appOrigin}/`)) {
throw new Error("Session handoff requires a canonical app-host redirect target");
}
const code = randomBytes(32).toString("base64url");
const payload: SessionHandoffPayload = {
createdAt: Date.now(),
userAgentHash: userAgentHash(request),
redirectTo: safeRedirectTo,
session: transferableSession(session),
};
const serializedPayload = JSON.stringify(payload);
const stored = await storeFactory().set(codeKey(code), JSON.stringify({ payload: serializedPayload, signature: signPayload(code, serializedPayload) }), {
ttlSeconds: SESSION_HANDOFF_TTL_SECONDS,
nx: true,
});
if (!stored) {
throw new Error("Could not reserve one-time session handoff code");
}
const target = new URL(absolutePublicAppPath(routing, SESSION_HANDOFF_PATH));
target.searchParams.set("code", code);
return redirect(target.toString(), {
headers: {
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
},
});
}
export async function consumeSessionHandoff(request: Request, code: string | null | undefined): Promise<Response | null> {
if (!code || !/^[A-Za-z0-9_-]{43}$/.test(code)) {
return null;
}
const routing = loadRequiredWebConfig().routing;
const requestUrl = new URL(request.url);
if (getHostRoutingContext(getRequestRoutingHost(request, requestUrl, routing), routing) !== "app") {
return null;
}
const store = storeFactory();
const consume = () => store.adapter.eval(CONSUME_SCRIPT, [store.key(codeKey(code))], []);
let raw: unknown;
if (store.adapter instanceof MemoryAdapter) {
// Redis runs the Lua script atomically. Serialize the development/test
// adapter too so concurrent consumers observe the same single-use rule.
const queued = memoryConsumeQueue.then(consume);
memoryConsumeQueue = queued.then(
() => undefined,
() => undefined
);
raw = await queued;
} else {
raw = await consume();
}
if (typeof raw !== "string") {
return null;
}
let payload: SessionHandoffPayload;
try {
const envelope = JSON.parse(raw) as { payload?: unknown; signature?: unknown };
if (
typeof envelope.payload !== "string" ||
typeof envelope.signature !== "string" ||
!safeSignatureMatch(envelope.signature, signPayload(code, envelope.payload))
) {
return null;
}
payload = JSON.parse(envelope.payload) as SessionHandoffPayload;
} catch {
return null;
}
const ageMs = Date.now() - payload.createdAt;
if (
!Number.isFinite(payload.createdAt) ||
ageMs < 0 ||
ageMs >= SESSION_HANDOFF_TTL_SECONDS * 1000 ||
payload.userAgentHash !== userAgentHash(request) ||
typeof payload.redirectTo !== "string" ||
!payload.session ||
typeof payload.session.userId !== "string"
) {
return null;
}
const response = await createUserSession(payload.session, payload.redirectTo, { request, rotate: true });
const headers = new Headers(response.headers);
headers.set("Cache-Control", "no-store");
headers.set("Referrer-Policy", "no-referrer");
return new Response(response.body, { status: response.status, headers });
}
export function __setSessionHandoffStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetSessionHandoffStoreForTests(): void {
storeFactory = () => getSharedStore();
memoryConsumeQueue = Promise.resolve();
}
@@ -4,6 +4,28 @@ const storeMock = vi.hoisted(() => ({
createUserSession: vi.fn(),
revokeSessionByToken: vi.fn(),
}));
const adminStoreMock = vi.hoisted(() => ({
createAdminSession: vi.fn(),
revokeAdminSessionByToken: vi.fn(),
}));
vi.mock("@hivegrid/config", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/config")>();
return {
...actual,
loadRequiredWebConfig: () => ({
routing: {
appBaseDomain: "example.test",
protocol: "https",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
},
}),
};
});
vi.mock("@hivegrid/db/admin-sessions.server", () => ({
createAdminSession: (...args: unknown[]) => adminStoreMock.createAdminSession(...args),
revokeAdminSessionByToken: (...args: unknown[]) => adminStoreMock.revokeAdminSessionByToken(...args),
}));
vi.mock("./sessionStore.server", () => ({
createUserSession: (...args: unknown[]) => storeMock.createUserSession(...args),
revokeSessionByToken: (...args: unknown[]) => storeMock.revokeSessionByToken(...args),
@@ -22,6 +44,10 @@ function requestWith(headers: Record<string, string>) {
return new Request("https://example.test/login", { headers });
}
function adminRequestWith(headers: Record<string, string>) {
return new Request("https://admin.example.test/login", { headers });
}
beforeEach(() => {
vi.clearAllMocks();
geoMock.lookupCountry.mockResolvedValue({ countryCode: "DE", countryName: "Germany" });
@@ -29,7 +55,13 @@ beforeEach(() => {
describe("buildSessionDeviceContext (AD-22)", () => {
it("hashes the IP and resolves the country, never exposing the raw IP", async () => {
const ctx = await buildSessionDeviceContext(requestWith({ "user-agent": "Safari", "x-forwarded-for": "9.9.9.9" }));
const ctx = await buildSessionDeviceContext(
requestWith({
"user-agent": "Safari",
"cf-connecting-ip": "9.9.9.9",
"x-forwarded-for": "198.51.100.9, 173.245.48.10",
}),
);
expect(ctx.ipHash).toBe("HASHED");
expect(ctx.userAgent).toBe("Safari");
expect(ctx.approxLocation).toBe("Germany");
@@ -48,10 +80,45 @@ describe("buildSessionDeviceContext (AD-22)", () => {
describe("startServerSession", () => {
it("creates a session row with the pseudonymized device context and returns the raw token", async () => {
storeMock.createUserSession.mockResolvedValue({ session: { id: "s1" }, rawToken: "tok-123" });
const token = await startServerSession({ request: requestWith({ "user-agent": "Safari", "x-forwarded-for": "1.2.3.4" }), userId: "u1" });
const token = await startServerSession({
request: requestWith({
"user-agent": "Safari",
"cf-connecting-ip": "1.2.3.4",
"x-forwarded-for": "198.51.100.4, 173.245.48.10",
}),
userId: "u1",
});
expect(token).toBe("tok-123");
expect(storeMock.createUserSession).toHaveBeenCalledWith({ userId: "u1", ipHash: "HASHED", userAgent: "Safari", approxLocation: "Germany" });
});
it("creates a dedicated eight-hour AdminSession only with Authentik MFA assurance", async () => {
const mfaAssuredAt = new Date("2026-07-24T18:00:00.000Z");
adminStoreMock.createAdminSession.mockResolvedValue({ session: { id: "as1" }, rawToken: "admin-token" });
const token = await startServerSession({
request: adminRequestWith({ "user-agent": "Safari" }),
userId: "admin-1",
adminAuthenticationMethods: ["pwd", "mfa"],
adminMfaAssuredAt: mfaAssuredAt,
});
expect(token).toBe("admin-token");
expect(adminStoreMock.createAdminSession).toHaveBeenCalledWith({
adminUserId: "admin-1",
authenticationMethods: ["pwd", "mfa"],
mfaAssuredAt,
ipHash: null,
userAgent: "Safari",
approxLocation: null,
});
expect(storeMock.createUserSession).not.toHaveBeenCalled();
});
it("fails closed on the admin host without MFA assurance", async () => {
await expect(startServerSession({ request: adminRequestWith({}), userId: "admin-1" })).rejects.toThrow(
"Admin server session requires Authentik MFA assurance"
);
expect(adminStoreMock.createAdminSession).not.toHaveBeenCalled();
});
});
describe("endServerSession", () => {
@@ -60,4 +127,12 @@ describe("endServerSession", () => {
await endServerSession("tok-123");
expect(storeMock.revokeSessionByToken).toHaveBeenCalledWith("tok-123");
});
it("revokes only the dedicated AdminSession on the admin host", async () => {
adminStoreMock.revokeAdminSessionByToken.mockResolvedValue(true);
const request = adminRequestWith({});
await endServerSession("admin-token", request);
expect(adminStoreMock.revokeAdminSessionByToken).toHaveBeenCalledWith("admin-token");
expect(storeMock.revokeSessionByToken).not.toHaveBeenCalled();
});
});
@@ -1,5 +1,8 @@
import { hashIp, lookupCountry } from "~/modules/ipAddress/services/geoip.server";
import { getClientIPAddress } from "~/utils/server/IpUtils";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { createAdminSession, revokeAdminSessionByToken } from "@hivegrid/db/admin-sessions.server";
import { getHostRoutingContext, getRequestRoutingHost } from "~/utils/app/HostRouting.server";
import { createUserSession as createServerSessionRow, revokeSessionByToken } from "./sessionStore.server";
@@ -8,7 +11,7 @@ import { createUserSession as createServerSessionRow, revokeSessionByToken } fro
// gefuehrt, damit Geraeteliste, Revoke und "ueberall abmelden" greifen.
export function extractRawClientIp(request: Request): string | null {
return getClientIPAddress(request.headers)?.toString() ?? null;
return getTrustedClientIpOrNull(request);
}
// AD-22: persistiert KEINE Klartext-IP. Die IP wird gehasht (hashIp, Wiedererkennung "gleiches
@@ -23,15 +26,46 @@ export async function buildSessionDeviceContext(request: Request): Promise<{ ipH
};
}
// Beim Login/Signup aufgerufen: legt die Session-Zeile mit (pseudonymisiertem) Geraete-Kontext an und
// liefert den rohen Token zurueck, der ins Cookie wandert. Best-effort: ein Store-Fehler darf den Login
// nicht verhindern (Cookie ist Source-of-Truth fuer die Identitaet).
export async function startServerSession({ request, userId }: { request: Request; userId: string }): Promise<string | null> {
// Every authenticated cookie is backed by this row. Store failures propagate
// so callers cannot issue an unrevocable fallback cookie.
export async function startServerSession({
request,
userId,
adminAuthenticationMethods,
adminMfaAssuredAt,
}: {
request: Request;
userId: string;
adminAuthenticationMethods?: readonly string[];
adminMfaAssuredAt?: Date;
}): Promise<string> {
const context = await buildSessionDeviceContext(request);
const routing = loadRequiredWebConfig().routing;
const host = getRequestRoutingHost(request, new URL(request.url), routing);
if (getHostRoutingContext(host, routing) === "admin") {
if (!adminAuthenticationMethods || !adminMfaAssuredAt) {
throw new Error("Admin server session requires Authentik MFA assurance");
}
const { rawToken } = await createAdminSession({
adminUserId: userId,
authenticationMethods: adminAuthenticationMethods,
mfaAssuredAt: adminMfaAssuredAt,
...context,
});
return rawToken;
}
const { rawToken } = await createServerSessionRow({ userId, ...context });
return rawToken;
}
export async function endServerSession(rawToken: string | undefined | null): Promise<void> {
export async function endServerSession(rawToken: string | undefined | null, request?: Request): Promise<void> {
if (request) {
const routing = loadRequiredWebConfig().routing;
const host = getRequestRoutingHost(request, new URL(request.url), routing);
if (getHostRoutingContext(host, routing) === "admin") {
await revokeAdminSessionByToken(rawToken);
return;
}
}
await revokeSessionByToken(rawToken);
}
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
const dbMock = vi.hoisted(() => ({
userSession: {
@@ -10,11 +11,13 @@ const dbMock = vi.hoisted(() => ({
updateMany: vi.fn(),
},
}));
const resolveUserSessionRlsIdentityMock = vi.hoisted(() => vi.fn());
vi.mock("~/utils/db.server", () => ({ db: dbMock, dbRead: dbMock }));
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolveUserSessionRlsIdentity: resolveUserSessionRlsIdentityMock,
}));
vi.mock("~/utils/cache.server", () => ({
// Cache als Pass-through: getFreshValue direkt aufrufen, clearCacheKey als Spy.
cachified: vi.fn(async (opts: { getFreshValue: () => Promise<unknown> }) => opts.getFreshValue()),
clearCacheKey: vi.fn(),
}));
@@ -27,6 +30,7 @@ import {
listActiveUserSessions,
markSessionTrusted,
revokeAllUserSessionsExcept,
revokeAllUserSessionsForUser,
revokeSessionByToken,
revokeUserSession,
} from "./sessionStore.server";
@@ -42,6 +46,7 @@ function pastDate(msAgo = 60_000) {
beforeEach(() => {
vi.clearAllMocks();
resolveUserSessionRlsIdentityMock.mockResolvedValue({ resourceId: "s1", userId: "u1" });
});
describe("session token hashing", () => {
@@ -71,6 +76,7 @@ describe("createUserSession", () => {
expect(data.ipHash).toBe("deadbeef");
expect(data.trustedAt).toBeNull();
});
});
describe("getActiveSessionByToken", () => {
@@ -80,19 +86,71 @@ describe("getActiveSessionByToken", () => {
});
it("returns the session when active", async () => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: futureDate() });
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: null,
expiresAt: futureDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
expect(await getActiveSessionByToken("raw")).toMatchObject({ id: "s1" });
expect(dbMock.userSession.findUnique).toHaveBeenCalledWith(
expect.objectContaining({ include: { user: { select: expect.objectContaining({ active: true, pendingDeletion: true, pseudonymized: true }) } } })
);
});
it("fails closed when the bootstrap resolver cannot prove the token owner", async () => {
resolveUserSessionRlsIdentityMock.mockResolvedValueOnce(null).mockResolvedValueOnce(null);
await expect(getActiveSessionByToken("unknown")).resolves.toBeNull();
await expect(revokeSessionByToken("unknown")).resolves.toBe(false);
expect(dbMock.userSession.findUnique).not.toHaveBeenCalled();
});
it("checks the source of truth on every cross-request validation", async () => {
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: null,
expiresAt: futureDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
await getActiveSessionByToken("raw");
await getActiveSessionByToken("raw");
expect(dbMock.userSession.findUnique).toHaveBeenCalledTimes(2);
});
it("returns null for a revoked session", async () => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: pastDate(), expiresAt: futureDate() });
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: pastDate(),
expiresAt: futureDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
expect(await getActiveSessionByToken("raw")).toBeNull();
});
it("returns null for an expired session", async () => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: pastDate() });
dbMock.userSession.findUnique.mockResolvedValue({
id: "s1",
revokedAt: null,
expiresAt: pastDate(),
user: { active: true, pendingDeletion: false, pseudonymized: false },
});
expect(await getActiveSessionByToken("raw")).toBeNull();
});
it.each([
{ active: false, pendingDeletion: false, pseudonymized: false },
{ active: true, pendingDeletion: true, pseudonymized: false },
{ active: true, pendingDeletion: false, pseudonymized: true },
])("returns null when the session owner is unavailable ($active/$pendingDeletion/$pseudonymized)", async (user) => {
dbMock.userSession.findUnique.mockResolvedValue({ id: "s1", revokedAt: null, expiresAt: futureDate(), user });
expect(await getActiveSessionByToken("raw")).toBeNull();
});
});
describe("listActiveUserSessions", () => {
@@ -104,6 +162,17 @@ describe("listActiveUserSessions", () => {
expect(where.revokedAt).toBeNull();
expect(where.expiresAt).toHaveProperty("gt");
});
it("reuses an already-bound matching user RLS context", async () => {
dbMock.userSession.findMany.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toEqual({ userId: "u1" });
return [];
});
await runWithRlsContext({ userId: "u1" }, () => listActiveUserSessions("u1"));
expect(getRlsExecutionContext()).toBeNull();
});
});
describe("revokeUserSession", () => {
@@ -149,6 +218,22 @@ describe("revokeAllUserSessionsExcept", () => {
});
});
describe("revokeAllUserSessionsForUser", () => {
it("revokes every active row after an external authorization change", async () => {
dbMock.userSession.findMany.mockResolvedValue([{ tokenHash: "h1" }, { tokenHash: "h2" }]);
dbMock.userSession.updateMany.mockResolvedValue({ count: 2 });
await expect(revokeAllUserSessionsForUser("u1")).resolves.toBe(2);
expect(dbMock.userSession.updateMany).toHaveBeenCalledWith({
where: { userId: "u1", revokedAt: null, expiresAt: { gt: expect.any(Date) } },
data: { revokedAt: expect.any(Date) },
});
expect(clearCacheKeyMock).toHaveBeenCalledWith("user-session:h1");
expect(clearCacheKeyMock).toHaveBeenCalledWith("user-session:h2");
});
});
describe("revokeSessionByToken", () => {
it("returns false for a missing token without touching the DB", async () => {
expect(await revokeSessionByToken(undefined)).toBe(false);
@@ -1,7 +1,9 @@
import { createHash, randomBytes } from "node:crypto";
import { cachified, clearCacheKey } from "~/utils/cache.server";
import { clearCacheKey } from "~/utils/cache.server";
import { db } from "~/utils/db.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolveUserSessionRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
// R-P2a S4 — serverseitige Sessions. Postgres ist Source-of-Truth (Tabelle UserSession),
// davor ein kurzlebiger Cache (LRU heute, Redis-swappable per cache.server, AD-4). Das
@@ -9,10 +11,25 @@ import { db } from "~/utils/db.server";
const SESSION_TOKEN_BYTES = 32;
const DEFAULT_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 Tage, deckt das Cookie-Max-Age
const SESSION_CACHE_TTL_MS = 60 * 1000; // kurzer Cache vor dem Postgres-SoT
const TOUCH_THROTTLE_MS = 5 * 60 * 1000; // lastSeenAt hoechstens alle 5min fortschreiben
export type UserSessionRow = Awaited<ReturnType<typeof db.userSession.create>>;
export type ActiveUserSessionOwner = {
id: string;
email: string;
firstName: string;
lastName: string;
avatar: string | null;
phone: string | null;
defaultTenantId: string | null;
createdAt: Date;
locale: string | null;
lightOrDarkMode: string | null;
active: boolean;
pendingDeletion: boolean;
pseudonymized: boolean;
};
export type ActiveUserSessionRow = UserSessionRow & { user: ActiveUserSessionOwner };
type Identified = { userId: string; sessionId: string };
@@ -47,13 +64,18 @@ export type CreateSessionInput = {
};
export async function createUserSession(input: CreateSessionInput): Promise<{ session: UserSessionRow; rawToken: string }> {
return withUserRlsContext(input.userId, () => createUserSessionScoped(input));
}
async function createUserSessionScoped(input: CreateSessionInput): Promise<{ session: UserSessionRow; rawToken: string }> {
const rawToken = input.rawToken ?? generateSessionToken();
const now = Date.now();
const expiresAt = input.expiresAt ?? new Date(now + DEFAULT_SESSION_TTL_MS);
const session = await db.userSession.create({
data: {
userId: input.userId,
tokenHash: hashSessionToken(rawToken),
expiresAt: input.expiresAt ?? new Date(now + DEFAULT_SESSION_TTL_MS),
expiresAt,
ipHash: input.ipHash ?? null,
userAgent: input.userAgent ?? null,
deviceLabel: input.deviceLabel ?? null,
@@ -65,22 +87,52 @@ export async function createUserSession(input: CreateSessionInput): Promise<{ se
return { session, rawToken };
}
// Liefert die aktive Session zum Cookie-Token oder null (revoked/abgelaufen/unbekannt). Der
// Cache wird bei Revoke gezielt invalidiert; die Ablauf-Pruefung laeuft zusaetzlich live gegen now.
export async function getActiveSessionByToken(rawToken: string | undefined | null): Promise<UserSessionRow | null> {
// Authorization reads always hit the source of truth. Positive cross-request
// caching would leave revoked sessions usable until the cache TTL elapsed.
export async function getActiveSessionByToken(rawToken: string | undefined | null): Promise<ActiveUserSessionRow | null> {
if (!rawToken) {
return null;
}
const tokenHash = hashSessionToken(rawToken);
const session = await cachified<UserSessionRow | null>({
key: sessionCacheKey(tokenHash),
ttl: SESSION_CACHE_TTL_MS,
getFreshValue: async () => db.userSession.findUnique({ where: { tokenHash } }),
});
if (!isActive(session)) {
const identity = await resolveUserSessionRlsIdentity(tokenHash);
if (!identity) {
return null;
}
return session;
return runWithRlsContext({ userId: identity.userId }, () => getActiveSessionByTokenScoped(tokenHash, identity.resourceId));
}
async function getActiveSessionByTokenScoped(tokenHash: string, expectedSessionId: string): Promise<ActiveUserSessionRow | null> {
const session = await db.userSession.findUnique({
where: { tokenHash },
include: {
user: {
select: {
id: true,
email: true,
firstName: true,
lastName: true,
avatar: true,
phone: true,
defaultTenantId: true,
createdAt: true,
locale: true,
lightOrDarkMode: true,
active: true,
pendingDeletion: true,
pseudonymized: true,
},
},
},
});
if (!session || session.id !== expectedSessionId || !isActive(session)) {
return null;
}
// Existing sessions must stop authorizing immediately when the account is
// disabled, enters deletion, or has already been pseudonymized.
if (!session.user.active || session.user.pendingDeletion || session.user.pseudonymized) {
return null;
}
return session as ActiveUserSessionRow;
}
// Schreibt lastSeenAt fort, aber gedrosselt (hoechstens alle TOUCH_THROTTLE_MS), um den
@@ -95,15 +147,21 @@ export async function touchSession(session: Pick<UserSessionRow, "id" | "lastSee
}
export async function listActiveUserSessions(userId: string): Promise<UserSessionRow[]> {
return db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastSeenAt: "desc" },
});
return withUserRlsContext(userId, () =>
db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
orderBy: { lastSeenAt: "desc" },
}),
);
}
// Revoke einzeln (Geraete-Liste). Verifiziert die Eigentuemerschaft ueber userId, damit ein
// Nutzer nur eigene Sessions beenden kann, und invalidiert den Cache.
export async function revokeUserSession({ userId, sessionId }: Identified): Promise<boolean> {
return withUserRlsContext(userId, () => revokeUserSessionScoped({ userId, sessionId }));
}
async function revokeUserSessionScoped({ userId, sessionId }: Identified): Promise<boolean> {
const session = await db.userSession.findFirst({ where: { id: sessionId, userId }, select: { id: true, tokenHash: true, revokedAt: true } });
if (!session || session.revokedAt !== null) {
return false;
@@ -115,6 +173,10 @@ export async function revokeUserSession({ userId, sessionId }: Identified): Prom
// "Ueberall abmelden": alle aktiven Sessions des Nutzers ausser der aktuellen beenden.
export async function revokeAllUserSessionsExcept({ userId, sessionId }: Identified): Promise<number> {
return withUserRlsContext(userId, () => revokeAllUserSessionsExceptScoped({ userId, sessionId }));
}
async function revokeAllUserSessionsExceptScoped({ userId, sessionId }: Identified): Promise<number> {
const sessions = await db.userSession.findMany({
where: { userId, revokedAt: null, id: { not: sessionId } },
select: { id: true, tokenHash: true },
@@ -133,14 +195,46 @@ export async function revokeAllUserSessionsExcept({ userId, sessionId }: Identif
return sessions.length;
}
// Used when an external identity loses an allowed group. Revoking every
// server-side row makes the decision visible to all web replicas immediately.
export async function revokeAllUserSessionsForUser(userId: string): Promise<number> {
return withUserRlsContext(userId, () => revokeAllUserSessionsForUserScoped(userId));
}
async function revokeAllUserSessionsForUserScoped(userId: string): Promise<number> {
const sessions = await db.userSession.findMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
select: { tokenHash: true },
});
if (sessions.length === 0) {
return 0;
}
const result = await db.userSession.updateMany({
where: { userId, revokedAt: null, expiresAt: { gt: new Date() } },
data: { revokedAt: new Date() },
});
for (const session of sessions) {
clearCacheKey(sessionCacheKey(session.tokenHash));
}
return result.count;
}
// Revoke ueber den Cookie-Token (Logout): beendet genau die aktuelle Session.
export async function revokeSessionByToken(rawToken: string | undefined | null): Promise<boolean> {
if (!rawToken) {
return false;
}
const tokenHash = hashSessionToken(rawToken);
const identity = await resolveUserSessionRlsIdentity(tokenHash);
if (!identity) {
return false;
}
return runWithRlsContext({ userId: identity.userId }, () => revokeSessionByTokenScoped(tokenHash, identity.resourceId));
}
async function revokeSessionByTokenScoped(tokenHash: string, expectedSessionId: string): Promise<boolean> {
const session = await db.userSession.findUnique({ where: { tokenHash }, select: { id: true, revokedAt: true } });
if (!session || session.revokedAt !== null) {
if (!session || session.id !== expectedSessionId || session.revokedAt !== null) {
return false;
}
await db.userSession.update({ where: { id: session.id }, data: { revokedAt: new Date() } });
@@ -150,9 +244,18 @@ export async function revokeSessionByToken(rawToken: string | undefined | null):
// Trust-Device (S5/2FA): markiert eine eigene Session als vertrauenswuerdig.
export async function markSessionTrusted({ userId, sessionId }: Identified): Promise<boolean> {
const result = await db.userSession.updateMany({
where: { id: sessionId, userId, revokedAt: null },
data: { trustedAt: new Date() },
return withUserRlsContext(userId, async () => {
const result = await db.userSession.updateMany({
where: { id: sessionId, userId, revokedAt: null },
data: { trustedAt: new Date() },
});
return result.count > 0;
});
return result.count > 0;
}
function withUserRlsContext<T>(userId: string, operation: () => T): T {
if (getRlsExecutionContext()?.userId) {
return operation();
}
return runWithRlsContext({ userId }, operation);
}
@@ -15,6 +15,7 @@ vi.mock("@hivegrid/config", () => ({
vi.mock("~/utils/db/users.db.server", () => ({
activateUserTotpPendingSecret: vi.fn(),
clearUserTotpPendingSecret: vi.fn(),
getUserTotpPendingEnrollment: vi.fn(),
setUserMfaRecoveryCodes: vi.fn(),
setUserTotpPendingSecret: vi.fn(),
@@ -222,6 +223,7 @@ describe("services/auth/totp.server", () => {
const usersDb = await import("~/utils/db/users.db.server");
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce({
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
totpPendingCreatedAt: new Date("2026-05-25T09:00:00.000Z"),
} as never);
const { activatePendingTotpForUser } = await import("./totp.server");
@@ -236,6 +238,27 @@ describe("services/auth/totp.server", () => {
expect(usersDb.setUserMfaRecoveryCodes).not.toHaveBeenCalled();
});
test("activatePendingTotpForUser clears and rejects an enrollment older than ten minutes", async () => {
const usersDb = await import("~/utils/db/users.db.server");
const pending = {
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
totpPendingCreatedAt: new Date("2026-05-25T09:00:00.000Z"),
};
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce(pending);
const { activatePendingTotpForUser } = await import("./totp.server");
await expect(
activatePendingTotpForUser({
userId: "user_1",
token: generateExpectedCode(vectorSecret, new Date("2026-05-25T09:10:00.001Z").getTime()),
now: new Date("2026-05-25T09:10:00.001Z"),
})
).resolves.toEqual({ activated: false, recoveryCodes: [] });
expect(usersDb.clearUserTotpPendingSecret).toHaveBeenCalledWith("user_1", pending);
expect(usersDb.activateUserTotpPendingSecret).not.toHaveBeenCalled();
expect(usersDb.setUserMfaRecoveryCodes).not.toHaveBeenCalled();
});
test("activatePendingTotpForUser promotes the pending secret and stores recovery codes", async () => {
const usersDb = await import("~/utils/db/users.db.server");
const { generateRecoveryCodes } = await import("~/utils/auth/mfa/recovery-codes.server");
@@ -243,6 +266,7 @@ describe("services/auth/totp.server", () => {
const code = generateExpectedCode(vectorSecret, now.getTime());
vi.mocked(usersDb.getUserTotpPendingEnrollment).mockResolvedValueOnce({
totpPendingSecretEncrypted: `encrypted:${vectorSecret}`,
totpPendingCreatedAt: now,
} as never);
const { activatePendingTotpForUser, TOTP_RECOVERY_CODE_COUNT } = await import("./totp.server");
@@ -3,13 +3,16 @@ import { loadRequiredWebConfig } from "@hivegrid/config";
import CryptoApi from "~/utils/api/.server/CryptoApi";
import {
activateUserTotpPendingSecret,
clearUserTotpPendingSecret,
getUserTotpPendingEnrollment,
setUserMfaRecoveryCodes,
setUserTotpPendingSecret,
type UserTotpPendingEnrollment,
} from "~/utils/db/users.db.server";
import { generateRecoveryCodes } from "~/utils/auth/mfa/recovery-codes.server";
export const TOTP_RECOVERY_CODE_COUNT = 10;
export const TOTP_PENDING_ENROLLMENT_TTL_MS = 10 * 60 * 1000;
const TOTP_DIGITS = 6;
const TOTP_PERIOD_SECONDS = 30;
const DEFAULT_WINDOW = 1;
@@ -36,6 +39,11 @@ export type TotpEnrollmentResult = {
secret: string;
};
export type FreshTotpPendingEnrollment = UserTotpPendingEnrollment & {
totpPendingSecretEncrypted: string;
totpPendingCreatedAt: Date;
};
type OtpauthOptions = {
appName?: string;
issuer?: string;
@@ -148,6 +156,28 @@ export async function createTotpEnrollmentForUser({
};
}
export async function getFreshTotpPendingEnrollmentForUser({
userId,
now = new Date(),
}: {
userId: string;
now?: Date;
}): Promise<FreshTotpPendingEnrollment | null> {
const pending = await getUserTotpPendingEnrollment(userId);
if (!pending) {
return null;
}
const pendingCreatedAtMs = pending.totpPendingCreatedAt?.getTime();
const ageMs = pendingCreatedAtMs === undefined ? Number.NaN : now.getTime() - pendingCreatedAtMs;
if (pending.totpPendingSecretEncrypted && Number.isFinite(ageMs) && ageMs >= 0 && ageMs <= TOTP_PENDING_ENROLLMENT_TTL_MS) {
return pending as FreshTotpPendingEnrollment;
}
if (pending.totpPendingSecretEncrypted || pending.totpPendingCreatedAt) {
await clearUserTotpPendingSecret(userId, pending);
}
return null;
}
export async function activatePendingTotpForUser({
userId,
token,
@@ -157,8 +187,8 @@ export async function activatePendingTotpForUser({
token: string;
now?: Date;
}): Promise<{ activated: boolean; recoveryCodes: string[] }> {
const pending = await getUserTotpPendingEnrollment(userId);
if (!pending?.totpPendingSecretEncrypted) {
const pending = await getFreshTotpPendingEnrollmentForUser({ userId, now });
if (!pending) {
return { activated: false, recoveryCodes: [] };
}
if (!verifyTotpCode(pending.totpPendingSecretEncrypted, token, { timestamp: now.getTime() })) {
@@ -169,4 +199,3 @@ export async function activatePendingTotpForUser({
await setUserMfaRecoveryCodes(userId, recovery.entries, recovery.generatedAt);
return { activated: true, recoveryCodes: recovery.codes };
}
@@ -1,11 +1,16 @@
import { describe, expect, it } from "vitest";
import { automationActionCatalog, automationTriggerCatalog } from "./automation.registry";
import { automationConditionBranchForParent } from "@hivegrid/db/automation-graph";
import { AUTOMATION_TRIGGERS_WITHOUT_EMITTER, automationActionCatalog, automationTriggerCatalog } from "./automation.registry";
import {
applyAutomationEditorOperation,
buildAutomationDryRunPreview,
buildAutomationEditorFlow,
buildAutomationReversePlan,
canConfirmAutomationReverse,
canConfirmAutomationDryRun,
extractAutomationClipboardSteps,
extractAutomationReverseRecipients,
incompleteAutomationNodeConfigKeys,
serializeAutomationEditorFlow,
validateAutomationEditorFlow,
} from "./automation.editor";
@@ -28,14 +33,130 @@ describe("automation editor contract", () => {
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
],
});
expect(validateAutomationEditorFlow(loop).issues).toContainEqual(expect.objectContaining({ code: "loop_detected", messageKey: "automation.editor.validation.loopDetected" }));
expect(validateAutomationEditorFlow(loop).issues).toContainEqual(
expect.objectContaining({ code: "loop_detected", messageKey: "automation.editor.validation.loopDetected" })
);
});
it("blocks flows the runtime could not execute", () => {
// A portal action under a CRM trigger reaches the generic executor, which
// has no portal handler and ends the run as unsupportedNode.
const mixedFamilies = buildAutomationEditorFlow({
flowData: {},
steps: [
{ stepKey: "trigger", stepKind: "trigger", nodeType: "crm.kontakt_created", parentStepIds: [] },
{ stepKey: "invite", stepKind: "action", nodeType: "portal.invite_user", parentStepIds: ["trigger"] },
],
});
const mixed = validateAutomationEditorFlow(mixedFamilies);
expect(mixed.issues).toContainEqual(expect.objectContaining({ code: "executor_family_mismatch", stepKey: "invite" }));
expect(mixed.canActivate).toBe(false);
// Same flow with a portal trigger is fine - it runs in the portal consumer.
const portalOnly = buildAutomationEditorFlow({
flowData: {},
steps: [
{ stepKey: "trigger", stepKind: "trigger", nodeType: "portal.user_created", parentStepIds: [] },
{ stepKey: "invite", stepKind: "action", nodeType: "portal.invite_user", parentStepIds: ["trigger"] },
],
});
expect(validateAutomationEditorFlow(portalOnly).issues).not.toContainEqual(expect.objectContaining({ code: "executor_family_mismatch" }));
const loop = buildAutomationEditorFlow({
flowData: {},
steps: [
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
{
stepKey: "loop",
stepKind: "flow_control",
nodeType: "loop.for_each",
parentStepIds: ["trigger"],
config: { liste: "offeneAufgabenDesProjekts", maxDurchlaeufe: "100" },
},
],
});
expect(validateAutomationEditorFlow(loop).issues).toContainEqual(expect.objectContaining({ code: "node_without_executor", stepKey: "loop" }));
expect(validateAutomationEditorFlow(loop).canActivate).toBe(false);
for (const triggerKey of AUTOMATION_TRIGGERS_WITHOUT_EMITTER) {
const dormant = buildAutomationEditorFlow({
flowData: {},
steps: [{ stepKey: "trigger", stepKind: "trigger", nodeType: triggerKey, parentStepIds: [] }],
});
const dormantResult = validateAutomationEditorFlow(dormant);
expect(dormantResult.issues).toContainEqual(expect.objectContaining({ code: "trigger_without_emitter", severity: "error", detail: triggerKey }));
expect(dormantResult.canActivate).toBe(false);
}
const webhook = buildAutomationEditorFlow({
flowData: {},
steps: [{ stepKey: "trigger", stepKind: "trigger", nodeType: "webhook.received", parentStepIds: [] }],
});
expect(validateAutomationEditorFlow(webhook).canActivate).toBe(true);
});
it("blocks incomplete action configuration before activation", () => {
const flow = buildAutomationEditorFlow({
flowData: {},
steps: [
{ stepKey: "trigger", stepKind: "trigger", nodeType: "webhook.received", parentStepIds: [] },
{ stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], config: {} },
],
});
const validation = validateAutomationEditorFlow(flow);
expect(validation.issues).toContainEqual(expect.objectContaining({ code: "incomplete_configuration", stepKey: "notify", detail: "notification.send" }));
expect(validation.canActivate).toBe(false);
expect(incompleteAutomationNodeConfigKeys("notification.send", {})).toEqual(["kanal", "empfaenger", "betreff", "nachricht"]);
expect(
incompleteAutomationNodeConfigKeys("notification.send", {
kanal: "intern",
empfaenger: "besitzerDerAutomation",
betreff: "Neuer Vorgang",
nachricht: "Bitte prüfen.",
})
).toEqual([]);
expect(incompleteAutomationNodeConfigKeys("email.send_transactional", { betreff: "Hallo", nachricht: "Text" })).toEqual(["an"]);
expect(
incompleteAutomationNodeConfigKeys("email.send_transactional", { an: "{{email}}", betreff: "Hallo", nachricht: "Text" })
).toEqual([]);
expect(incompleteAutomationNodeConfigKeys("chat.post_message", { chatId: "chat-1" })).toEqual(["nachricht"]);
expect(incompleteAutomationNodeConfigKeys("chat.post_message", { chatId: "{{chatId}}", nachricht: "Hallo {{name}}" })).toEqual([]);
expect(
incompleteAutomationNodeConfigKeys("task.assign", { aufgabe: "bestimmteAufgabe", zustaendig: "erstellerDerAufgabe", benachrichtigungAn: "niemand" })
).toContain("taskId");
expect(incompleteAutomationNodeConfigKeys("loop.for_each", { liste: "offeneAufgabenDesProjekts", maxDurchlaeufe: "101" })).toEqual(["maxDurchlaeufe"]);
});
it("places added nodes without overlapping the neighbouring card", () => {
const catalogNodes = catalog;
let flow = buildAutomationEditorFlow({ flowData: {}, steps: [] });
flow = applyAutomationEditorOperation(flow, { type: "add-node", nodeType: "lead.qualified" }, catalogNodes);
flow = applyAutomationEditorOperation(flow, { type: "add-node", nodeType: "task.create", parentStepKey: flow.steps[0]?.stepKey }, catalogNodes);
// The card renders 288px wide; a narrower pitch dropped every second node
// on top of its neighbour.
const [first, second] = flow.steps;
expect(Math.abs(second!.position.x - first!.position.x)).toBeGreaterThanOrEqual(288);
});
it("applies graph operations with undo and redo history", () => {
const initial = buildAutomationEditorFlow({ flowData: {}, steps: [] });
const withTrigger = applyAutomationEditorOperation(initial, { type: "add-node", nodeType: "lead.qualified" }, catalog);
const withTask = applyAutomationEditorOperation(withTrigger, { type: "add-node", nodeType: "task.create", parentStepKey: withTrigger.steps[0]?.stepKey }, catalog);
const connected = applyAutomationEditorOperation(withTask, { type: "connect", fromStepKey: withTrigger.steps[0]!.stepKey, toStepKey: withTask.steps[1]!.stepKey }, catalog);
const withTaskUnconfigured = applyAutomationEditorOperation(
withTrigger,
{ type: "add-node", nodeType: "task.create", parentStepKey: withTrigger.steps[0]?.stepKey },
catalog
);
const withTask = {
...withTaskUnconfigured,
steps: withTaskUnconfigured.steps.map((step) =>
step.nodeType === "task.create" ? { ...step, config: { ...step.config, titel: "Lead nachfassen" } } : step
),
};
const connected = applyAutomationEditorOperation(
withTask,
{ type: "connect", fromStepKey: withTrigger.steps[0]!.stepKey, toStepKey: withTask.steps[1]!.stepKey },
catalog
);
expect(validateAutomationEditorFlow(connected).canActivate).toBe(true);
expect(serializeAutomationEditorFlow(connected).steps).toHaveLength(2);
@@ -47,6 +168,48 @@ describe("automation editor contract", () => {
expect(redone.steps).toHaveLength(2);
});
it("persists and removes explicit condition edge branches", () => {
const flow = buildAutomationEditorFlow({
flowData: {},
steps: [
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
{
stepKey: "condition",
stepKind: "condition",
nodeType: "condition.if_else",
parentStepIds: ["trigger"],
config: { feld: "status", vergleich: "istGleich", wert: "gewonnen" },
},
{
stepKey: "fallback",
stepKind: "action",
nodeType: "task.create",
parentStepIds: [],
config: { titel: "Nachbearbeiten", zustaendig: "besitzerDerAutomation", prioritaet: "normal" },
},
],
});
const connected = applyAutomationEditorOperation(
flow,
{ type: "connect", fromStepKey: "condition", toStepKey: "fallback", branch: "false" },
catalog
);
const fallback = connected.steps.find((step) => step.stepKey === "fallback")!;
expect(automationConditionBranchForParent(fallback.config, "condition")).toBe("false");
const disconnected = applyAutomationEditorOperation(
connected,
{ type: "disconnect", fromStepKey: "condition", toStepKey: "fallback" },
catalog
);
expect(disconnected.steps.find((step) => step.stepKey === "fallback")?.config).toEqual({
titel: "Nachbearbeiten",
zustaendig: "besitzerDerAutomation",
prioritaet: "normal",
});
});
it("builds dry-run previews with confirmation threshold", () => {
const flow = buildAutomationEditorFlow({
flowData: {},
@@ -55,17 +218,47 @@ describe("automation editor contract", () => {
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
],
});
const preview = buildAutomationDryRunPreview({ flow, matchedRecords: 101, examples: ["Lead A", "Lead B", "Lead C", "Lead D", "Lead E", "Lead F"] });
const preview = buildAutomationDryRunPreview({
flow,
confirmationPhrase: "START DRY RUN",
matchedRecords: 101,
inspectedEvents: 500,
sampleLimitReached: true,
examples: ["Lead A", "Lead B", "Lead C", "Lead D", "Lead E", "Lead F"],
});
expect(preview.requiresConfirmation).toBe(true);
expect(preview.inspectedEvents).toBe(500);
expect(preview.sampleLimitReached).toBe(true);
expect(preview.examples).toHaveLength(5);
expect(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: "falsch" })).toBe(false);
expect(canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: preview.confirmationPhrase })).toBe(true);
expect(preview.confirmationPhrase).toBe("START DRY RUN");
expect(
canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: "DRY RUN STARTEN", expectedConfirmationPhrase: preview.confirmationPhrase })
).toBe(false);
expect(
canConfirmAutomationDryRun({ matchedRecords: 101, confirmationPhrase: preview.confirmationPhrase, expectedConfirmationPhrase: preview.confirmationPhrase })
).toBe(true);
});
it("rejects scheduler configs that the minute sweep cannot execute", () => {
expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "taeglich", uhrzeit: "morgen" })).toContain("uhrzeit");
expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "taeglich", uhrzeit: "08:00" })).toEqual([]);
expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "woechentlich", uhrzeit: "08:00" })).toEqual(["wochentag"]);
expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "monatlich", uhrzeit: "08:00", monatstag: "32" })).toEqual(["monatstag"]);
expect(incompleteAutomationNodeConfigKeys("time.schedule", { wiederholung: "woechentlich", uhrzeit: "08:00", wochentag: "freitag" })).toEqual([]);
expect(
incompleteAutomationNodeConfigKeys("projects.deadline_soon", {
fristtyp: "projektDeadline",
leadTime: 0,
leadTimeUnit: "tage",
})
).toContain("leadTime");
});
it("builds 24h reverse plans and marks deliveries as not reversible", () => {
const plan = buildAutomationReversePlan({
reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z",
confirmationPhrase: "REVERSE AUTOMATION",
now: new Date("2026-07-02T09:00:00.000Z"),
steps: [
{ stepKey: "task", nodeType: "task.create" },
@@ -79,4 +272,98 @@ describe("automation editor contract", () => {
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false }),
]);
});
it("requires the exact reverse confirmation phrase", () => {
expect(canConfirmAutomationReverse({ confirmationPhrase: "REVERSE AUTOMATION", expectedConfirmationPhrase: "REVERSE AUTOMATION" })).toBe(true);
expect(canConfirmAutomationReverse({ confirmationPhrase: "reverse automation", expectedConfirmationPhrase: "REVERSE AUTOMATION" })).toBe(true);
expect(canConfirmAutomationReverse({ confirmationPhrase: "AUTOMATION RÜCKGÄNGIG", expectedConfirmationPhrase: "REVERSE AUTOMATION" })).toBe(false);
});
it("copies and pastes steps with fresh keys and remapped parents", () => {
const flow = buildAutomationEditorFlow({
flowData: {},
steps: [
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"], config: { titel: "Angebot" } },
{ stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["task"] },
],
});
const clipboard = extractAutomationClipboardSteps(flow, ["task", "notify"]);
expect(clipboard).toHaveLength(2);
const pasted = applyAutomationEditorOperation(flow, { type: "paste-steps", steps: clipboard }, catalog);
expect(pasted.steps).toHaveLength(5);
const pastedTask = pasted.steps.find((step) => step.nodeType === "task.create" && step.stepKey !== "task");
const pastedNotify = pasted.steps.find((step) => step.nodeType === "notification.send" && step.stepKey !== "notify");
// Intra-clipboard parent is remapped to the fresh key; the parent link to
// the still-existing trigger survives the paste.
expect(pastedNotify?.parentStepIds).toEqual([pastedTask?.stepKey]);
expect(pastedTask?.parentStepIds).toEqual(["trigger"]);
expect(pastedTask?.config).toEqual({ titel: "Angebot" });
expect(pasted.history.past.length).toBeGreaterThan(0);
});
it("drops unknown node types on paste and deletes multiple steps at once", () => {
const flow = buildAutomationEditorFlow({
flowData: {},
steps: [
{ stepKey: "trigger", stepKind: "trigger", nodeType: "lead.qualified", parentStepIds: [] },
{ stepKey: "task", stepKind: "action", nodeType: "task.create", parentStepIds: ["trigger"] },
{ stepKey: "notify", stepKind: "action", nodeType: "notification.send", parentStepIds: ["task"] },
],
});
const unknownPaste = applyAutomationEditorOperation(flow, { type: "paste-steps", steps: [{ stepKey: "x", nodeType: "tags.add" }] }, catalog);
expect(unknownPaste.steps).toHaveLength(3);
const deleted = applyAutomationEditorOperation(flow, { type: "delete-nodes", stepKeys: ["task", "notify"] }, catalog);
expect(deleted.steps.map((step) => step.stepKey)).toEqual(["trigger"]);
expect(deleted.steps[0]?.parentStepIds).toEqual([]);
});
it("extracts persisted send recipients for the reverse plan", () => {
expect(
extractAutomationReverseRecipients("notification.send", { recipients: [{ name: "Sandra Vogel", email: "buero@example.com" }, "chef@example.com"] })
).toEqual([
{ name: "Sandra Vogel", email: "buero@example.com" },
{ name: null, email: "chef@example.com" },
]);
// Fail-tolerant: missing/malformed outputs yield an empty list instead of throwing.
expect(extractAutomationReverseRecipients("notification.send", null)).toEqual([]);
expect(extractAutomationReverseRecipients("notification.send", { recipients: [{}, 42] })).toEqual([]);
expect(extractAutomationReverseRecipients("task.create", { recipients: ["a@b.c"] })).toEqual([]);
const plan = buildAutomationReversePlan({
reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z",
confirmationPhrase: "REVERSE AUTOMATION",
now: new Date("2026-07-02T09:00:00.000Z"),
steps: [{ stepKey: "notify", nodeType: "notification.send", output: { recipients: ["buero@example.com"] } }],
});
expect(plan.items[0]?.recipients).toEqual([{ name: null, email: "buero@example.com" }]);
expect(plan.items[0]?.reversible).toBe(false);
});
it("describes the reversible CRM tag and assignment actions", () => {
const plan = buildAutomationReversePlan({
reverseWindowExpiresAt: "2026-07-02T10:00:00.000Z",
confirmationPhrase: "REVERSE AUTOMATION",
now: new Date("2026-07-02T09:00:00.000Z"),
steps: [
{ stepKey: "add-tag", nodeType: "crm.add_tag", output: {} },
{ stepKey: "remove-tag", nodeType: "crm.remove_tag", output: {} },
{ stepKey: "assign-contact", nodeType: "crm.assign_kontakt", output: {} },
{ stepKey: "assign-lead", nodeType: "lead.assign", output: {} },
{ stepKey: "status-lead", nodeType: "lead.set_status", output: {} },
],
});
expect(plan.items).toEqual([
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.removeContactTag", reversible: true }),
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreContactTag", reversible: true }),
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreContactAssignment", reversible: true }),
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreLeadAssignment", reversible: true }),
expect.objectContaining({ actionKey: "automation.editor.reverse.actions.restoreLeadStatus", reversible: true }),
]);
});
});
@@ -1,12 +1,32 @@
import {
AUTOMATION_TRIGGERS_WITHOUT_EMITTER,
automationExecutionFamily,
evaluateLoopGuard,
getAutomationNode,
isAutomationNodeRunnable,
type AutomationGraphStep,
type AutomationNodeDefinition,
type AutomationNodeKind,
} from "./automation.registry";
import {
AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY,
automationConditionBranches,
withAutomationConditionBranch,
type AutomationConditionBranch,
} from "@hivegrid/db/automation-graph";
export type AutomationEditorIssueCode = "missing_trigger" | "multiple_triggers" | "unknown_node" | "unconnected_step" | "missing_parent" | "loop_detected" | "empty_flow";
export type AutomationEditorIssueCode =
| "missing_trigger"
| "multiple_triggers"
| "unknown_node"
| "unconnected_step"
| "missing_parent"
| "loop_detected"
| "empty_flow"
| "node_without_executor"
| "executor_family_mismatch"
| "trigger_without_emitter"
| "incomplete_configuration";
export interface AutomationEditorStep {
readonly stepKey: string;
@@ -61,8 +81,10 @@ export interface AutomationEditorStepInput {
export type AutomationEditorOperation =
| { readonly type: "add-node"; readonly nodeType: string; readonly parentStepKey?: string | null }
| { readonly type: "delete-node"; readonly stepKey: string }
| { readonly type: "delete-nodes"; readonly stepKeys: readonly string[] }
| { readonly type: "duplicate-node"; readonly stepKey: string }
| { readonly type: "connect"; readonly fromStepKey: string; readonly toStepKey: string }
| { readonly type: "paste-steps"; readonly steps: readonly AutomationEditorStepInput[] }
| { readonly type: "connect"; readonly fromStepKey: string; readonly toStepKey: string; readonly branch?: AutomationConditionBranch }
| { readonly type: "disconnect"; readonly fromStepKey: string; readonly toStepKey: string }
| { readonly type: "auto-layout" }
| { readonly type: "undo" }
@@ -72,6 +94,8 @@ export interface AutomationDryRunPreview {
readonly requiresConfirmation: boolean;
readonly confirmationPhrase: string;
readonly matchedRecords: number;
readonly inspectedEvents: number;
readonly sampleLimitReached: boolean;
readonly examples: readonly string[];
readonly steps: readonly {
readonly stepKey: string;
@@ -82,6 +106,11 @@ export interface AutomationDryRunPreview {
readonly warnings: readonly string[];
}
export interface AutomationReverseRecipient {
readonly name: string | null;
readonly email: string | null;
}
export interface AutomationReversePlan {
readonly canReverse: boolean;
readonly confirmationPhrase: string;
@@ -90,14 +119,27 @@ export interface AutomationReversePlan {
readonly nodeType: string;
readonly actionKey: string;
readonly reversible: boolean;
/** Delivered-to list for send-type steps; shown as "not retractable" evidence. */
readonly recipients: readonly AutomationReverseRecipient[];
}[];
readonly warnings: readonly string[];
}
const DRY_RUN_CONFIRMATION_PHRASE = "DRY RUN STARTEN";
const DRY_RUN_CONFIRMATION_THRESHOLD = 100;
const REVERSE_CONFIRMATION_PHRASE = "AUTOMATION RUECKGAENGIG";
const MAX_HISTORY = 20;
/**
* Canvas grid for placed nodes. The step card renders at 288px wide (w-72), so
* the column pitch has to clear that plus a gutter - a narrower grid drops each
* new node on top of its neighbour.
*/
const CANVAS_COLUMN_WIDTH = 340;
const CANVAS_ROW_HEIGHT = 160;
const CANVAS_COLUMNS = 3;
/** Grid slot for the n-th node, left to right and then wrapping downwards. */
function gridPosition(index: number): { x: number; y: number } {
return { x: CANVAS_COLUMN_WIDTH * (index % CANVAS_COLUMNS), y: CANVAS_ROW_HEIGHT * Math.floor(index / CANVAS_COLUMNS) };
}
export function buildAutomationEditorFlow(input: { readonly flowData: unknown; readonly steps: readonly AutomationEditorStepInput[] }): AutomationEditorFlow {
const rawFlow = objectOrEmpty(input.flowData);
@@ -106,7 +148,7 @@ export function buildAutomationEditorFlow(input: { readonly flowData: unknown; r
.map((raw, index) => normalizeStep(raw, index))
.filter((step): step is AutomationEditorStep => step !== null)
.sort((a, b) => a.sortOrder - b.sortOrder || a.stepKey.localeCompare(b.stepKey));
const triggerKey = typeof rawFlow.triggerKey === "string" ? rawFlow.triggerKey : steps.find((step) => step.kind === "trigger")?.nodeType ?? "";
const triggerKey = typeof rawFlow.triggerKey === "string" ? rawFlow.triggerKey : (steps.find((step) => step.kind === "trigger")?.nodeType ?? "");
const history = normalizeHistory(rawFlow.history);
return { triggerKey, steps, history };
}
@@ -141,10 +183,25 @@ export function validateAutomationEditorFlow(flow: AutomationEditorFlow): Automa
issues.push(issue("multiple_triggers", null, "automation.editor.validation.multipleTriggers", triggerSteps.map((step) => step.stepKey).join(", ")));
}
// The trigger decides which executor picks the rule up, so every action has
// to belong to the same family (see automationExecutionFamily).
const triggerFamily = triggerSteps.length === 1 ? automationExecutionFamily(triggerSteps[0]!.nodeType) : null;
if (triggerSteps.length === 1 && AUTOMATION_TRIGGERS_WITHOUT_EMITTER.has(triggerSteps[0]!.nodeType)) {
issues.push(issue("trigger_without_emitter", triggerSteps[0]!.stepKey, "automation.editor.validation.triggerWithoutEmitter", triggerSteps[0]!.nodeType));
}
const stepKeys = new Set(flow.steps.map((step) => step.stepKey));
for (const step of flow.steps) {
if (!getAutomationNode(step.nodeType)) {
const node = getAutomationNode(step.nodeType);
if (!node) {
issues.push(issue("unknown_node", step.stepKey, "automation.editor.validation.unknownNode", step.nodeType));
} else if (!isAutomationNodeRunnable(node)) {
issues.push(issue("node_without_executor", step.stepKey, "automation.editor.validation.nodeWithoutExecutor", step.nodeType));
} else if (triggerFamily && step.kind !== "trigger" && automationExecutionFamily(step.nodeType) !== triggerFamily) {
issues.push(issue("executor_family_mismatch", step.stepKey, "automation.editor.validation.executorFamilyMismatch", step.nodeType));
}
if (node && incompleteAutomationNodeConfigKeys(step.nodeType, step.config).length > 0) {
issues.push(issue("incomplete_configuration", step.stepKey, "automation.editor.validation.incompleteConfiguration", step.nodeType));
}
for (const parentStepId of step.parentStepIds) {
if (!stepKeys.has(parentStepId)) {
@@ -175,7 +232,158 @@ export function validateAutomationEditorFlow(flow: AutomationEditorFlow): Automa
};
}
export function applyAutomationEditorOperation(flow: AutomationEditorFlow, operation: AutomationEditorOperation, catalog: readonly AutomationNodeDefinition[]): AutomationEditorFlow {
type AutomationConfigRequirement = {
readonly required?: readonly string[];
readonly allowed?: Readonly<Record<string, readonly string[]>>;
readonly requiredWhen?: readonly { readonly key: string; readonly whenKey: string; readonly equals: string }[];
};
const AUTOMATION_CONFIG_REQUIREMENTS: Readonly<Record<string, AutomationConfigRequirement>> = {
"projects.deadline_soon": {
required: ["fristtyp", "leadTime", "leadTimeUnit"],
allowed: {
fristtyp: ["aufgabenFaelligkeit", "projektDeadline", "zahlungsziel"],
leadTimeUnit: ["stunden", "tage", "wochen"],
},
},
"time.schedule": {
required: ["wiederholung", "uhrzeit"],
allowed: {
wiederholung: ["taeglich", "woechentlich", "monatlich"],
wochentag: ["montag", "dienstag", "mittwoch", "donnerstag", "freitag", "samstag", "sonntag"],
},
requiredWhen: [
{ key: "wochentag", whenKey: "wiederholung", equals: "woechentlich" },
{ key: "monatstag", whenKey: "wiederholung", equals: "monatlich" },
],
},
"crm.update_kontakt": {
required: ["kontakt", "feld", "wert"],
allowed: {
kontakt: ["ausloeser", "manuell"],
feld: ["kontaktStatus", "vorname", "nachname", "orgName", "primaerEmail", "primaerTelefon", "language"],
},
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
},
"crm.add_tag": {
required: ["kontakt", "tagId"],
allowed: { kontakt: ["ausloeser", "manuell"] },
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
},
"crm.remove_tag": {
required: ["kontakt", "tagId"],
allowed: { kontakt: ["ausloeser", "manuell"] },
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
},
"crm.assign_kontakt": {
required: ["kontakt", "userId"],
allowed: { kontakt: ["ausloeser", "manuell"] },
requiredWhen: [{ key: "kontaktId", whenKey: "kontakt", equals: "manuell" }],
},
"lead.assign": {
required: ["lead", "userId"],
allowed: { lead: ["ausloeser", "manuell"] },
requiredWhen: [{ key: "leadId", whenKey: "lead", equals: "manuell" }],
},
"lead.set_status": {
required: ["lead", "status"],
allowed: { lead: ["ausloeser", "manuell"], status: ["new", "qualified", "converted", "lost", "spam"] },
requiredWhen: [{ key: "leadId", whenKey: "lead", equals: "manuell" }],
},
"crm.create_note": {
required: ["datensatz", "notiztext"],
allowed: { datensatz: ["kontaktAusAusloeser", "auftragAusAusloeser", "projektAusAusloeser"] },
},
"notification.send": {
required: ["kanal", "empfaenger", "betreff", "nachricht"],
allowed: { kanal: ["intern"], empfaenger: ["besitzerDerAutomation", "bestimmtePerson"] },
requiredWhen: [{ key: "userId", whenKey: "empfaenger", equals: "bestimmtePerson" }],
},
"email.send_transactional": { required: ["an", "betreff", "nachricht"] },
"chat.post_message": { required: ["chatId", "nachricht"] },
"http.request": {
required: ["url", "methode"],
allowed: { methode: ["get", "post", "put", "delete"] },
},
"task.create": {
required: ["titel", "zustaendig", "prioritaet"],
allowed: { zustaendig: ["besitzerDerAutomation"], prioritaet: ["niedrig", "normal", "hoch"] },
},
"task.assign": {
required: ["aufgabe", "zustaendig", "benachrichtigungAn"],
allowed: {
aufgabe: ["ausVorherigemSchritt", "bestimmteAufgabe"],
zustaendig: ["erstellerDerAufgabe"],
benachrichtigungAn: ["neueVerantwortung", "bisherigeVerantwortung", "beide", "niemand"],
},
requiredWhen: [{ key: "taskId", whenKey: "aufgabe", equals: "bestimmteAufgabe" }],
},
"condition.if_else": {
required: ["feld", "vergleich", "wert"],
allowed: { vergleich: ["istGroesserAls", "istGleich", "istKleinerAls", "enthaelt"] },
},
"delay.wait": {
required: ["dauer", "dauerEinheit"],
allowed: { dauerEinheit: ["minuten", "stunden", "tage", "wochen"] },
},
"loop.for_each": {
required: ["liste", "maxDurchlaeufe"],
allowed: { liste: ["offeneAufgabenDesProjekts", "kontakteDesProjekts", "positionenDesAngebots", "termineDieserWoche"] },
},
"portal.invite_user": { required: ["kind", "email", "firstName", "lastName"], allowed: { kind: ["customer", "subcontractor"] } },
"portal.grant_access": { required: ["portalUserId", "projectId"] },
"portal.revoke_access": { required: ["portalUserId", "projectId"] },
"portal.release_document": { required: ["projectId", "fileId"] },
"portal.send_status_mail": { required: ["projectId", "stageChangeId"] },
"portal.disable_user": { required: ["portalUserId"] },
};
export function incompleteAutomationNodeConfigKeys(nodeType: string, config: Record<string, unknown>): readonly string[] {
const contract = AUTOMATION_CONFIG_REQUIREMENTS[nodeType];
if (!contract) return [];
const invalid = new Set<string>();
for (const key of contract.required ?? []) {
if (!hasAutomationConfigValue(config[key])) invalid.add(key);
}
for (const [key, allowedValues] of Object.entries(contract.allowed ?? {})) {
const value = config[key];
if (hasAutomationConfigValue(value) && (typeof value !== "string" || !allowedValues.includes(value))) invalid.add(key);
}
for (const conditional of contract.requiredWhen ?? []) {
if (config[conditional.whenKey] === conditional.equals && !hasAutomationConfigValue(config[conditional.key])) invalid.add(conditional.key);
}
if (nodeType === "delay.wait" && hasAutomationConfigValue(config.dauer)) {
const amount = Number(config.dauer);
if (!Number.isFinite(amount) || amount <= 0) invalid.add("dauer");
}
if (nodeType === "loop.for_each" && hasAutomationConfigValue(config.maxDurchlaeufe)) {
const count = Number(config.maxDurchlaeufe);
if (!Number.isInteger(count) || count < 1 || count > 100) invalid.add("maxDurchlaeufe");
}
if (nodeType === "projects.deadline_soon" && hasAutomationConfigValue(config.leadTime)) {
const leadTime = Number(config.leadTime);
if (!Number.isFinite(leadTime) || leadTime <= 0) invalid.add("leadTime");
}
if (nodeType === "time.schedule" && hasAutomationConfigValue(config.uhrzeit)) {
if (typeof config.uhrzeit !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/u.test(config.uhrzeit.trim())) invalid.add("uhrzeit");
}
if (nodeType === "time.schedule" && hasAutomationConfigValue(config.monatstag)) {
const day = Number(config.monatstag);
if (!Number.isInteger(day) || day < 1 || day > 31) invalid.add("monatstag");
}
return [...invalid];
}
function hasAutomationConfigValue(value: unknown): boolean {
if (typeof value === "string") return value.trim().length > 0;
return typeof value === "number" ? Number.isFinite(value) : typeof value === "boolean";
}
export function applyAutomationEditorOperation(
flow: AutomationEditorFlow,
operation: AutomationEditorOperation,
catalog: readonly AutomationNodeDefinition[]
): AutomationEditorFlow {
if (operation.type === "undo") return undoFlow(flow);
if (operation.type === "redo") return redoFlow(flow);
@@ -192,45 +400,143 @@ export function applyAutomationEditorOperation(flow: AutomationEditorFlow, opera
nodeType: node.key,
parentStepIds,
config: node.defaultConfig,
position: { x: 160 * (nextSteps.length % 4), y: 120 * Math.floor(nextSteps.length / 4) },
position: gridPosition(nextSteps.length),
sortOrder: nextSteps.length,
summaryKey: node.titleKey,
});
}
if (operation.type === "delete-node") {
if (operation.type === "delete-node" || operation.type === "delete-nodes") {
const removed = new Set(operation.type === "delete-node" ? [operation.stepKey] : operation.stepKeys);
nextSteps = nextSteps
.filter((step) => step.stepKey !== operation.stepKey)
.map((step, index) => ({ ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.stepKey), sortOrder: index }));
.filter((step) => !removed.has(step.stepKey))
.map((step, index) => ({ ...step, parentStepIds: step.parentStepIds.filter((parent) => !removed.has(parent)), sortOrder: index }));
}
if (operation.type === "duplicate-node") {
const source = nextSteps.find((step) => step.stepKey === operation.stepKey);
if (!source) return flow;
nextSteps.push({ ...source, stepKey: uniqueStepKey(nextSteps, source.nodeType), sortOrder: nextSteps.length, position: { x: source.position.x + 48, y: source.position.y + 48 } });
nextSteps.push({
...source,
stepKey: uniqueStepKey(nextSteps, source.nodeType),
sortOrder: nextSteps.length,
position: { x: source.position.x + 48, y: source.position.y + 48 },
});
}
if (operation.type === "paste-steps") {
const pasted = operation.steps
.map((raw, index) => normalizeStep(raw, nextSteps.length + index))
.filter(
(step): step is AutomationEditorStep => step !== null && Boolean(catalog.find((item) => item.key === step.nodeType) ?? getAutomationNode(step.nodeType))
);
if (pasted.length === 0) return flow;
const keyMap = new Map<string, string>();
const accumulated = [...nextSteps];
for (const step of pasted) {
const freshKey = uniqueStepKey(accumulated, step.nodeType);
keyMap.set(step.stepKey, freshKey);
accumulated.push({ ...step, stepKey: freshKey });
}
const existingKeys = new Set(nextSteps.map((step) => step.stepKey));
for (const step of pasted) {
nextSteps.push({
...step,
stepKey: keyMap.get(step.stepKey) ?? step.stepKey,
parentStepIds: step.parentStepIds
.map((parent) => keyMap.get(parent) ?? (existingKeys.has(parent) ? parent : null))
.filter((parent): parent is string => parent !== null),
config: remapConditionBranchParents(step.config, keyMap, existingKeys),
position: { x: step.position.x + 48, y: step.position.y + 48 },
sortOrder: nextSteps.length,
});
}
}
if (operation.type === "connect") {
const source = nextSteps.find((step) => step.stepKey === operation.fromStepKey);
nextSteps = nextSteps.map((step) =>
step.stepKey === operation.toStepKey && step.stepKey !== operation.fromStepKey
? { ...step, parentStepIds: uniqueStrings([...step.parentStepIds, operation.fromStepKey]) }
? {
...step,
parentStepIds: uniqueStrings([...step.parentStepIds, operation.fromStepKey]),
config:
source?.nodeType === "condition.if_else"
? withAutomationConditionBranch(step.config, operation.fromStepKey, operation.branch ?? "true")
: step.config,
}
: step
);
}
if (operation.type === "disconnect") {
nextSteps = nextSteps.map((step) => (step.stepKey === operation.toStepKey ? { ...step, parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.fromStepKey) } : step));
nextSteps = nextSteps.map((step) =>
step.stepKey === operation.toStepKey
? {
...step,
parentStepIds: step.parentStepIds.filter((parent) => parent !== operation.fromStepKey),
config: withAutomationConditionBranch(step.config, operation.fromStepKey, null),
}
: step
);
}
if (operation.type === "auto-layout") {
nextSteps = nextSteps.map((step, index) => ({ ...step, position: { x: 220 * (index % 3), y: 140 * Math.floor(index / 3) }, sortOrder: index }));
nextSteps = nextSteps.map((step, index) => ({ ...step, position: gridPosition(index), sortOrder: index }));
}
return withHistory({ triggerKey: nextSteps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey, steps: nextSteps, history: flow.history }, before);
return withHistory(
{ triggerKey: nextSteps.find((step) => step.kind === "trigger")?.nodeType ?? flow.triggerKey, steps: nextSteps, history: flow.history },
before
);
}
export function buildAutomationDryRunPreview(input: { readonly flow: AutomationEditorFlow; readonly matchedRecords?: number; readonly examples?: readonly string[] }): AutomationDryRunPreview {
function remapConditionBranchParents(
config: Record<string, unknown>,
keyMap: ReadonlyMap<string, string>,
existingKeys: ReadonlySet<string>
): Record<string, unknown> {
const next = { ...config };
delete next[AUTOMATION_CONDITION_BRANCHES_CONFIG_KEY];
for (const [parentStepKey, branch] of Object.entries(automationConditionBranches(config))) {
const remappedParent = keyMap.get(parentStepKey) ?? (existingKeys.has(parentStepKey) ? parentStepKey : null);
if (remappedParent) Object.assign(next, withAutomationConditionBranch(next, remappedParent, branch));
}
return next;
}
/**
* Extracts the given steps as serializable clipboard payload. Parent references
* pointing outside the selection are kept so a paste into the same flow can
* re-attach to still-existing steps; `applyAutomationEditorOperation` drops
* references that no longer resolve.
*/
export function extractAutomationClipboardSteps(flow: AutomationEditorFlow, stepKeys: readonly string[]): readonly AutomationEditorStepInput[] {
const wanted = new Set(stepKeys);
return flow.steps
.filter((step) => wanted.has(step.stepKey))
.map((step) => ({
stepKey: step.stepKey,
kind: step.kind,
nodeType: step.nodeType,
parentStepIds: [...step.parentStepIds],
config: { ...step.config },
position: { ...step.position },
sortOrder: step.sortOrder,
summaryKey: step.summaryKey,
}));
}
export function buildAutomationDryRunPreview(input: {
readonly flow: AutomationEditorFlow;
readonly confirmationPhrase: string;
readonly matchedRecords?: number;
readonly inspectedEvents?: number;
readonly sampleLimitReached?: boolean;
readonly examples?: readonly string[];
}): AutomationDryRunPreview {
const matchedRecords = Math.max(0, input.matchedRecords ?? 0);
const validation = validateAutomationEditorFlow(input.flow);
return {
requiresConfirmation: matchedRecords > DRY_RUN_CONFIRMATION_THRESHOLD,
confirmationPhrase: DRY_RUN_CONFIRMATION_PHRASE,
confirmationPhrase: input.confirmationPhrase,
matchedRecords,
inspectedEvents: Math.max(0, input.inspectedEvents ?? matchedRecords),
sampleLimitReached: input.sampleLimitReached ?? false,
examples: (input.examples ?? []).slice(0, 5),
steps: input.flow.steps.map((step) => ({
stepKey: step.stepKey,
@@ -242,29 +548,47 @@ export function buildAutomationDryRunPreview(input: { readonly flow: AutomationE
};
}
export function canConfirmAutomationDryRun(input: { readonly matchedRecords: number; readonly confirmationPhrase?: string | null }): boolean {
return input.matchedRecords <= DRY_RUN_CONFIRMATION_THRESHOLD || input.confirmationPhrase === DRY_RUN_CONFIRMATION_PHRASE;
export function canConfirmAutomationDryRun(input: {
readonly matchedRecords: number;
readonly confirmationPhrase?: string | null;
readonly expectedConfirmationPhrase: string;
}): boolean {
return input.matchedRecords <= DRY_RUN_CONFIRMATION_THRESHOLD || input.confirmationPhrase?.trim() === input.expectedConfirmationPhrase;
}
export function buildAutomationReversePlan(input: {
readonly reverseWindowExpiresAt: string | Date | null;
readonly steps: readonly { readonly stepKey: string; readonly nodeType: string }[];
readonly steps: readonly { readonly stepKey: string; readonly nodeType: string; readonly output?: unknown }[];
readonly confirmationPhrase: string;
readonly now?: Date;
}): AutomationReversePlan {
const expiresAt = typeof input.reverseWindowExpiresAt === "string" ? new Date(input.reverseWindowExpiresAt) : input.reverseWindowExpiresAt;
const canReverse = !!expiresAt && expiresAt.getTime() > (input.now ?? new Date()).getTime();
const items = input.steps.map((step) => {
const action = reverseActionForNode(step.nodeType);
return { stepKey: step.stepKey, nodeType: step.nodeType, actionKey: action.actionKey, reversible: action.reversible };
return {
stepKey: step.stepKey,
nodeType: step.nodeType,
actionKey: action.actionKey,
reversible: action.reversible,
recipients: extractAutomationReverseRecipients(step.nodeType, step.output),
};
});
return {
canReverse,
confirmationPhrase: REVERSE_CONFIRMATION_PHRASE,
confirmationPhrase: input.confirmationPhrase,
items,
warnings: items.filter((item) => !item.reversible).map((item) => item.actionKey),
};
}
export function canConfirmAutomationReverse(input: {
readonly confirmationPhrase: string | null | undefined;
readonly expectedConfirmationPhrase: string;
}): boolean {
return input.confirmationPhrase?.trim().toLocaleUpperCase() === input.expectedConfirmationPhrase.trim().toLocaleUpperCase();
}
function normalizeStep(raw: AutomationEditorStepInput, index: number): AutomationEditorStep | null {
const object = objectOrEmpty(raw);
const nodeType = typeof object.nodeType === "string" ? object.nodeType : "";
@@ -279,23 +603,40 @@ function normalizeStep(raw: AutomationEditorStepInput, index: number): Automatio
config: objectOrEmpty(object.config),
position: normalizePosition(object.position, index),
sortOrder: typeof object.sortOrder === "number" ? object.sortOrder : index,
summaryKey: typeof object.summaryKey === "string" ? object.summaryKey : typeof object.summaryText === "string" ? object.summaryText : node?.titleKey ?? "automation.execution.stepQueued",
summaryKey:
typeof object.summaryKey === "string"
? object.summaryKey
: typeof object.summaryText === "string"
? object.summaryText
: (node?.titleKey ?? "automation.execution.stepQueued"),
};
}
function normalizeHistory(value: unknown): AutomationEditorFlow["history"] {
const raw = objectOrEmpty(value);
return {
past: Array.isArray(raw.past) ? raw.past.map(normalizeSnapshot).filter((item): item is AutomationEditorSnapshot => item !== null).slice(-MAX_HISTORY) : [],
future: Array.isArray(raw.future) ? raw.future.map(normalizeSnapshot).filter((item): item is AutomationEditorSnapshot => item !== null).slice(-MAX_HISTORY) : [],
past: Array.isArray(raw.past)
? raw.past
.map(normalizeSnapshot)
.filter((item): item is AutomationEditorSnapshot => item !== null)
.slice(-MAX_HISTORY)
: [],
future: Array.isArray(raw.future)
? raw.future
.map(normalizeSnapshot)
.filter((item): item is AutomationEditorSnapshot => item !== null)
.slice(-MAX_HISTORY)
: [],
};
}
function normalizeSnapshot(value: unknown): AutomationEditorSnapshot | null {
const raw = objectOrEmpty(value);
const steps = Array.isArray(raw.steps) ? raw.steps.map((step, index) => normalizeStep(step as AutomationEditorStepInput, index)).filter((step): step is AutomationEditorStep => step !== null) : [];
const steps = Array.isArray(raw.steps)
? raw.steps.map((step, index) => normalizeStep(step as AutomationEditorStepInput, index)).filter((step): step is AutomationEditorStep => step !== null)
: [];
if (steps.length === 0) return null;
return { triggerKey: typeof raw.triggerKey === "string" ? raw.triggerKey : steps.find((step) => step.kind === "trigger")?.nodeType ?? "", steps };
return { triggerKey: typeof raw.triggerKey === "string" ? raw.triggerKey : (steps.find((step) => step.kind === "trigger")?.nodeType ?? ""), steps };
}
function normalizeKind(value: unknown, fallback: AutomationNodeKind): AutomationNodeKind {
@@ -304,9 +645,10 @@ function normalizeKind(value: unknown, fallback: AutomationNodeKind): Automation
function normalizePosition(value: unknown, index: number): AutomationEditorStep["position"] {
const raw = objectOrEmpty(value);
const fallback = gridPosition(index);
return {
x: typeof raw.x === "number" ? raw.x : 220 * (index % 3),
y: typeof raw.y === "number" ? raw.y : 140 * Math.floor(index / 3),
x: typeof raw.x === "number" ? raw.x : fallback.x,
y: typeof raw.y === "number" ? raw.y : fallback.y,
};
}
@@ -390,12 +732,42 @@ function uniqueStrings(values: readonly string[]): readonly string[] {
return [...new Set(values.filter(Boolean))];
}
/**
* Reads the delivered-recipient list from a persisted send-step output.
* Contract: `output.recipients` is an array of strings (email) or objects with
* `name`/`email`. Tolerates missing or malformed outputs (returns empty list)
* because forward outputs are only available once the executor persisted them.
*/
export function extractAutomationReverseRecipients(nodeType: string, output: unknown): readonly AutomationReverseRecipient[] {
if (nodeType !== "notification.send" && !nodeType.startsWith("email.")) return [];
const record = objectOrEmpty(output);
const raw = Array.isArray(record.recipients) ? record.recipients : [];
return raw
.map((entry): AutomationReverseRecipient => {
if (typeof entry === "string") return { name: null, email: entry };
const item = objectOrEmpty(entry);
return {
name: typeof item.name === "string" && item.name.trim() ? item.name : null,
email: typeof item.email === "string" && item.email.trim() ? item.email : null,
};
})
.filter((entry) => entry.name !== null || entry.email !== null);
}
function reverseActionForNode(nodeType: string): { actionKey: string; reversible: boolean } {
if (nodeType === "task.create") return { actionKey: "automation.editor.reverse.actions.deleteTask", reversible: true };
if (nodeType === "crm.update_kontakt") return { actionKey: "automation.editor.reverse.actions.revertCrmStatus", reversible: true };
if (nodeType === "crm.create_note") return { actionKey: "automation.editor.reverse.actions.deleteCrmNote", reversible: true };
if (nodeType === "crm.add_tag") return { actionKey: "automation.editor.reverse.actions.removeContactTag", reversible: true };
if (nodeType === "crm.remove_tag") return { actionKey: "automation.editor.reverse.actions.restoreContactTag", reversible: true };
if (nodeType === "crm.assign_kontakt") return { actionKey: "automation.editor.reverse.actions.restoreContactAssignment", reversible: true };
if (nodeType === "lead.assign") return { actionKey: "automation.editor.reverse.actions.restoreLeadAssignment", reversible: true };
if (nodeType === "lead.set_status") return { actionKey: "automation.editor.reverse.actions.restoreLeadStatus", reversible: true };
// CRM notes are append-only Activity entries in the current typed model. They
// stay visible for auditability and therefore cannot be destructively undone.
if (nodeType === "crm.create_note") return { actionKey: "automation.editor.reverse.actions.deleteCrmNote", reversible: false };
if (nodeType === "task.assign") return { actionKey: "automation.editor.reverse.actions.restoreTaskAssignment", reversible: true };
if (nodeType === "notification.send" || nodeType.startsWith("email.")) return { actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false };
if (nodeType === "notification.send" || nodeType.startsWith("email.") || nodeType === "chat.post_message")
return { actionKey: "automation.editor.reverse.actions.deliveryNotReversible", reversible: false };
return { actionKey: "automation.editor.reverse.actions.noop", reversible: false };
}
@@ -0,0 +1,31 @@
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
export function buildCalendarCreatedWorkflowEvent(input: {
readonly tenantId: string;
readonly calendarEventId: string;
readonly userId: string | null;
readonly calendarKey: string;
readonly eventKind: string;
readonly source: string;
readonly sourceEntityId: string;
readonly startsAt: Date;
readonly endsAt: Date;
}) {
return buildWorkflowTriggerOutboxEvent({
tenantId: input.tenantId,
event: "calendar.event_created",
data: {
calendarEventId: input.calendarEventId,
calendarKey: input.calendarKey,
kalender: input.calendarKey,
eventKind: input.eventKind,
ereignisart: input.eventKind,
source: input.source,
sourceEntityId: input.sourceEntityId,
startsAt: input.startsAt.toISOString(),
endsAt: input.endsAt.toISOString(),
},
userId: input.userId,
sourceId: `calendar:${input.calendarEventId}:created`,
});
}
@@ -1,17 +1,23 @@
import { describe, expect, it } from "vitest";
import { AUTOMATION_CORE_EXECUTOR_NODE_TYPES } from "@hivegrid/db/automation-executor.server";
import {
AUTOMATION_MODULE_KEY,
AUTOMATION_READ_PERMISSION,
AUTOMATION_TRIGGERS_WITHOUT_EMITTER,
automationActionCatalog,
automationTemplateCatalog,
automationTemplateFlowData,
automationTriggerCatalog,
buildAutomationIdempotencyKey,
buildReverseWindowExpiresAt,
evaluateLoopGuard,
evaluateTriggerVolume,
getAutomationPlatformTemplateByStoredName,
listAutomationNodes,
planAutomationRetry,
translateAutomationPlatformTemplate,
} from "./automation.registry";
import { buildAutomationEditorFlow, validateAutomationEditorFlow } from "./automation.editor";
describe("automation registry contract", () => {
it("uses the R-P12a module and permission keys", () => {
@@ -20,20 +26,183 @@ describe("automation registry contract", () => {
});
it("covers the required trigger and action groups", () => {
expect(new Set(automationTriggerCatalog.map((node) => node.group))).toEqual(new Set(["crm", "lead", "sales", "projects", "email", "forms", "booking", "calendar", "time", "webhook"]));
expect(new Set(automationActionCatalog.map((node) => node.group))).toEqual(new Set(["crm", "notification", "http", "task", "flow_control", "kwp"]));
expect(new Set(automationTriggerCatalog.map((node) => node.group))).toEqual(
new Set(["crm", "lead", "sales", "projects", "email", "forms", "booking", "calendar", "time", "webhook", "portal"])
);
expect(new Set(automationActionCatalog.map((node) => node.group))).toEqual(
new Set([
"crm",
"lead",
"sales",
"projects",
"notification",
"chat",
"email",
"webhook",
"calendar",
"files",
"http",
"task",
"flow_control",
"kwp",
"portal",
])
);
expect(automationActionCatalog.find((node) => node.key === "kwp.push_project")?.availability).toBe("extension_slot");
expect(
automationActionCatalog
.filter((node) => ["crm.add_tag", "crm.remove_tag", "crm.assign_kontakt"].includes(node.key))
.every((node) => node.availability === "active")
).toBe(true);
expect(
automationActionCatalog.filter((node) => ["lead.assign", "lead.set_status"].includes(node.key)).every((node) => node.availability === "active")
).toBe(true);
expect(automationActionCatalog.find((node) => node.key === "chat.post_message")?.availability).toBe("active");
expect(automationActionCatalog.filter((node) => ["flow.parallel", "flow.merge"].includes(node.key)).every((node) => node.availability === "active")).toBe(
true
);
expect(automationActionCatalog.find((node) => node.key === "loop.for_each")).toMatchObject({ kind: "flow_control", availability: "extension_slot" });
expect(listAutomationNodes()).toHaveLength(automationTriggerCatalog.length + automationActionCatalog.length);
});
it("prepares every still-missing Phase-1 action without making it runnable", () => {
expect(automationActionCatalog.filter((node) => node.availability === "extension_slot").map((node) => node.key)).toEqual([
"lead.convert_to_project",
"sales.create_project",
"sales.change_stage",
"sales.change_volume",
"sales.assign_project",
"sales.add_project_tag",
"sales.move_pipeline",
"projects.create_project",
"projects.create_from_won_sales",
"projects.change_stage",
"projects.add_member",
"projects.create_task",
"projects.create_appointment",
"projects.start_acceptance",
"projects.move_pipeline",
"notification.send_push",
"webhook.send_signed",
"calendar.create_event",
"calendar.update_event",
"files.create_from_url",
"loop.for_each",
"kwp.push_project",
]);
});
it("never exposes an active core action without a real executor handler", () => {
const activeCoreNodes = automationActionCatalog.filter((node) => node.availability === "active" && node.group !== "portal");
expect(activeCoreNodes.map((node) => node.key).filter((key) => !AUTOMATION_CORE_EXECUTOR_NODE_TYPES.has(key))).toEqual([]);
});
it("registers the complete P26b portal trigger and action contracts", () => {
expect(automationTriggerCatalog.filter((node) => node.group === "portal").map((node) => node.key)).toEqual([
"portal.user_created",
"portal.setup_completed",
"portal.logged_in",
"portal.upload_completed",
"portal.complaint_submitted",
"portal.access_granted",
"portal.access_revoked",
"portal.document_released",
"portal.document_downloaded",
"portal.status_mail_sent",
"portal.lifecycle_changed",
]);
expect(automationActionCatalog.filter((node) => node.group === "portal").map((node) => node.key)).toEqual([
"portal.invite_user",
"portal.grant_access",
"portal.revoke_access",
"portal.release_document",
"portal.send_status_mail",
"portal.disable_user",
]);
for (const node of [...automationTriggerCatalog, ...automationActionCatalog].filter((entry) => entry.group === "portal")) {
expect(node.availability).toBe("active");
expect(node.requiredAnyPermission.every((permission) => permission.startsWith("portal."))).toBe(true);
}
});
it("tracks every catalog trigger that has no production emitter", () => {
expect([...AUTOMATION_TRIGGERS_WITHOUT_EMITTER].sort()).toEqual([]);
expect(AUTOMATION_TRIGGERS_WITHOUT_EMITTER.has("webhook.received")).toBe(false);
});
it("ships platform templates that can become rules", () => {
expect(automationTemplateCatalog.map((template) => template.key)).toEqual(["lead-qualified-follow-up", "project-deadline-warning", "form-submission-create-task"]);
expect(automationTemplateCatalog.map((template) => template.key)).toEqual([
"lead-qualified-follow-up",
"project-deadline-warning",
"form-submission-create-task",
]);
for (const template of automationTemplateCatalog) {
expect(template.steps[0]?.kind).toBe("trigger");
expect(template.steps.map((step) => step.stepKey)).toContain("trigger");
const flowData = automationTemplateFlowData(template);
const flow = buildAutomationEditorFlow({ flowData, steps: flowData.steps });
expect(validateAutomationEditorFlow(flow).issues).toEqual([]);
expect(validateAutomationEditorFlow(flow).canActivate).toBe(true);
expect(getAutomationPlatformTemplateByStoredName(template.defaultName)?.key).toBe(template.key);
expect(getAutomationPlatformTemplateByStoredName(template.nameKey)?.key).toBe(template.key);
}
});
it("translates all code-owned template copy without changing config semantics", () => {
const translationKeys: string[] = [];
const translate = (key: string) => {
translationKeys.push(key);
return `translated:${key}`;
};
const [leadTemplate, deadlineTemplate, formTemplate] = automationTemplateCatalog;
const translatedLead = translateAutomationPlatformTemplate(leadTemplate, translate);
const translatedDeadline = translateAutomationPlatformTemplate(deadlineTemplate, translate);
const translatedForm = translateAutomationPlatformTemplate(formTemplate, translate);
expect(translatedLead.name).toBe("translated:automation.templates.leadQualifiedFollowUp.name");
expect(translatedLead.description).toBe("translated:automation.templates.leadQualifiedFollowUp.description");
expect(translatedLead.flowData.steps.find((step) => step.stepKey === "create-task")?.config).toMatchObject({
titel: "translated:automation.templates.leadQualifiedFollowUp.taskTitle",
zustaendig: "besitzerDerAutomation",
faelligkeit: "einTag",
prioritaet: "hoch",
});
expect(translatedLead.flowData.steps.find((step) => step.stepKey === "notify-office")?.config).toMatchObject({
betreff: "translated:automation.templates.leadQualifiedFollowUp.notificationSubject",
nachricht: "translated:automation.templates.leadQualifiedFollowUp.notificationMessage",
});
expect(translatedDeadline.flowData.steps.find((step) => step.stepKey === "notify-project-lead")?.config).toMatchObject({
betreff: "translated:automation.templates.projectDeadlineWarning.notificationSubject",
nachricht: "translated:automation.templates.projectDeadlineWarning.notificationMessage",
});
expect(translatedForm.flowData.steps.find((step) => step.stepKey === "create-task")?.config.titel).toBe(
"translated:automation.templates.formSubmissionCreateTask.taskTitle"
);
expect(translationKeys).toEqual([
"automation.templates.leadQualifiedFollowUp.name",
"automation.templates.leadQualifiedFollowUp.description",
"automation.templates.leadQualifiedFollowUp.taskTitle",
"automation.templates.leadQualifiedFollowUp.notificationSubject",
"automation.templates.leadQualifiedFollowUp.notificationMessage",
"automation.templates.projectDeadlineWarning.name",
"automation.templates.projectDeadlineWarning.description",
"automation.templates.projectDeadlineWarning.notificationSubject",
"automation.templates.projectDeadlineWarning.notificationMessage",
"automation.templates.formSubmissionCreateTask.name",
"automation.templates.formSubmissionCreateTask.description",
"automation.templates.formSubmissionCreateTask.taskTitle",
]);
});
it("keeps locale-free seed copy stable and excludes translation metadata", () => {
const [template] = automationTemplateCatalog;
const flowData = automationTemplateFlowData(template);
expect(flowData.steps.find((step) => step.stepKey === "create-task")?.config.titel).toBe("Qualifizierten Lead nachfassen");
expect(flowData.steps.every((step) => !("configTranslationKeys" in step))).toBe(true);
});
it("detects dependency cycles for loop guard warnings", () => {
expect(
evaluateLoopGuard([
@@ -52,12 +221,21 @@ describe("automation registry contract", () => {
});
it("builds idempotency keys and 24h reverse windows deterministically", () => {
expect(buildAutomationIdempotencyKey({ tenantId: "t1", ruleId: "r1", triggerKey: "lead.qualified", sourceEventId: "evt1" })).toBe("t1:r1:lead.qualified:evt1");
expect(buildAutomationIdempotencyKey({ tenantId: "t1", ruleId: "r1", triggerKey: "lead.qualified", sourceEventId: "evt1" })).toBe(
"t1:r1:lead.qualified:evt1"
);
expect(buildReverseWindowExpiresAt(new Date("2026-07-01T10:00:00.000Z")).toISOString()).toBe("2026-07-02T10:00:00.000Z");
});
it("pauses anomalous trigger volumes with Klartext diagnostics", () => {
const result = evaluateTriggerVolume({ triggerKey: "lead.qualified", countInWindow: 2000, windowMinutes: 5, typicalDailyMin: 5, typicalDailyMax: 10, hardLimitInWindow: 2000 });
const result = evaluateTriggerVolume({
triggerKey: "lead.qualified",
countInWindow: 2000,
windowMinutes: 5,
typicalDailyMin: 5,
typicalDailyMax: 10,
hardLimitInWindow: 2000,
});
expect(result.action).toBe("pause");
expect(result.summaryText).toContain("2000 automation triggers in 5 minutes");
@@ -69,6 +247,10 @@ describe("automation registry contract", () => {
expect(retry).toMatchObject({ shouldRetry: true, nextAttempt: 2, summaryKey: "automation.guards.retryScheduled" });
expect(retry.nextRetryAt?.toISOString()).toBe("2026-07-01T10:00:01.000Z");
expect(planAutomationRetry({ attempt: 3, maxAttempts: 3 })).toMatchObject({ shouldRetry: false, nextAttempt: 4, summaryKey: "automation.guards.retryExhausted" });
expect(planAutomationRetry({ attempt: 3, maxAttempts: 3 })).toMatchObject({
shouldRetry: false,
nextAttempt: 4,
summaryKey: "automation.guards.retryExhausted",
});
});
});
@@ -4,7 +4,25 @@ export const AUTOMATION_MANAGE_PERMISSION = "automation.manage";
export const AUTOMATION_RUN_PERMISSION = "automation.run";
export const AUTOMATION_ADMIN_PERMISSION = "automation.admin";
export type AutomationNodeGroup = "crm" | "lead" | "sales" | "projects" | "email" | "forms" | "booking" | "calendar" | "time" | "webhook" | "notification" | "http" | "task" | "flow_control" | "kwp";
export type AutomationNodeGroup =
| "crm"
| "lead"
| "sales"
| "projects"
| "email"
| "forms"
| "booking"
| "calendar"
| "chat"
| "files"
| "time"
| "webhook"
| "notification"
| "http"
| "task"
| "flow_control"
| "kwp"
| "portal";
export type AutomationNodeKind = "trigger" | "condition" | "action" | "flow_control";
export type AutomationNodeAvailability = "active" | "extension_slot";
@@ -23,6 +41,13 @@ export interface AutomationTemplateDefinition {
readonly key: string;
readonly nameKey: string;
readonly descriptionKey: string;
/**
* Legacy seed copy used only by the locale-free deployment seed and to match
* rows written by older revisions. Request paths resolve `nameKey` and
* `descriptionKey` instead, so this fallback must never become tenant copy.
*/
readonly defaultName: string;
readonly defaultDescription: string;
readonly category: "crm" | "sales" | "projects" | "operations";
readonly triggerKey: string;
readonly steps: readonly {
@@ -31,42 +56,30 @@ export interface AutomationTemplateDefinition {
readonly nodeType: string;
readonly parentStepIds: readonly string[];
readonly summaryKey: string;
readonly config: Readonly<Record<string, string | number | boolean>>;
/** Config fields whose code-owned copy is translated per request. */
readonly configTranslationKeys?: Readonly<Record<string, string>>;
}[];
}
export interface AutomationGraphStep {
readonly stepKey: string;
readonly nodeType: string;
readonly parentStepIds: readonly string[];
}
type AutomationTemplateTranslator = (key: string) => string;
export interface AutomationLoopGuardResult {
readonly ok: boolean;
readonly summaryKey: string;
readonly cycleStepKeys: readonly string[];
readonly dependencyEdges: readonly { readonly from: string; readonly to: string }[];
}
export interface AutomationTriggerVolumeInput {
readonly triggerKey: string;
readonly countInWindow: number;
readonly windowMinutes: number;
readonly typicalDailyMin: number;
readonly typicalDailyMax: number;
readonly hardLimitInWindow: number;
}
export interface AutomationTriggerVolumeResult {
readonly action: "allow" | "pause";
readonly summaryText: string;
}
export interface AutomationRetryPlan {
readonly shouldRetry: boolean;
readonly nextRetryAt: Date | null;
readonly nextAttempt: number;
readonly summaryKey: string;
}
// R-P12c: the pure guard functions moved to @hivegrid/db/automation-guards so
// the worker-side forward executor can share them. Re-exported here so all
// existing web consumers keep importing from the registry unchanged.
export {
AUTOMATION_TRIGGER_VOLUME_ANOMALY_KEY,
buildAutomationIdempotencyKey,
buildReverseWindowExpiresAt,
evaluateLoopGuard,
evaluateTriggerVolume,
planAutomationRetry,
type AutomationGraphStep,
type AutomationLoopGuardResult,
type AutomationRetryPlan,
type AutomationTriggerVolumeInput,
type AutomationTriggerVolumeResult,
} from "@hivegrid/db/automation-guards";
export const automationTriggerCatalog = Object.freeze([
trigger("crm.kontakt_created", "crm", ["crm.read_all", "crm.write"]),
@@ -85,58 +98,216 @@ export const automationTriggerCatalog = Object.freeze([
trigger("calendar.event_created", "calendar", ["calendar.connect_own", "calendar.admin"]),
trigger("time.schedule", "time", [AUTOMATION_MANAGE_PERMISSION]),
trigger("webhook.received", "webhook", [AUTOMATION_RUN_PERMISSION, AUTOMATION_MANAGE_PERMISSION]),
trigger("portal.user_created", "portal", ["portal.read", "portal.manage_users"]),
trigger("portal.setup_completed", "portal", ["portal.activity.read", "portal.manage_users"]),
trigger("portal.logged_in", "portal", ["portal.activity.read"]),
trigger("portal.upload_completed", "portal", ["portal.activity.read"]),
trigger("portal.complaint_submitted", "portal", ["portal.activity.read"]),
trigger("portal.access_granted", "portal", ["portal.activity.read", "portal.manage_access"]),
trigger("portal.access_revoked", "portal", ["portal.activity.read", "portal.manage_access"]),
trigger("portal.document_released", "portal", ["portal.activity.read", "portal.manage_access"]),
trigger("portal.document_downloaded", "portal", ["portal.activity.read"]),
trigger("portal.status_mail_sent", "portal", ["portal.activity.read"]),
trigger("portal.lifecycle_changed", "portal", ["portal.activity.read", "portal.manage_users"]),
] as const satisfies readonly AutomationNodeDefinition[]);
export const automationActionCatalog = Object.freeze([
action("crm.update_kontakt", "crm", ["crm.write"]),
action("crm.add_tag", "crm", ["crm.write"]),
action("crm.remove_tag", "crm", ["crm.write"]),
action("crm.assign_kontakt", "crm", ["crm.write"]),
action("crm.create_note", "crm", ["crm.write"]),
action("lead.assign", "lead", ["leads.write"]),
action("lead.set_status", "lead", ["leads.write"]),
extension("lead.convert_to_project", "lead", ["leads.write", "projects.write"]),
extension("sales.create_project", "sales", ["projects.write"]),
extension("sales.change_stage", "sales", ["projects.change_stage"]),
extension("sales.change_volume", "sales", ["projects.write"]),
extension("sales.assign_project", "sales", ["projects.write"]),
extension("sales.add_project_tag", "sales", ["projects.write"]),
extension("sales.move_pipeline", "sales", ["projects.change_stage"]),
extension("projects.create_project", "projects", ["projects.write"]),
extension("projects.create_from_won_sales", "projects", ["projects.write"]),
extension("projects.change_stage", "projects", ["projects.change_stage"]),
extension("projects.add_member", "projects", ["projects.write"]),
extension("projects.create_task", "projects", ["projects.write", "tasks.write"]),
extension("projects.create_appointment", "projects", ["projects.write"]),
extension("projects.start_acceptance", "projects", ["projects.write"]),
extension("projects.move_pipeline", "projects", ["projects.change_stage"]),
action("notification.send", "notification", [AUTOMATION_RUN_PERMISSION]),
extension("notification.send_push", "notification", [AUTOMATION_RUN_PERMISSION]),
action("chat.post_message", "chat", ["chat.write"]),
// R-P12c: external transactional mail via the durable mail outbox (K-A2
// "E-Mail senden" — was design-only until the forward executor existed).
action("email.send_transactional", "email", [AUTOMATION_RUN_PERMISSION]),
action("http.request", "http", [AUTOMATION_RUN_PERMISSION]),
extension("webhook.send_signed", "webhook", [AUTOMATION_RUN_PERMISSION]),
extension("calendar.create_event", "calendar", ["calendar.connect_own", "calendar.admin"]),
extension("calendar.update_event", "calendar", ["calendar.connect_own", "calendar.admin"]),
extension("files.create_from_url", "files", ["files.write"]),
action("task.create", "task", ["tasks.write"]),
action("task.assign", "task", ["tasks.write"]),
flow("condition.if_else", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
flow("delay.wait", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
flow("loop.for_each", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
flow("flow.parallel", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
flow("flow.merge", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
flowExtension("loop.for_each", "flow_control", [AUTOMATION_MANAGE_PERMISSION]),
extension("kwp.push_project", "kwp", ["integrations.manual_sync", AUTOMATION_MANAGE_PERMISSION]),
action("portal.invite_user", "portal", ["portal.manage_users"]),
action("portal.grant_access", "portal", ["portal.manage_access"]),
action("portal.revoke_access", "portal", ["portal.manage_access"]),
action("portal.release_document", "portal", ["portal.manage_access"]),
action("portal.send_status_mail", "portal", ["portal.activity.manage"]),
action("portal.disable_user", "portal", ["portal.manage_users"]),
] as const satisfies readonly AutomationNodeDefinition[]);
export const automationTemplateCatalog = Object.freeze([
{
key: "lead-qualified-follow-up",
defaultName: "Qualifizierter Lead: Nachfassen",
defaultDescription: "Legt nach einer Lead-Qualifizierung eine Vertriebsaufgabe an und benachrichtigt das Büro.",
nameKey: "automation.templates.leadQualifiedFollowUp.name",
descriptionKey: "automation.templates.leadQualifiedFollowUp.description",
category: "sales",
triggerKey: "lead.qualified",
steps: [
{ stepKey: "trigger", kind: "trigger", nodeType: "lead.qualified", parentStepIds: [], summaryKey: "automation.steps.triggerLeadQualified" },
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createSalesTask" },
{ stepKey: "notify-office", kind: "action", nodeType: "notification.send", parentStepIds: ["create-task"], summaryKey: "automation.steps.notifyOffice" },
{
stepKey: "trigger",
kind: "trigger",
nodeType: "lead.qualified",
parentStepIds: [],
summaryKey: "automation.steps.triggerLeadQualified",
config: {},
},
{
stepKey: "create-task",
kind: "action",
nodeType: "task.create",
parentStepIds: ["trigger"],
summaryKey: "automation.steps.createSalesTask",
config: { titel: "Qualifizierten Lead nachfassen", zustaendig: "besitzerDerAutomation", faelligkeit: "einTag", prioritaet: "hoch" },
configTranslationKeys: { titel: "automation.templates.leadQualifiedFollowUp.taskTitle" },
},
{
stepKey: "notify-office",
kind: "action",
nodeType: "notification.send",
parentStepIds: ["create-task"],
summaryKey: "automation.steps.notifyOffice",
config: {
kanal: "intern",
empfaenger: "besitzerDerAutomation",
betreff: "Qualifizierter Lead",
nachricht: "Ein qualifizierter Lead wartet auf Nachverfolgung.",
},
configTranslationKeys: {
betreff: "automation.templates.leadQualifiedFollowUp.notificationSubject",
nachricht: "automation.templates.leadQualifiedFollowUp.notificationMessage",
},
},
],
},
{
key: "project-deadline-warning",
defaultName: "Projektfrist früh warnen",
defaultDescription: "Benachrichtigt die Projektleitung vor kritischen Fristen.",
nameKey: "automation.templates.projectDeadlineWarning.name",
descriptionKey: "automation.templates.projectDeadlineWarning.description",
category: "projects",
triggerKey: "projects.deadline_soon",
steps: [
{ stepKey: "trigger", kind: "trigger", nodeType: "projects.deadline_soon", parentStepIds: [], summaryKey: "automation.steps.triggerProjectDeadline" },
{ stepKey: "notify-project-lead", kind: "action", nodeType: "notification.send", parentStepIds: ["trigger"], summaryKey: "automation.steps.notifyProjectLead" },
{
stepKey: "trigger",
kind: "trigger",
nodeType: "projects.deadline_soon",
parentStepIds: [],
summaryKey: "automation.steps.triggerProjectDeadline",
config: { fristtyp: "projektDeadline", leadTime: "3", leadTimeUnit: "tage" },
},
{
stepKey: "notify-project-lead",
kind: "action",
nodeType: "notification.send",
parentStepIds: ["trigger"],
summaryKey: "automation.steps.notifyProjectLead",
config: {
kanal: "intern",
empfaenger: "besitzerDerAutomation",
betreff: "Projektfrist naht",
nachricht: "Eine Projektfrist wird in Kürze erreicht.",
},
configTranslationKeys: {
betreff: "automation.templates.projectDeadlineWarning.notificationSubject",
nachricht: "automation.templates.projectDeadlineWarning.notificationMessage",
},
},
],
},
{
key: "form-submission-create-task",
defaultName: "Formularantwort als Aufgabe",
defaultDescription: "Erstellt aus einer Formularantwort eine Backoffice-Aufgabe.",
nameKey: "automation.templates.formSubmissionCreateTask.name",
descriptionKey: "automation.templates.formSubmissionCreateTask.description",
category: "operations",
triggerKey: "forms.submitted",
steps: [
{ stepKey: "trigger", kind: "trigger", nodeType: "forms.submitted", parentStepIds: [], summaryKey: "automation.steps.triggerFormSubmitted" },
{ stepKey: "create-task", kind: "action", nodeType: "task.create", parentStepIds: ["trigger"], summaryKey: "automation.steps.createBackofficeTask" },
{
stepKey: "trigger",
kind: "trigger",
nodeType: "forms.submitted",
parentStepIds: [],
summaryKey: "automation.steps.triggerFormSubmitted",
config: {},
},
{
stepKey: "create-task",
kind: "action",
nodeType: "task.create",
parentStepIds: ["trigger"],
summaryKey: "automation.steps.createBackofficeTask",
config: { titel: "Formularantwort prüfen", zustaendig: "besitzerDerAutomation", faelligkeit: "einTag", prioritaet: "normal" },
configTranslationKeys: { titel: "automation.templates.formSubmissionCreateTask.taskTitle" },
},
],
},
] as const satisfies readonly AutomationTemplateDefinition[]);
export function automationTemplateFlowData(template: (typeof automationTemplateCatalog)[number], translate?: AutomationTemplateTranslator) {
return {
templateKey: template.key,
triggerKey: template.triggerKey,
steps: template.steps.map((step) => ({
stepKey: step.stepKey,
kind: step.kind,
nodeType: step.nodeType,
parentStepIds: step.parentStepIds,
summaryKey: step.summaryKey,
config: Object.fromEntries(
Object.entries(step.config).map(([field, value]) => {
const configTranslationKeys =
"configTranslationKeys" in step ? (step.configTranslationKeys as Readonly<Record<string, string>>) : undefined;
const translationKey = configTranslationKeys?.[field];
return [field, translate && translationKey ? translate(translationKey) : value];
})
),
})),
};
}
export function translateAutomationPlatformTemplate(template: (typeof automationTemplateCatalog)[number], translate: AutomationTemplateTranslator) {
return {
name: translate(template.nameKey),
description: translate(template.descriptionKey),
flowData: automationTemplateFlowData(template, translate),
};
}
/** Resolves code-owned platform templates even when a persisted row is from an older seed revision. */
export function getAutomationPlatformTemplateByStoredName(name: string): (typeof automationTemplateCatalog)[number] | undefined {
return automationTemplateCatalog.find((template) => template.defaultName === name || template.nameKey === name);
}
const nodeByKey = new Map([...automationTriggerCatalog, ...automationActionCatalog].map((node) => [node.key, node]));
export function listAutomationNodes(): readonly AutomationNodeDefinition[] {
@@ -147,6 +318,37 @@ export function getAutomationNode(key: string): AutomationNodeDefinition | undef
return nodeByKey.get(key);
}
/**
* Which executor can run a node. `portal.*` nodes are served exclusively by the
* portal-automation consumer (apps/worker/src/jobs/portal-automation.ts), every
* other node by the generic forward executor. The two never meet: a portal
* action in a core flow ends the run as `unsupportedNode`, and the portal
* consumer rejects a rule whose actions are not all portal actions. Mixing them
* therefore has to be caught while building, not at runtime.
*/
export type AutomationExecutionFamily = "portal" | "core";
export function automationExecutionFamily(nodeKey: string): AutomationExecutionFamily {
return nodeKey.startsWith("portal.") ? "portal" : "core";
}
/**
* Nodes the catalog lists but no executor implements yet. Active core and
* portal nodes are backed by their corresponding executor; extension slots
* remain non-runnable until their provider handler exists (AD-32 / KWP).
*/
const NODES_WITHOUT_EXECUTOR = new Set<string>();
export function isAutomationNodeRunnable(node: AutomationNodeDefinition): boolean {
return node.availability === "active" && !NODES_WITHOUT_EXECUTOR.has(node.key);
}
/**
* Triggers the catalog offers that no emitter publishes yet, so a rule built on
* them would sit active and never start.
*/
export const AUTOMATION_TRIGGERS_WITHOUT_EMITTER: ReadonlySet<string> = new Set();
export function assertAutomationNodeExists(key: string): AutomationNodeDefinition {
const node = getAutomationNode(key);
if (!node) {
@@ -155,94 +357,6 @@ export function assertAutomationNodeExists(key: string): AutomationNodeDefinitio
return node;
}
export function evaluateLoopGuard(steps: readonly AutomationGraphStep[]): AutomationLoopGuardResult {
const stepKeys = new Set(steps.map((step) => step.stepKey));
const dependencyEdges = steps.flatMap((step) =>
step.parentStepIds.filter((parentStepId) => stepKeys.has(parentStepId)).map((parentStepId) => ({ from: parentStepId, to: step.stepKey }))
);
const outgoing = new Map<string, string[]>();
for (const edge of dependencyEdges) {
outgoing.set(edge.from, [...(outgoing.get(edge.from) ?? []), edge.to]);
}
const visiting = new Set<string>();
const visited = new Set<string>();
const path: string[] = [];
function visit(stepKey: string): string[] | null {
if (visiting.has(stepKey)) {
const start = path.indexOf(stepKey);
return start >= 0 ? path.slice(start).concat(stepKey) : [stepKey];
}
if (visited.has(stepKey)) return null;
visiting.add(stepKey);
path.push(stepKey);
for (const next of outgoing.get(stepKey) ?? []) {
const cycle = visit(next);
if (cycle) return cycle;
}
path.pop();
visiting.delete(stepKey);
visited.add(stepKey);
return null;
}
for (const step of steps) {
const cycle = visit(step.stepKey);
if (cycle) {
return {
ok: false,
summaryKey: "automation.guards.loopDetected",
cycleStepKeys: cycle,
dependencyEdges,
};
}
}
return {
ok: true,
summaryKey: "automation.guards.loopClear",
cycleStepKeys: [],
dependencyEdges,
};
}
export function evaluateTriggerVolume(input: AutomationTriggerVolumeInput): AutomationTriggerVolumeResult {
if (input.countInWindow >= input.hardLimitInWindow) {
return {
action: "pause",
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; typical volume is ${input.typicalDailyMin}-${input.typicalDailyMax} per day. Rule paused for review.`,
};
}
return {
action: "allow",
summaryText: `${input.countInWindow} automation triggers in ${input.windowMinutes} minutes for ${input.triggerKey}; guard within limit.`,
};
}
export function buildAutomationIdempotencyKey(input: { tenantId: string; ruleId: string; triggerKey: string; sourceEventId?: string | null; payloadHash?: string | null }): string {
return [input.tenantId, input.ruleId, input.triggerKey, input.sourceEventId || input.payloadHash || "manual"].join(":");
}
export function planAutomationRetry(input: { attempt: number; maxAttempts?: number; baseDelayMs?: number; now?: Date }): AutomationRetryPlan {
const maxAttempts = input.maxAttempts ?? 3;
const nextAttempt = input.attempt + 1;
if (nextAttempt > maxAttempts) {
return { shouldRetry: false, nextRetryAt: null, nextAttempt, summaryKey: "automation.guards.retryExhausted" };
}
const delayMs = (input.baseDelayMs ?? 60_000) * 2 ** Math.max(input.attempt - 1, 0);
return {
shouldRetry: true,
nextRetryAt: new Date((input.now ?? new Date()).getTime() + delayMs),
nextAttempt,
summaryKey: "automation.guards.retryScheduled",
};
}
export function buildReverseWindowExpiresAt(now = new Date()): Date {
return new Date(now.getTime() + 24 * 60 * 60 * 1000);
}
function trigger(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
return node("trigger", key, group, requiredAnyPermission, "active");
}
@@ -259,7 +373,17 @@ function extension(key: string, group: AutomationNodeGroup, requiredAnyPermissio
return node("action", key, group, requiredAnyPermission, "extension_slot");
}
function node(kind: AutomationNodeKind, key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[], availability: AutomationNodeAvailability): AutomationNodeDefinition {
function flowExtension(key: string, group: AutomationNodeGroup, requiredAnyPermission: readonly string[]): AutomationNodeDefinition {
return node("flow_control", key, group, requiredAnyPermission, "extension_slot");
}
function node(
kind: AutomationNodeKind,
key: string,
group: AutomationNodeGroup,
requiredAnyPermission: readonly string[],
availability: AutomationNodeAvailability
): AutomationNodeDefinition {
const i18nKey = key.replaceAll(".", "_");
return {
key,
@@ -269,6 +393,41 @@ function node(kind: AutomationNodeKind, key: string, group: AutomationNodeGroup,
descriptionKey: `automation.nodes.${i18nKey}.description`,
requiredAnyPermission,
availability,
defaultConfig: {},
defaultConfig: automationNodeDefaultConfig(key),
};
}
function automationNodeDefaultConfig(key: string): Record<string, string | number | boolean> {
if (key === "crm.update_kontakt") return { kontakt: "ausloeser" };
if (key === "crm.add_tag" || key === "crm.remove_tag" || key === "crm.assign_kontakt") return { kontakt: "ausloeser" };
if (key === "lead.assign" || key === "lead.set_status") return { lead: "ausloeser" };
if (key === "lead.convert_to_project") return { lead: "ausloeser", targetPipelineId: "", targetStageId: "" };
if (key === "sales.create_project" || key === "projects.create_project") return { pipelineId: "", stageId: "", titel: "" };
if (key === "sales.change_stage" || key === "projects.change_stage") return { project: "ausloeser", stageId: "" };
if (key === "sales.change_volume") return { project: "ausloeser", volume: "" };
if (key === "sales.assign_project" || key === "projects.add_member") return { project: "ausloeser", userId: "" };
if (key === "sales.add_project_tag") return { project: "ausloeser", tagId: "" };
if (key === "sales.move_pipeline" || key === "projects.move_pipeline") return { project: "ausloeser", pipelineId: "", stageId: "" };
if (key === "projects.create_from_won_sales") return { salesProject: "ausloeser", mappingId: "" };
if (key === "projects.create_task") return { project: "ausloeser", titel: "" };
if (key === "projects.create_appointment") return { project: "ausloeser", titel: "", startsAt: "", endsAt: "" };
if (key === "projects.start_acceptance") return { project: "ausloeser" };
if (key === "crm.create_note") return { datensatz: "kontaktAusAusloeser" };
if (key === "notification.send") return { kanal: "intern", empfaenger: "besitzerDerAutomation" };
if (key === "notification.send_push") return { recipient: "besitzerDerAutomation", title: "", message: "" };
if (key === "chat.post_message") return {};
if (key === "task.create") return { zustaendig: "besitzerDerAutomation", prioritaet: "normal" };
if (key === "task.assign") {
return { aufgabe: "ausVorherigemSchritt", zustaendig: "erstellerDerAufgabe", benachrichtigungAn: "niemand" };
}
if (key === "condition.if_else") return { vergleich: "istGleich" };
if (key === "delay.wait") return { dauer: "2", dauerEinheit: "minuten" };
if (key === "loop.for_each") return { maxDurchlaeufe: "100" };
if (key === "http.request") return { methode: "post" };
if (key === "webhook.send_signed") return { url: "", credentialId: "", body: "" };
if (key === "calendar.create_event") return { connectionId: "", title: "", startsAt: "", endsAt: "" };
if (key === "calendar.update_event") return { connectionId: "", eventId: "", title: "", startsAt: "", endsAt: "" };
if (key === "files.create_from_url") return { url: "", fileName: "" };
if (key === "portal.invite_user") return { kind: "customer" };
return {};
}
@@ -0,0 +1,320 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tx: {
automationExecution: { findFirst: vi.fn(), update: vi.fn(), updateMany: vi.fn() },
task: { updateMany: vi.fn() },
kontakt: { findFirst: vi.fn(), updateMany: vi.fn() },
tag: { findFirst: vi.fn() },
tagAssignment: { deleteMany: vi.fn(), upsert: vi.fn() },
inboxLead: { updateMany: vi.fn() },
activity: { create: vi.fn() },
},
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
import { executeAutomationReverse } from "./automation.server";
describe("automation reverse executor", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tx.task.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.kontakt.findFirst.mockResolvedValue({ id: "k-1" });
mocks.tx.kontakt.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.tag.findFirst.mockResolvedValue({ id: "tag-1" });
mocks.tx.tagAssignment.deleteMany.mockResolvedValue({ count: 1 });
mocks.tx.tagAssignment.upsert.mockResolvedValue({ id: "tag-assignment-1" });
mocks.tx.inboxLead.updateMany.mockResolvedValue({ count: 1 });
mocks.tx.activity.create.mockResolvedValue({ id: "activity-1" });
mocks.tx.automationExecution.update.mockResolvedValue({ id: "execution-1" });
mocks.tx.automationExecution.updateMany.mockResolvedValue({ count: 1 });
});
it("archives a task from the persisted step output and closes the reverse window", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }],
});
await expect(
executeAutomationReverse({
tenantId: "tenant-1",
actorUserId: "user-1",
ruleId: "rule-1",
executionId: "execution-1",
now: new Date("2026-07-11T12:00:00.000Z"),
})
).resolves.toBe(1);
expect(mocks.tx.task.updateMany).toHaveBeenCalledWith({
where: { id: "task-1", tenantId: "tenant-1", archivedAt: null },
data: { archivedAt: new Date("2026-07-11T12:00:00.000Z") },
});
expect(mocks.tx.automationExecution.updateMany).toHaveBeenCalledWith({
where: {
id: "execution-1",
tenantId: "tenant-1",
ruleId: "rule-1",
reverseWindowExpiresAt: { gt: new Date("2026-07-11T12:00:00.000Z") },
},
data: { reverseWindowExpiresAt: null },
});
expect(mocks.tx.activity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ activityType: "automation_reversed", subjectId: "task-1" }) }));
expect(mocks.tx.automationExecution.update).toHaveBeenCalledWith({
where: { id: "execution-1" },
data: { summaryText: "automation.execution.reversed" },
});
});
it("fails closed when a reversible step has no persisted target", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: {} }],
});
await expect(
executeAutomationReverse({
tenantId: "tenant-1",
actorUserId: "user-1",
ruleId: "rule-1",
executionId: "execution-1",
now: new Date("2026-07-11T12:00:00.000Z"),
})
).rejects.toThrow("automation.detail.reverse.missingOutput");
expect(mocks.tx.automationExecution.update).not.toHaveBeenCalled();
});
it("restores a previously unassigned task", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [
{
stepKey: "assign-task",
nodeType: "task.assign",
output: { taskId: "task-1", before: { assignedToUserId: null, assignedToGroupId: null } },
},
],
});
await expect(
executeAutomationReverse({
tenantId: "tenant-1",
actorUserId: "user-1",
ruleId: "rule-1",
executionId: "execution-1",
now: new Date("2026-07-11T12:00:00.000Z"),
})
).resolves.toBe(1);
expect(mocks.tx.task.updateMany).toHaveBeenCalledWith({
where: { id: "task-1", tenantId: "tenant-1", archivedAt: null },
data: { assignedToUserId: null, assignedToGroupId: null },
});
});
it("removes a contact tag that the automation added", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [
{
stepKey: "add-tag",
nodeType: "crm.add_tag",
output: { kontaktId: "k-1", tagId: "tag-1", changed: true, beforeAssigned: false },
},
],
});
await expect(executeAutomationReverse(baseInput)).resolves.toBe(1);
expect(mocks.tx.tagAssignment.deleteMany).toHaveBeenCalledWith({
where: { tenantId: "tenant-1", tagId: "tag-1", entityType: "kontakt", entityId: "k-1" },
});
});
it("restores a contact tag that the automation removed", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [
{
stepKey: "remove-tag",
nodeType: "crm.remove_tag",
output: { kontaktId: "k-1", tagId: "tag-1", changed: true, beforeAssigned: true },
},
],
});
await expect(executeAutomationReverse(baseInput)).resolves.toBe(1);
expect(mocks.tx.kontakt.findFirst).toHaveBeenCalledWith({
where: { id: "k-1", tenantId: "tenant-1", archivedAt: null },
select: { id: true },
});
expect(mocks.tx.tag.findFirst).toHaveBeenCalledWith({ where: { id: "tag-1", tenantId: "tenant-1" }, select: { id: true } });
expect(mocks.tx.tagAssignment.upsert).toHaveBeenCalledWith({
where: { tagId_entityId_entityType: { tagId: "tag-1", entityId: "k-1", entityType: "kontakt" } },
update: {},
create: { tenantId: "tenant-1", tagId: "tag-1", entityType: "kontakt", entityId: "k-1" },
});
});
it("restores the previous contact owner", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [
{
stepKey: "assign-contact",
nodeType: "crm.assign_kontakt",
output: {
kontaktId: "k-1",
assignedToUserId: "user-new",
changed: true,
before: { zustaendigerUserId: null },
},
},
],
});
await expect(executeAutomationReverse(baseInput)).resolves.toBe(1);
expect(mocks.tx.kontakt.updateMany).toHaveBeenCalledWith({
where: { id: "k-1", tenantId: "tenant-1", archivedAt: null },
data: { zustaendigerUserId: null },
});
});
it("fails closed when a changed tag output contradicts its before snapshot", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [
{
stepKey: "add-tag",
nodeType: "crm.add_tag",
output: { kontaktId: "k-1", tagId: "tag-1", changed: true, beforeAssigned: true },
},
],
});
await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.missingOutput");
expect(mocks.tx.tagAssignment.deleteMany).not.toHaveBeenCalled();
});
it("restores the previous lead owner", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [
{
stepKey: "assign-lead",
nodeType: "lead.assign",
output: { leadId: "lead-1", assignedToUserId: "user-new", changed: true, before: { zustaendigerUserId: null } },
},
],
});
await expect(executeAutomationReverse(baseInput)).resolves.toBe(1);
expect(mocks.tx.inboxLead.updateMany).toHaveBeenCalledWith({
where: { id: "lead-1", tenantId: "tenant-1", archivedAt: null },
data: { zustaendigerUserId: null },
});
});
it("restores every field changed by a lead status transition", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [
{
stepKey: "qualify-lead",
nodeType: "lead.set_status",
output: {
leadId: "lead-1",
status: "qualified",
changed: true,
before: {
status: "new",
weiterverarbeitungFreigabe: "unklar",
convertedAt: null,
lostAt: "2026-07-01T10:00:00.000Z",
spamMarkedAt: null,
autoDeleteAt: null,
},
},
},
],
});
await expect(executeAutomationReverse(baseInput)).resolves.toBe(1);
expect(mocks.tx.inboxLead.updateMany).toHaveBeenCalledWith({
where: { id: "lead-1", tenantId: "tenant-1", archivedAt: null },
data: {
status: "new",
weiterverarbeitungFreigabe: "unklar",
convertedAt: null,
lostAt: new Date("2026-07-01T10:00:00.000Z"),
spamMarkedAt: null,
autoDeleteAt: null,
},
});
});
// Fail-closed guard matrix (R-P12b DoD 4 / Audit-Nachzug): notFound,
// expired (both variants), targetUnavailable, nothingReversible, and the
// kontakt before-snapshot guard.
const baseInput = {
tenantId: "tenant-1",
actorUserId: "user-1",
ruleId: "rule-1",
executionId: "execution-1",
now: new Date("2026-07-11T12:00:00.000Z"),
};
it("fails closed when the execution does not exist for this tenant/rule", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue(null);
await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.notFound");
expect(mocks.tx.task.updateMany).not.toHaveBeenCalled();
});
it("fails closed when the 24h window has already expired", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-11T11:00:00.000Z"),
stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }],
});
await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.expired");
expect(mocks.tx.task.updateMany).not.toHaveBeenCalled();
});
it("fails closed when a concurrent reverse already claimed the window (atomic close)", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }],
});
mocks.tx.automationExecution.updateMany.mockResolvedValue({ count: 0 });
await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.expired");
expect(mocks.tx.task.updateMany).not.toHaveBeenCalled();
});
it("fails closed when the reverse target is archived or gone (targetUnavailable)", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [{ stepKey: "create-task", nodeType: "task.create", output: { taskId: "task-1" } }],
});
mocks.tx.task.updateMany.mockResolvedValue({ count: 0 });
await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.targetUnavailable");
expect(mocks.tx.automationExecution.update).not.toHaveBeenCalled();
});
it("fails closed when no step of the run is reversible (nothingReversible)", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [{ stepKey: "notify", nodeType: "notification.send", output: { recipients: [{ email: "a@b.de" }] } }],
});
await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.nothingReversible");
});
it("fails closed when the kontakt before-snapshot carries no allowed fields", async () => {
mocks.tx.automationExecution.findFirst.mockResolvedValue({
reverseWindowExpiresAt: new Date("2026-07-12T12:00:00.000Z"),
stepExecutions: [{ stepKey: "update", nodeType: "crm.update_kontakt", output: { kontaktId: "k-1", before: { notAllowed: "x" } } }],
});
await expect(executeAutomationReverse(baseInput)).rejects.toThrow("automation.detail.reverse.missingOutput");
expect(mocks.tx.kontakt.updateMany).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,110 @@
// R-P12c / R-P12b DoD 4 — manual run path: startAutomationExecutionForRule
// dispatches queued live runs durably to the forward executor (outbox row in
// the same transaction), dedups on the idempotency key and falls back to the
// rule's own trigger key for run-now/retry/resume.
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tx: {
automationRule: { findFirst: vi.fn(), update: vi.fn() },
automationExecution: { findFirst: vi.fn(), create: vi.fn() },
automationTriggerMeter: { upsert: vi.fn(), update: vi.fn() },
outboxEvent: { create: vi.fn(), findUnique: vi.fn() },
},
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
import { startAutomationExecutionForRule } from "./automation.server";
const RULE = {
id: "rule-1",
enabled: true,
status: "active",
triggerKey: "forms.submitted",
steps: [
{ id: "rs-1", stepKey: "trigger", nodeType: "forms.submitted", stepKind: "trigger", parentStepIds: [], sortOrder: 0, summaryText: "t" },
{ id: "rs-2", stepKey: "create-task", nodeType: "task.create", stepKind: "action", parentStepIds: ["trigger"], sortOrder: 1, summaryText: "a" },
],
};
describe("startAutomationExecutionForRule", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tx.automationRule.findFirst.mockResolvedValue(RULE);
mocks.tx.automationExecution.findFirst.mockResolvedValue(null);
mocks.tx.automationExecution.create.mockResolvedValue({ id: "exec-1", status: "queued" });
mocks.tx.automationTriggerMeter.upsert.mockResolvedValue({ count: 1 });
mocks.tx.outboxEvent.create.mockImplementation(async (args: { data: unknown }) => args.data);
});
it("queues a run with the rule's own trigger key and publishes the executor dispatch in the same tx", async () => {
const result = await startAutomationExecutionForRule({
tenantId: "tenant-1",
tenantSlug: "tenant-1",
userId: "user-1",
ruleId: "rule-1",
triggerPayload: { source: "manual" },
sourceEventId: "manual:abc",
});
expect(result).toEqual({ id: "exec-1", status: "queued", deduplicated: false });
expect(mocks.tx.automationExecution.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ triggerKey: "forms.submitted" }) })
);
expect(mocks.tx.outboxEvent.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ eventType: "automation.execution.requested", dispatchKey: "automation-exec:exec-1:initial" }),
})
);
});
it("does not dispatch dry runs or deduplicated runs", async () => {
await startAutomationExecutionForRule({
tenantId: "tenant-1",
tenantSlug: "tenant-1",
userId: "user-1",
ruleId: "rule-1",
triggerPayload: {},
dryRun: true,
});
expect(mocks.tx.outboxEvent.create).not.toHaveBeenCalled();
mocks.tx.automationExecution.findFirst.mockResolvedValue({ id: "exec-0", status: "success" });
const result = await startAutomationExecutionForRule({
tenantId: "tenant-1",
tenantSlug: "tenant-1",
userId: "user-1",
ruleId: "rule-1",
triggerPayload: {},
sourceEventId: "manual:abc",
});
expect(result.deduplicated).toBe(true);
expect(mocks.tx.outboxEvent.create).not.toHaveBeenCalled();
});
it("passes resumeFromStepId through to the new execution", async () => {
await startAutomationExecutionForRule({
tenantId: "tenant-1",
tenantSlug: "tenant-1",
userId: "user-1",
ruleId: "rule-1",
triggerPayload: {},
sourceEventId: "resume:exec-0:xyz",
resumeFromStepId: "rs-2",
});
expect(mocks.tx.automationExecution.create).toHaveBeenCalledWith(
expect.objectContaining({ data: expect.objectContaining({ resumeFromStepId: "rs-2" }) })
);
});
it("fails closed when the rule has no trigger key", async () => {
mocks.tx.automationRule.findFirst.mockResolvedValue({ ...RULE, triggerKey: null });
await expect(
startAutomationExecutionForRule({ tenantId: "tenant-1", tenantSlug: "tenant-1", userId: "user-1", ruleId: "rule-1", triggerPayload: {} })
).rejects.toThrow();
});
});
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff. Show more