Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+70
@@ -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);
|
||||
});
|
||||
});
|
||||
+91
@@ -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));
|
||||
}
|
||||
+5
-1
@@ -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",
|
||||
|
||||
+30
-5
@@ -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);
|
||||
}
|
||||
+78
@@ -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)
|
||||
);
|
||||
});
|
||||
});
|
||||
+172
@@ -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";
|
||||
}
|
||||
}
|
||||
+109
@@ -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 };
|
||||
}
|
||||
+70
@@ -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",
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+154
@@ -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`;
|
||||
}
|
||||
+157
@@ -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,
|
||||
});
|
||||
}
|
||||
+79
@@ -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" });
|
||||
});
|
||||
});
|
||||
+149
@@ -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;
|
||||
}
|
||||
+30
@@ -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"');
|
||||
});
|
||||
});
|
||||
+135
@@ -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();
|
||||
});
|
||||
});
|
||||
+520
@@ -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);
|
||||
}
|
||||
+257
@@ -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[],
|
||||
};
|
||||
}
|
||||
+94
@@ -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" });
|
||||
});
|
||||
});
|
||||
+161
@@ -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;
|
||||
}
|
||||
+140
@@ -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",
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+582
@@ -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("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
||||
}
|
||||
+45
@@ -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));
|
||||
}
|
||||
+315
@@ -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);
|
||||
});
|
||||
});
|
||||
+176
@@ -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";
|
||||
}
|
||||
}
|
||||
+25
@@ -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);
|
||||
});
|
||||
});
|
||||
+393
@@ -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"
|
||||
)
|
||||
: [],
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
+223
@@ -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;
|
||||
}
|
||||
+182
@@ -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]!);
|
||||
});
|
||||
});
|
||||
+292
@@ -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 });
|
||||
}
|
||||
+96
@@ -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 }),
|
||||
});
|
||||
});
|
||||
}
|
||||
+50
@@ -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;
|
||||
}
|
||||
+102
@@ -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 }),
|
||||
});
|
||||
});
|
||||
}
|
||||
+168
@@ -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();
|
||||
});
|
||||
});
|
||||
+125
@@ -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;
|
||||
}
|
||||
+286
@@ -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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
+78
@@ -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" });
|
||||
});
|
||||
});
|
||||
+151
@@ -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;
|
||||
}
|
||||
+85
@@ -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();
|
||||
});
|
||||
});
|
||||
+69
@@ -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);
|
||||
}
|
||||
}
|
||||
+86
@@ -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",
|
||||
},
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+274
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
+96
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
+159
@@ -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;
|
||||
}
|
||||
+236
-14
@@ -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"));
|
||||
});
|
||||
});
|
||||
+148
-32
@@ -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 },
|
||||
|
||||
+58
@@ -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" }]);
|
||||
});
|
||||
});
|
||||
+122
@@ -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));
|
||||
}
|
||||
+232
@@ -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 };
|
||||
}
|
||||
+265
@@ -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;
|
||||
}
|
||||
+98
@@ -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),
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
+130
@@ -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,
|
||||
};
|
||||
}
|
||||
+156
@@ -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) }),
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+170
@@ -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();
|
||||
}
|
||||
}
|
||||
+95
@@ -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();
|
||||
});
|
||||
});
|
||||
+106
@@ -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;
|
||||
}
|
||||
+103
-2
@@ -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();
|
||||
});
|
||||
});
|
||||
+149
-19
@@ -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) {
|
||||
|
||||
+9
@@ -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
|
||||
|
||||
+9
@@ -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({
|
||||
|
||||
+72
@@ -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 });
|
||||
});
|
||||
});
|
||||
+159
@@ -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"]);
|
||||
}
|
||||
+191
@@ -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);
|
||||
});
|
||||
});
|
||||
+298
@@ -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);
|
||||
}
|
||||
+112
@@ -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" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+231
@@ -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 };
|
||||
}
|
||||
Reference in new issue
Block a user