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
+47
@@ -0,0 +1,47 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
requireAuth: vi.fn(),
|
||||
getTenantId: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
getTenantMember: vi.fn(),
|
||||
getPermissions: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...args: unknown[]) => mocks.requireAuth(...args) }));
|
||||
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantId(...args) }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenantMember: (...args: unknown[]) => mocks.getTenantMember(...args) }));
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
getPermissionsByUser: (...args: unknown[]) => mocks.getPermissions(...args),
|
||||
}));
|
||||
|
||||
import { requirePortalAdminWorkspaceContext } from "./portal-admin-context.server";
|
||||
|
||||
const request = new Request("https://app.example.test/acme/settings/customer-portal");
|
||||
const params = { tenant: "acme" };
|
||||
|
||||
describe("portal admin context", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.getTenantId.mockResolvedValue("tenant_1");
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
|
||||
mocks.getTenantMember.mockResolvedValue({ id: "member_1" });
|
||||
mocks.getPermissions.mockResolvedValue(["portal.admin"]);
|
||||
});
|
||||
|
||||
it("returns the permitted workspace", async () => {
|
||||
await expect(requirePortalAdminWorkspaceContext(request, params, "portal.admin")).resolves.toEqual({
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
permissions: ["portal.admin"],
|
||||
tenantSlug: "acme",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns 404 before portal data access when workspace membership is missing", async () => {
|
||||
mocks.getTenantMember.mockResolvedValue(null);
|
||||
|
||||
await expect(requirePortalAdminWorkspaceContext(request, params, "portal.admin")).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import { CatalogError, requirePermission } from "@hivegrid/foundation";
|
||||
|
||||
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { requireAuth } from "~/utils/loaders.middleware";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
|
||||
export type PortalAdminWorkspaceContext = {
|
||||
readonly tenantId: string;
|
||||
readonly userId: string;
|
||||
readonly permissions: readonly string[];
|
||||
readonly tenantSlug: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolves the authenticated workspace principal and intentionally translates
|
||||
* membership failures into 404 to avoid tenant disclosure.
|
||||
*/
|
||||
export async function requirePortalAdminWorkspaceMembership(
|
||||
request: Request,
|
||||
params: Record<string, string | undefined>
|
||||
): Promise<PortalAdminWorkspaceContext> {
|
||||
await requireAuth({ request, params });
|
||||
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
|
||||
const tenantSlug = params.tenant?.trim() ?? "";
|
||||
if (!tenantId || !userInfo.userId || !tenantSlug) throw new Response(null, { status: 404 });
|
||||
const [member, permissions] = await Promise.all([getTenantMember(userInfo.userId, tenantId), getPermissionsByUser(userInfo.userId, tenantId)]);
|
||||
if (!member) throw new Response(null, { status: 404 });
|
||||
return { tenantId, userId: userInfo.userId, permissions, tenantSlug };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies one narrow portal permission to an already verified membership.
|
||||
* Keeping this separate lets multi-intent actions resolve their required
|
||||
* custom-role permission before CSRF or payload validation can disclose data.
|
||||
*/
|
||||
export function requirePortalAdminWorkspacePermission(context: PortalAdminWorkspaceContext, permission: string): PortalAdminWorkspaceContext {
|
||||
try {
|
||||
requirePermission(context, permission);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) throw new Response(null, { status: 404 });
|
||||
throw error;
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
/** Resolves membership and applies one narrow portal permission. */
|
||||
export async function requirePortalAdminWorkspaceContext(
|
||||
request: Request,
|
||||
params: Record<string, string | undefined>,
|
||||
permission: string
|
||||
): Promise<PortalAdminWorkspaceContext> {
|
||||
const context = await requirePortalAdminWorkspaceMembership(request, params);
|
||||
return requirePortalAdminWorkspacePermission(context, permission);
|
||||
}
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
billingState: vi.fn(),
|
||||
commercialEligibility: vi.fn(),
|
||||
acquireBillingLocks: vi.fn(),
|
||||
publishAudit: vi.fn(),
|
||||
publishOutbox: vi.fn(),
|
||||
logActivity: vi.fn(),
|
||||
brandingPreviewHref: vi.fn(),
|
||||
brandingStorageKey: vi.fn(),
|
||||
removeBrandingLogo: vi.fn(),
|
||||
storeBrandingLogo: vi.fn(),
|
||||
tx: {
|
||||
portal: { findFirst: vi.fn(), update: vi.fn() },
|
||||
portalConfiguration: { upsert: vi.fn() },
|
||||
portalUser: { findFirst: vi.fn(), findUnique: vi.fn(), create: vi.fn(), update: vi.fn() },
|
||||
portalSession: { updateMany: vi.fn() },
|
||||
portalToken: { updateMany: vi.fn() },
|
||||
portalProjectAccess: { upsert: vi.fn(), updateMany: vi.fn() },
|
||||
portalSubcontractorAccess: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn(), updateMany: vi.fn() },
|
||||
portalServiceInboxItem: { updateMany: vi.fn() },
|
||||
pipelineStage: { findMany: vi.fn() },
|
||||
projekt: { findFirst: vi.fn(), findMany: vi.fn() },
|
||||
user: { findMany: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/billingStatusService", () => ({
|
||||
getTenantBillingReadOnlyState: (...args: unknown[]) => mocks.billingState(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/portal-domain-billing-fence.server", () => ({
|
||||
acquirePortalDomainBillingActivationLocks: (...args: unknown[]) => mocks.acquireBillingLocks(...args),
|
||||
}));
|
||||
vi.mock("./portal-domain-commercial.server", () => ({
|
||||
getCustomerPortalCommercialEligibilityWithClient: (...args: unknown[]) => mocks.commercialEligibility(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAudit(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/outbox", () => ({
|
||||
publishOutboxEvent: (...args: unknown[]) => mocks.publishOutbox(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/activity", () => ({
|
||||
logActivity: (...args: unknown[]) => mocks.logActivity(...args),
|
||||
}));
|
||||
vi.mock("./portal-branding.server", () => ({
|
||||
portalBrandingLogoPreviewHref: (...args: unknown[]) => mocks.brandingPreviewHref(...args),
|
||||
portalBrandingLogoStorageKey: (...args: unknown[]) => mocks.brandingStorageKey(...args),
|
||||
removePortalBrandingLogo: (...args: unknown[]) => mocks.removeBrandingLogo(...args),
|
||||
storePortalBrandingLogo: (...args: unknown[]) => mocks.storeBrandingLogo(...args),
|
||||
}));
|
||||
|
||||
import {
|
||||
disablePortalUser,
|
||||
loadPortalAdminSnapshot,
|
||||
PortalAdminError,
|
||||
savePortalBranding,
|
||||
savePortalConfiguration,
|
||||
setPortalProjectAccess,
|
||||
updatePortalInbox,
|
||||
} from "./portal-admin.server";
|
||||
|
||||
describe("customer portal tenant administration", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.billingState.mockResolvedValue({ readOnly: false, status: "active" });
|
||||
mocks.commercialEligibility.mockResolvedValue({ portalAllowed: true });
|
||||
mocks.acquireBillingLocks.mockResolvedValue(undefined);
|
||||
mocks.tx.portal.findFirst.mockResolvedValue({ id: "portal_1" });
|
||||
mocks.tx.portal.update.mockResolvedValue({ id: "portal_1" });
|
||||
mocks.tx.portalConfiguration.upsert.mockResolvedValue({ id: "config_1" });
|
||||
mocks.tx.portalSession.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.portalToken.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.portalProjectAccess.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.portalSubcontractorAccess.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.portalServiceInboxItem.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.projekt.findMany.mockResolvedValue([]);
|
||||
mocks.tx.user.findMany.mockResolvedValue([]);
|
||||
mocks.tx.pipelineStage.findMany.mockResolvedValue([]);
|
||||
mocks.brandingPreviewHref.mockReturnValue("https://portal.example.test/demo-pro-crm/branding/logo");
|
||||
mocks.brandingStorageKey.mockReturnValue("tenants/tenant_1/portal/branding/logo");
|
||||
mocks.removeBrandingLogo.mockResolvedValue(undefined);
|
||||
mocks.storeBrandingLogo.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("exposes only a configured flag and absolute proxy preview URL in the admin snapshot", async () => {
|
||||
mocks.tx.portal.findFirst.mockResolvedValue({
|
||||
id: "portal_1",
|
||||
isPublished: true,
|
||||
brandingLogo: "tenants/tenant_1/portal/branding/logo",
|
||||
configuration: null,
|
||||
stageVisibilities: [],
|
||||
documentAutoReleaseRules: [],
|
||||
users: [],
|
||||
projectAccesses: [],
|
||||
serviceInboxItems: [],
|
||||
});
|
||||
|
||||
const snapshot = await loadPortalAdminSnapshot({ tenantId: "tenant_1", tenantSlug: "demo-pro-crm" });
|
||||
|
||||
expect(snapshot.configuration).toMatchObject({
|
||||
brandingLogoConfigured: true,
|
||||
brandingLogoPreviewHref: "https://portal.example.test/demo-pro-crm/branding/logo",
|
||||
});
|
||||
expect(mocks.brandingPreviewHref).toHaveBeenCalledWith("demo-pro-crm");
|
||||
expect(JSON.stringify(snapshot)).not.toContain("tenants/tenant_1/portal/branding/logo");
|
||||
});
|
||||
|
||||
it("allows an incomplete draft but enforces legal links and project type before publishing", async () => {
|
||||
await savePortalConfiguration({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
lifecycleMode: "customer",
|
||||
projectAutoCloseMonths: 12,
|
||||
inactivityDisableMonths: 24,
|
||||
enabledProjectTypes: [],
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
|
||||
statusEmailsEnabled: true,
|
||||
imprintUrl: null,
|
||||
privacyUrl: null,
|
||||
publish: false,
|
||||
});
|
||||
|
||||
expect(mocks.tx.portalConfiguration.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({ imprintUrl: null, privacyUrl: null, enabledProjectTypes: [] }),
|
||||
}),
|
||||
);
|
||||
expect(mocks.tx.portal.update).toHaveBeenCalledWith({ where: { id: "portal_1" }, data: { isPublished: false } });
|
||||
expect(mocks.publishAudit).toHaveBeenCalledOnce();
|
||||
expect(mocks.logActivity).toHaveBeenCalledOnce();
|
||||
|
||||
await expect(
|
||||
savePortalConfiguration({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
lifecycleMode: "customer",
|
||||
projectAutoCloseMonths: 12,
|
||||
inactivityDisableMonths: 24,
|
||||
enabledProjectTypes: [],
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
|
||||
statusEmailsEnabled: true,
|
||||
imprintUrl: "https://example.test/imprint",
|
||||
privacyUrl: "https://example.test/privacy",
|
||||
publish: true,
|
||||
}),
|
||||
).rejects.toMatchObject<Partial<PortalAdminError>>({ status: 409, messageKey: "customerPortal.admin.errors.activationGate" });
|
||||
});
|
||||
|
||||
it("blocks every mutation before opening a tenant transaction while billing is frozen", async () => {
|
||||
mocks.billingState.mockResolvedValue({ readOnly: true, status: "frozen" });
|
||||
|
||||
await expect(
|
||||
disablePortalUser({ tenantId: "tenant_1", actorUserId: "user_1", portalUserId: "portal_user_1" }),
|
||||
).rejects.toMatchObject<Partial<PortalAdminError>>({ status: 423, messageKey: "customerPortal.states.frozen.body" });
|
||||
expect(mocks.tx.portalUser.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a live commercial entitlement before publishing but still allows an unpublished draft", async () => {
|
||||
mocks.commercialEligibility.mockResolvedValue({ portalAllowed: false });
|
||||
|
||||
await expect(
|
||||
savePortalConfiguration({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
lifecycleMode: "customer",
|
||||
projectAutoCloseMonths: 12,
|
||||
inactivityDisableMonths: 24,
|
||||
enabledProjectTypes: ["renovation"],
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
|
||||
statusEmailsEnabled: true,
|
||||
imprintUrl: "https://example.test/imprint",
|
||||
privacyUrl: "https://example.test/privacy",
|
||||
publish: true,
|
||||
}),
|
||||
).rejects.toMatchObject<Partial<PortalAdminError>>({
|
||||
status: 409,
|
||||
messageKey: "customerPortal.domain.errors.entitlementRequired",
|
||||
});
|
||||
expect(mocks.acquireBillingLocks).toHaveBeenCalledWith(mocks.tx, { tenantId: "tenant_1" });
|
||||
expect(mocks.tx.portalConfiguration.upsert).not.toHaveBeenCalled();
|
||||
|
||||
await expect(
|
||||
savePortalConfiguration({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
lifecycleMode: "customer",
|
||||
projectAutoCloseMonths: 12,
|
||||
inactivityDisableMonths: 24,
|
||||
enabledProjectTypes: [],
|
||||
uploadMaxFiles: 10,
|
||||
uploadMaxFileSizeBytes: 50 * 1024 * 1024,
|
||||
statusEmailsEnabled: true,
|
||||
publish: false,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("stores a scanned tenant logo, persists only its deterministic key, and redacts audit metadata", async () => {
|
||||
const logo = {
|
||||
content: "data:image/png;base64,secret-image-bytes",
|
||||
declaredMimeType: "image/png",
|
||||
filename: "secret-customer-name.png",
|
||||
};
|
||||
|
||||
await savePortalBranding({ tenantId: "tenant_1", actorUserId: "user_1", logo });
|
||||
|
||||
expect(mocks.storeBrandingLogo).toHaveBeenCalledWith({ tenantId: "tenant_1", upload: logo });
|
||||
expect(mocks.tx.portal.update).toHaveBeenCalledWith({
|
||||
where: { id: "portal_1" },
|
||||
data: { brandingLogo: "tenants/tenant_1/portal/branding/logo" },
|
||||
});
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({
|
||||
action: "customer_portal.branding.updated",
|
||||
targetType: "Portal",
|
||||
targetId: "portal_1",
|
||||
metadata: { configured: true },
|
||||
}),
|
||||
);
|
||||
expect(mocks.logActivity).toHaveBeenCalledOnce();
|
||||
const emittedPayload = JSON.stringify([mocks.publishAudit.mock.calls, mocks.logActivity.mock.calls]);
|
||||
expect(emittedPayload).not.toContain("secret-image-bytes");
|
||||
expect(emittedPayload).not.toContain("secret-customer-name.png");
|
||||
});
|
||||
|
||||
it("deletes the private object before clearing the marker and audits removal", async () => {
|
||||
await savePortalBranding({ tenantId: "tenant_1", actorUserId: "user_1", logo: null });
|
||||
|
||||
expect(mocks.removeBrandingLogo).toHaveBeenCalledWith("tenant_1");
|
||||
expect(mocks.tx.portal.update).toHaveBeenCalledWith({ where: { id: "portal_1" }, data: { brandingLogo: null } });
|
||||
expect(mocks.removeBrandingLogo.mock.invocationCallOrder[0]).toBeLessThan(mocks.tx.portal.update.mock.invocationCallOrder[0] ?? 0);
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({ action: "customer_portal.branding.removed", metadata: { configured: false } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("deletes a newly uploaded object if the tenant transaction cannot commit", async () => {
|
||||
mocks.tx.portal.update.mockRejectedValueOnce(new Error("database unavailable"));
|
||||
|
||||
await expect(
|
||||
savePortalBranding({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
logo: { content: "data:image/webp;base64,AAAA", declaredMimeType: "image/webp", filename: "logo.webp" },
|
||||
}),
|
||||
).rejects.toThrow("database unavailable");
|
||||
expect(mocks.removeBrandingLogo).toHaveBeenCalledWith("tenant_1");
|
||||
});
|
||||
|
||||
it("persists the subcontractor project, stage and document matrix and emits a canonical workflow trigger", async () => {
|
||||
mocks.tx.portalUser.findFirst.mockResolvedValue({ id: "portal_user_1", kind: "subcontractor" });
|
||||
mocks.tx.projekt.findFirst.mockResolvedValue({ id: "project_1" });
|
||||
mocks.tx.pipelineStage.findMany.mockResolvedValue([{ id: "stage_1" }, { id: "stage_2" }]);
|
||||
mocks.tx.portalProjectAccess.upsert.mockResolvedValue({ id: "access_1", updatedAt: new Date("2026-07-16T12:00:00.000Z") });
|
||||
mocks.tx.portalSubcontractorAccess.findFirst.mockResolvedValue(null);
|
||||
mocks.tx.portalSubcontractorAccess.create.mockResolvedValue({ id: "sub_access_1" });
|
||||
|
||||
await setPortalProjectAccess({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
portalUserId: "portal_user_1",
|
||||
projectId: "project_1",
|
||||
active: true,
|
||||
canUpload: false,
|
||||
validUntil: new Date("2026-12-31T23:59:59.999Z"),
|
||||
companyName: "Montage GmbH",
|
||||
roleLabel: "Elektrik",
|
||||
visibleStageIds: ["stage_1", "stage_2", "stage_1"],
|
||||
visibleDocumentTypes: ["plan", "invoice", "plan"],
|
||||
canSeeOtherSubcontractors: false,
|
||||
});
|
||||
|
||||
expect(mocks.tx.portalSubcontractorAccess.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
portalId: "portal_1",
|
||||
portalUserId: "portal_user_1",
|
||||
projectId: "project_1",
|
||||
projectAccessId: "access_1",
|
||||
companyName: "Montage GmbH",
|
||||
roleLabel: "Elektrik",
|
||||
visibleStageIds: ["stage_1", "stage_2"],
|
||||
visibleDocumentTypes: ["plan", "invoice"],
|
||||
canUpload: false,
|
||||
}),
|
||||
});
|
||||
expect(mocks.publishOutbox).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({
|
||||
type: "workflow.trigger.event",
|
||||
payload: expect.objectContaining({ event: "portal.access_granted" }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("revokes sessions, tokens and both access layers when disabling a portal user", async () => {
|
||||
mocks.tx.portalUser.findFirst.mockResolvedValue({ id: "portal_user_1" });
|
||||
mocks.tx.portalUser.update.mockResolvedValue({ id: "portal_user_1" });
|
||||
|
||||
await disablePortalUser({ tenantId: "tenant_1", actorUserId: "user_1", portalUserId: "portal_user_1" });
|
||||
|
||||
expect(mocks.tx.portalSession.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalToken.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalProjectAccess.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalSubcontractorAccess.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.publishOutbox).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({ type: "workflow.trigger.event", payload: expect.objectContaining({ event: "portal.lifecycle_changed" }) }),
|
||||
);
|
||||
});
|
||||
|
||||
it("updates inbox state, audit and activity in the same tenant transaction", async () => {
|
||||
await updatePortalInbox({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
itemId: "inbox_1",
|
||||
status: "resolved",
|
||||
});
|
||||
|
||||
expect(mocks.tx.portalServiceInboxItem.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({ action: "customer_portal.inbox.updated", targetId: "inbox_1" }),
|
||||
);
|
||||
expect(mocks.logActivity).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
+688
@@ -0,0 +1,688 @@
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import {
|
||||
acquirePortalDomainBillingActivationLocks,
|
||||
type PortalDomainBillingActivationLockClient,
|
||||
} from "@hivegrid/db/portal-domain-billing-fence.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import type {
|
||||
PortalAdminAccessRowVM,
|
||||
PortalAdminUserRowVM,
|
||||
PortalConfigurationSummaryVM,
|
||||
PortalInboxItemVM,
|
||||
PortalStageConfigurationRowVM,
|
||||
PortalAutoReleaseRuleRowVM,
|
||||
PortalAdminProjectOptionVM,
|
||||
} from "@hivegrid/view-models";
|
||||
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
|
||||
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
|
||||
import {
|
||||
getCustomerPortalCommercialEligibilityWithClient,
|
||||
type CommercialReadClient,
|
||||
} from "./portal-domain-commercial.server";
|
||||
import {
|
||||
portalBrandingLogoPreviewHref,
|
||||
portalBrandingLogoStorageKey,
|
||||
removePortalBrandingLogo,
|
||||
storePortalBrandingLogo,
|
||||
type PortalBrandingLogoUpload,
|
||||
} from "./portal-branding.server";
|
||||
import { updatePortalServiceInboxItemWithClient, type PortalInboxClient, type PortalServiceInboxStatus } from "./portal-service-inbox.server";
|
||||
import { invitePortalUserFromAdmin, PortalInvitationError, resendPortalUserInvitation as resendPortalInvitation } from "./portal-invitation.server";
|
||||
|
||||
const MAX_UPLOAD_BYTES = 100 * 1024 * 1024;
|
||||
|
||||
export class PortalAdminError extends Error {
|
||||
override readonly name = "PortalAdminError";
|
||||
|
||||
constructor(
|
||||
readonly messageKey: string,
|
||||
readonly status: 400 | 404 | 409 | 423 = 400
|
||||
) {
|
||||
super(messageKey);
|
||||
}
|
||||
}
|
||||
|
||||
export type PortalAdminSnapshot = {
|
||||
readonly frozen: boolean;
|
||||
readonly portalId: string;
|
||||
readonly published: boolean;
|
||||
readonly configuration: PortalConfigurationSummaryVM;
|
||||
readonly users: readonly PortalAdminUserRowVM[];
|
||||
readonly accessRows: readonly PortalAdminAccessRowVM[];
|
||||
readonly inbox: readonly PortalInboxItemVM[];
|
||||
readonly stages: readonly PortalStageConfigurationRowVM[];
|
||||
readonly autoReleaseRules: readonly PortalAutoReleaseRuleRowVM[];
|
||||
readonly projectOptions: readonly PortalAdminProjectOptionVM[];
|
||||
};
|
||||
|
||||
export async function loadPortalAdminSnapshot(input: { readonly tenantId: string; readonly tenantSlug: string }): Promise<PortalAdminSnapshot> {
|
||||
const [snapshot, billing] = await Promise.all([
|
||||
withTenantRLS(input.tenantId, async (tx) => {
|
||||
const portal = await tx.portal.findFirst({
|
||||
where: { tenantId: input.tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
isPublished: true,
|
||||
brandingLogo: true,
|
||||
configuration: true,
|
||||
stageVisibilities: { select: { id: true, stageId: true, visible: true, customerLabel: true, stage: { select: { name: true } } } },
|
||||
documentAutoReleaseRules: { select: { id: true, projectType: true, documentType: true, enabled: true } },
|
||||
users: {
|
||||
where: { archivedAt: null },
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
status: true,
|
||||
lastActivityAt: true,
|
||||
projectAccesses: { where: { active: true, revokedAt: null }, select: { id: true } },
|
||||
},
|
||||
},
|
||||
projectAccesses: {
|
||||
select: {
|
||||
id: true,
|
||||
portalUserId: true,
|
||||
active: true,
|
||||
revokedAt: true,
|
||||
portalUser: { select: { firstName: true, lastName: true, email: true, kind: true } },
|
||||
project: { select: { id: true, projektname: true, projektNummer: true } },
|
||||
subcontractorAccess: {
|
||||
select: {
|
||||
companyName: true,
|
||||
roleLabel: true,
|
||||
visibleStageIds: true,
|
||||
visibleDocumentTypes: true,
|
||||
canSeeOtherSubcontractors: true,
|
||||
canUpload: true,
|
||||
validUntil: true,
|
||||
active: true,
|
||||
revokedAt: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
serviceInboxItems: {
|
||||
where: { expiresAt: { gt: new Date() } },
|
||||
orderBy: [{ priority: "desc" }, { lastOccurredAt: "desc" }],
|
||||
take: 250,
|
||||
select: {
|
||||
id: true,
|
||||
kind: true,
|
||||
status: true,
|
||||
priority: true,
|
||||
titleKey: true,
|
||||
projectId: true,
|
||||
portalUser: { select: { firstName: true, lastName: true, email: true } },
|
||||
bundledCount: true,
|
||||
lastOccurredAt: true,
|
||||
expiresAt: true,
|
||||
ownerUserId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!portal) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
const ownerIds = portal.serviceInboxItems.flatMap((item) => (item.ownerUserId ? [item.ownerUserId] : []));
|
||||
const [projects, owners, stages] = await Promise.all([
|
||||
tx.projekt.findMany({
|
||||
where: { tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true, projektname: true, projektNummer: true, projekttyp: true },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
take: 500,
|
||||
}),
|
||||
ownerIds.length ? tx.user.findMany({ where: { id: { in: ownerIds } }, select: { id: true, firstName: true, lastName: true, email: true } }) : [],
|
||||
tx.pipelineStage.findMany({
|
||||
where: { tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true, name: true },
|
||||
orderBy: [{ position: "asc" }, { name: "asc" }],
|
||||
}),
|
||||
]);
|
||||
const projectById = new Map(projects.map((project) => [project.id, `${project.projektNummer} · ${project.projektname}`]));
|
||||
const ownerById = new Map(owners.map((owner) => [owner.id, personLabel(owner)]));
|
||||
const visibilityByStageId = new Map(portal.stageVisibilities.map((visibility) => [visibility.stageId, visibility]));
|
||||
const configuration = portal.configuration;
|
||||
const brandingLogoConfigured = Boolean(portal.brandingLogo?.trim());
|
||||
return {
|
||||
portalId: portal.id,
|
||||
published: portal.isPublished,
|
||||
configuration: {
|
||||
published: portal.isPublished,
|
||||
lifecycleMode: configuration?.lifecycleMode ?? "customer",
|
||||
projectAutoCloseMonths: configuration?.projectAutoCloseMonths ?? 12,
|
||||
inactivityDisableMonths: configuration?.inactivityDisableMonths ?? 24,
|
||||
uploadMaxFiles: configuration?.uploadMaxFiles ?? 10,
|
||||
uploadMaxFileSizeBytes: configuration?.uploadMaxFileSizeBytes ?? 50 * 1024 * 1024,
|
||||
enabledProjectTypes: configuration?.enabledProjectTypes ?? [],
|
||||
statusEmailsEnabled: configuration?.statusEmailsEnabled ?? true,
|
||||
imprintUrl: configuration?.imprintUrl ?? null,
|
||||
privacyUrl: configuration?.privacyUrl ?? null,
|
||||
termsUrl: configuration?.termsUrl ?? null,
|
||||
legalLinksComplete: Boolean(configuration?.imprintUrl && configuration.privacyUrl),
|
||||
visibleStageCount: portal.stageVisibilities.filter((visibility) => visibility.visible).length,
|
||||
autoReleaseRuleCount: portal.documentAutoReleaseRules.filter((rule) => rule.enabled).length,
|
||||
emailTemplateHref: `/${encodeURIComponent(input.tenantSlug)}/settings/customer-portal/email-templates`,
|
||||
brandingLogoConfigured,
|
||||
brandingLogoPreviewHref: brandingLogoConfigured ? portalBrandingLogoPreviewHref(input.tenantSlug) : null,
|
||||
} satisfies PortalConfigurationSummaryVM,
|
||||
stages: stages.map((stage) => {
|
||||
const visibility = visibilityByStageId.get(stage.id);
|
||||
return {
|
||||
stageId: stage.id,
|
||||
stageLabel: stage.name,
|
||||
visible: visibility?.visible ?? false,
|
||||
customerLabel: visibility?.customerLabel ?? null,
|
||||
} satisfies PortalStageConfigurationRowVM;
|
||||
}),
|
||||
autoReleaseRules: portal.documentAutoReleaseRules.map((rule) => ({ ...rule }) satisfies PortalAutoReleaseRuleRowVM),
|
||||
projectOptions: projects.map(
|
||||
(project) =>
|
||||
({
|
||||
id: project.id,
|
||||
label: `${project.projektNummer} · ${project.projektname}`,
|
||||
projectType: project.projekttyp,
|
||||
}) satisfies PortalAdminProjectOptionVM
|
||||
),
|
||||
users: portal.users.map(
|
||||
(user) =>
|
||||
({
|
||||
id: user.id,
|
||||
kind: user.kind,
|
||||
name: personLabel(user),
|
||||
email: user.email,
|
||||
status: user.status,
|
||||
canResendInvitation: user.status === "invited",
|
||||
projectCount: user.projectAccesses.length,
|
||||
lastActivityAt: user.lastActivityAt?.toISOString() ?? null,
|
||||
}) satisfies PortalAdminUserRowVM
|
||||
),
|
||||
accessRows: portal.projectAccesses.map(
|
||||
(access) =>
|
||||
({
|
||||
id: access.id,
|
||||
portalUserId: access.portalUserId,
|
||||
portalUserLabel: personLabel(access.portalUser),
|
||||
viewerKind: access.portalUser.kind,
|
||||
projectId: access.project.id,
|
||||
projectLabel: `${access.project.projektNummer} · ${access.project.projektname}`,
|
||||
active:
|
||||
access.active &&
|
||||
!access.revokedAt &&
|
||||
(access.portalUser.kind === "customer" || Boolean(access.subcontractorAccess?.active && !access.subcontractorAccess.revokedAt)),
|
||||
canUpload: access.portalUser.kind === "customer" || access.subcontractorAccess?.canUpload === true,
|
||||
validUntil: access.subcontractorAccess?.validUntil?.toISOString() ?? null,
|
||||
companyName: access.subcontractorAccess?.companyName ?? null,
|
||||
roleLabel: access.subcontractorAccess?.roleLabel ?? null,
|
||||
visibleStageIds: access.subcontractorAccess?.visibleStageIds ?? [],
|
||||
visibleDocumentTypes: access.subcontractorAccess?.visibleDocumentTypes ?? [],
|
||||
canSeeOtherSubcontractors: access.subcontractorAccess?.canSeeOtherSubcontractors ?? false,
|
||||
}) satisfies PortalAdminAccessRowVM
|
||||
),
|
||||
inbox: portal.serviceInboxItems.map(
|
||||
(item) =>
|
||||
({
|
||||
id: item.id,
|
||||
kind: item.kind,
|
||||
status: item.status,
|
||||
priority: item.priority,
|
||||
titleKey: item.titleKey,
|
||||
portalUserLabel: personLabel(item.portalUser),
|
||||
projectLabel: item.projectId ? (projectById.get(item.projectId) ?? null) : null,
|
||||
bundledCount: item.bundledCount,
|
||||
occurredAt: item.lastOccurredAt.toISOString(),
|
||||
expiresAt: item.expiresAt.toISOString(),
|
||||
ownerLabel: item.ownerUserId ? (ownerById.get(item.ownerUserId) ?? null) : null,
|
||||
}) satisfies PortalInboxItemVM
|
||||
),
|
||||
};
|
||||
}),
|
||||
getTenantBillingReadOnlyState(input.tenantId),
|
||||
]);
|
||||
return { ...snapshot, frozen: billing.readOnly };
|
||||
}
|
||||
|
||||
export async function savePortalConfiguration(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly lifecycleMode: "customer" | "project";
|
||||
readonly projectAutoCloseMonths: number;
|
||||
readonly inactivityDisableMonths: number;
|
||||
readonly enabledProjectTypes: readonly string[];
|
||||
readonly uploadMaxFiles: number;
|
||||
readonly uploadMaxFileSizeBytes: number;
|
||||
readonly statusEmailsEnabled: boolean;
|
||||
readonly imprintUrl?: string | null;
|
||||
readonly privacyUrl?: string | null;
|
||||
readonly termsUrl?: string | null;
|
||||
readonly publish: boolean;
|
||||
}): Promise<void> {
|
||||
await assertPortalAdminWritable(input.tenantId);
|
||||
if (!Number.isInteger(input.projectAutoCloseMonths) || input.projectAutoCloseMonths < 1 || input.projectAutoCloseMonths > 120) throw invalid();
|
||||
if (!Number.isInteger(input.inactivityDisableMonths) || input.inactivityDisableMonths < 1 || input.inactivityDisableMonths > 120) throw invalid();
|
||||
if (!Number.isInteger(input.uploadMaxFiles) || input.uploadMaxFiles < 1 || input.uploadMaxFiles > 10) throw invalid();
|
||||
if (!Number.isInteger(input.uploadMaxFileSizeBytes) || input.uploadMaxFileSizeBytes < 1 || input.uploadMaxFileSizeBytes > MAX_UPLOAD_BYTES) throw invalid();
|
||||
const enabledProjectTypes = [...new Set(input.enabledProjectTypes.map(normalizeToken).filter(Boolean))];
|
||||
const imprintUrl = normalizeOptionalLegalUrl(input.imprintUrl);
|
||||
const privacyUrl = normalizeOptionalLegalUrl(input.privacyUrl);
|
||||
const termsUrl = normalizeOptionalLegalUrl(input.termsUrl);
|
||||
if (input.publish && (!imprintUrl || !privacyUrl || enabledProjectTypes.length === 0)) {
|
||||
throw new PortalAdminError("customerPortal.admin.errors.activationGate", 409);
|
||||
}
|
||||
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const portal = await tx.portal.findFirst({ where: { tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!portal) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
if (input.publish) {
|
||||
await acquirePortalDomainBillingActivationLocks(tx as unknown as PortalDomainBillingActivationLockClient, {
|
||||
tenantId: input.tenantId,
|
||||
});
|
||||
const commercial = await getCustomerPortalCommercialEligibilityWithClient(
|
||||
tx as unknown as CommercialReadClient,
|
||||
{ tenantId: input.tenantId },
|
||||
);
|
||||
if (!commercial.portalAllowed) {
|
||||
throw new PortalAdminError("customerPortal.domain.errors.entitlementRequired", 409);
|
||||
}
|
||||
}
|
||||
await tx.portalConfiguration.upsert({
|
||||
where: { portalId_tenantId: { portalId: portal.id, tenantId: input.tenantId } },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
portalId: portal.id,
|
||||
lifecycleMode: input.lifecycleMode,
|
||||
projectAutoCloseMonths: input.projectAutoCloseMonths,
|
||||
inactivityDisableMonths: input.inactivityDisableMonths,
|
||||
enabledProjectTypes,
|
||||
uploadMaxFiles: input.uploadMaxFiles,
|
||||
uploadMaxFileSizeBytes: input.uploadMaxFileSizeBytes,
|
||||
statusEmailsEnabled: input.statusEmailsEnabled,
|
||||
imprintUrl,
|
||||
privacyUrl,
|
||||
termsUrl,
|
||||
},
|
||||
update: {
|
||||
lifecycleMode: input.lifecycleMode,
|
||||
projectAutoCloseMonths: input.projectAutoCloseMonths,
|
||||
inactivityDisableMonths: input.inactivityDisableMonths,
|
||||
enabledProjectTypes,
|
||||
uploadMaxFiles: input.uploadMaxFiles,
|
||||
uploadMaxFileSizeBytes: input.uploadMaxFileSizeBytes,
|
||||
statusEmailsEnabled: input.statusEmailsEnabled,
|
||||
imprintUrl,
|
||||
privacyUrl,
|
||||
termsUrl,
|
||||
},
|
||||
});
|
||||
await tx.portal.update({ where: { id: portal.id }, data: { isPublished: input.publish } });
|
||||
await auditPortalAdminMutation(tx, input, "customer_portal.configuration.updated", "PortalConfiguration", portal.id, {
|
||||
publish: input.publish,
|
||||
enabledProjectTypes,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces or removes the tenant's private portal logo. Storage is changed
|
||||
* before the database marker so a failed upload can never advertise an object
|
||||
* that was not scanned and persisted. Upload failures after the PUT are
|
||||
* compensated by deleting the deterministic object, which safely falls back
|
||||
* to the HiveGrid logo.
|
||||
*/
|
||||
export async function savePortalBranding(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly logo: PortalBrandingLogoUpload | null;
|
||||
}): Promise<void> {
|
||||
await assertPortalAdminWritable(input.tenantId);
|
||||
const portal = await withTenantRLS(input.tenantId, (tx) =>
|
||||
tx.portal.findFirst({ where: { tenantId: input.tenantId }, select: { id: true } }),
|
||||
);
|
||||
if (!portal) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
|
||||
const configured = input.logo !== null;
|
||||
if (input.logo) {
|
||||
await storePortalBrandingLogo({ tenantId: input.tenantId, upload: input.logo });
|
||||
} else {
|
||||
// Deletion is fail-closed: never clear the marker while a reachable private
|
||||
// object could remain behind the deterministic public proxy path.
|
||||
await removePortalBrandingLogo(input.tenantId);
|
||||
}
|
||||
|
||||
try {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await tx.portal.update({
|
||||
where: { id: portal.id },
|
||||
data: { brandingLogo: configured ? portalBrandingLogoStorageKey(input.tenantId) : null },
|
||||
});
|
||||
await auditPortalAdminMutation(
|
||||
tx,
|
||||
input,
|
||||
configured ? "customer_portal.branding.updated" : "customer_portal.branding.removed",
|
||||
"Portal",
|
||||
portal.id,
|
||||
{ configured },
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
if (configured) {
|
||||
await removePortalBrandingLogo(input.tenantId).catch(() => undefined);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function setPortalStageVisibility(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly stageId: string;
|
||||
readonly visible: boolean;
|
||||
readonly customerLabel?: string | null;
|
||||
}): Promise<void> {
|
||||
await assertPortalAdminWritable(input.tenantId);
|
||||
const stageId = requireId(input.stageId);
|
||||
const customerLabel = input.customerLabel?.trim().slice(0, 200) || null;
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const [portal, stage] = await Promise.all([
|
||||
tx.portal.findFirst({ where: { tenantId: input.tenantId }, select: { id: true } }),
|
||||
tx.pipelineStage.findFirst({ where: { id: stageId, tenantId: input.tenantId }, select: { id: true } }),
|
||||
]);
|
||||
if (!portal || !stage) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
const visibility = await tx.portalStageVisibility.upsert({
|
||||
where: { portalId_stageId: { portalId: portal.id, stageId } },
|
||||
create: { tenantId: input.tenantId, portalId: portal.id, stageId, visible: input.visible, customerLabel },
|
||||
update: { visible: input.visible, customerLabel },
|
||||
});
|
||||
await auditPortalAdminMutation(tx, input, "customer_portal.stage_visibility.updated", "PortalStageVisibility", visibility.id, {
|
||||
stageId,
|
||||
visible: input.visible,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function setPortalDocumentAutoReleaseRule(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly projectType?: string | null;
|
||||
readonly documentType: string;
|
||||
readonly enabled: boolean;
|
||||
}): Promise<void> {
|
||||
await assertPortalAdminWritable(input.tenantId);
|
||||
const projectType = input.projectType?.trim() ? normalizeToken(input.projectType) : null;
|
||||
const documentType = normalizeToken(input.documentType);
|
||||
if (!documentType) throw invalid();
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const portal = await tx.portal.findFirst({ where: { tenantId: input.tenantId }, select: { id: true } });
|
||||
if (!portal) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
const existing = await tx.portalDocumentAutoReleaseRule.findFirst({ where: { portalId: portal.id, projectType, documentType }, select: { id: true } });
|
||||
const rule = existing
|
||||
? await tx.portalDocumentAutoReleaseRule.update({ where: { id: existing.id }, data: { enabled: input.enabled } })
|
||||
: await tx.portalDocumentAutoReleaseRule.create({
|
||||
data: { tenantId: input.tenantId, portalId: portal.id, projectType, documentType, enabled: input.enabled },
|
||||
});
|
||||
await auditPortalAdminMutation(tx, input, "customer_portal.auto_release.updated", "PortalDocumentAutoReleaseRule", rule.id, {
|
||||
projectType,
|
||||
documentType,
|
||||
enabled: input.enabled,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function invitePortalUser(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly email: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly kind: "customer" | "subcontractor";
|
||||
}): Promise<string> {
|
||||
try {
|
||||
return await invitePortalUserFromAdmin({ ...input, locale: null });
|
||||
} catch (error) {
|
||||
if (error instanceof PortalInvitationError) throw new PortalAdminError(error.messageKey, error.status);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function resendPortalUserInvitation(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly portalUserId: string;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
await resendPortalInvitation(input);
|
||||
} catch (error) {
|
||||
if (error instanceof PortalInvitationError) throw new PortalAdminError(error.messageKey, error.status);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function setPortalProjectAccess(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly portalUserId: string;
|
||||
readonly projectId: string;
|
||||
readonly active: boolean;
|
||||
readonly canUpload?: boolean;
|
||||
readonly validUntil?: Date | null;
|
||||
readonly companyName?: string | null;
|
||||
readonly roleLabel?: string | null;
|
||||
readonly visibleStageIds?: readonly string[];
|
||||
readonly visibleDocumentTypes?: readonly string[];
|
||||
readonly canSeeOtherSubcontractors?: boolean;
|
||||
}): Promise<void> {
|
||||
await assertPortalAdminWritable(input.tenantId);
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const [portal, user, project] = await Promise.all([
|
||||
tx.portal.findFirst({ where: { tenantId: input.tenantId }, select: { id: true } }),
|
||||
tx.portalUser.findFirst({ where: { id: requireId(input.portalUserId), tenantId: input.tenantId, archivedAt: null }, select: { id: true, kind: true } }),
|
||||
tx.projekt.findFirst({ where: { id: requireId(input.projectId), tenantId: input.tenantId, archivedAt: null }, select: { id: true } }),
|
||||
]);
|
||||
if (!portal || !user || !project) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
const visibleStageIds = [...new Set((input.visibleStageIds ?? []).map((value) => requireId(value)))];
|
||||
if (user.kind === "subcontractor" && visibleStageIds.length > 0) {
|
||||
const stages = await tx.pipelineStage.findMany({
|
||||
where: { tenantId: input.tenantId, id: { in: visibleStageIds }, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (stages.length !== visibleStageIds.length) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
}
|
||||
const visibleDocumentTypes = [...new Set((input.visibleDocumentTypes ?? []).map(normalizeToken).filter(Boolean))];
|
||||
const access = await tx.portalProjectAccess.upsert({
|
||||
where: { portalId_portalUserId_projectId: { portalId: portal.id, portalUserId: user.id, projectId: project.id } },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
portalId: portal.id,
|
||||
portalUserId: user.id,
|
||||
projectId: project.id,
|
||||
active: input.active,
|
||||
revokedAt: input.active ? null : new Date(),
|
||||
},
|
||||
update: { active: input.active, revokedAt: input.active ? null : new Date() },
|
||||
});
|
||||
if (user.kind === "subcontractor") {
|
||||
const existing = await tx.portalSubcontractorAccess.findFirst({ where: { projectAccessId: access.id, tenantId: input.tenantId }, select: { id: true } });
|
||||
const companyName = input.companyName?.trim().slice(0, 200) ?? "";
|
||||
if (input.active && !companyName) throw invalid();
|
||||
const data = {
|
||||
active: input.active,
|
||||
revokedAt: input.active ? null : new Date(),
|
||||
canUpload: input.canUpload ?? true,
|
||||
validFrom: input.active ? new Date() : undefined,
|
||||
validUntil: input.validUntil ?? null,
|
||||
companyName: companyName || "Subunternehmer",
|
||||
roleLabel: input.roleLabel?.trim().slice(0, 200) || null,
|
||||
visibleStageIds,
|
||||
visibleDocumentTypes,
|
||||
canSeeOtherSubcontractors: input.canSeeOtherSubcontractors ?? false,
|
||||
};
|
||||
if (existing) await tx.portalSubcontractorAccess.update({ where: { id: existing.id }, data });
|
||||
else
|
||||
await tx.portalSubcontractorAccess.create({
|
||||
data: { ...data, tenantId: input.tenantId, portalId: portal.id, portalUserId: user.id, projectId: project.id, projectAccessId: access.id },
|
||||
});
|
||||
} else {
|
||||
await tx.portalSubcontractorAccess.updateMany({
|
||||
where: { tenantId: input.tenantId, projectAccessId: access.id, revokedAt: null },
|
||||
data: { active: false, revokedAt: new Date() },
|
||||
});
|
||||
}
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: input.active ? "portal.access_granted" : "portal.access_revoked",
|
||||
data: { portalUserId: user.id, projectId: project.id, projectAccessId: access.id },
|
||||
userId: input.actorUserId,
|
||||
sourceId: `portal-access:${access.id}:${input.active ? "grant" : "revoke"}:${access.updatedAt.getTime()}`,
|
||||
})
|
||||
);
|
||||
await auditPortalAdminMutation(
|
||||
tx,
|
||||
input,
|
||||
input.active ? "customer_portal.access.granted" : "customer_portal.access.revoked",
|
||||
"PortalProjectAccess",
|
||||
access.id,
|
||||
{
|
||||
portalUserId: user.id,
|
||||
projectId: project.id,
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function disablePortalUser(input: { readonly tenantId: string; readonly actorUserId: string; readonly portalUserId: string }): Promise<void> {
|
||||
await assertPortalAdminWritable(input.tenantId);
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
const user = await tx.portalUser.findFirst({
|
||||
where: { id: requireId(input.portalUserId), tenantId: input.tenantId, archivedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!user) throw new PortalAdminError("customerPortal.admin.errors.notFound", 404);
|
||||
const now = new Date();
|
||||
await Promise.all([
|
||||
tx.portalUser.update({ where: { id: user.id }, data: { status: "disabled" } }),
|
||||
tx.portalSession.updateMany({ where: { tenantId: input.tenantId, portalUserId: user.id, revokedAt: null }, data: { revokedAt: now } }),
|
||||
tx.portalToken.updateMany({ where: { tenantId: input.tenantId, portalUserId: user.id, revokedAt: null }, data: { revokedAt: now } }),
|
||||
tx.portalProjectAccess.updateMany({
|
||||
where: { tenantId: input.tenantId, portalUserId: user.id, revokedAt: null },
|
||||
data: { active: false, revokedAt: now },
|
||||
}),
|
||||
tx.portalSubcontractorAccess.updateMany({
|
||||
where: { tenantId: input.tenantId, portalUserId: user.id, revokedAt: null },
|
||||
data: { active: false, revokedAt: now },
|
||||
}),
|
||||
]);
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: input.tenantId,
|
||||
event: "portal.lifecycle_changed",
|
||||
data: { portalUserId: user.id, status: "disabled" },
|
||||
userId: input.actorUserId,
|
||||
sourceId: `portal-user:${user.id}:disabled:${now.getTime()}`,
|
||||
})
|
||||
);
|
||||
await auditPortalAdminMutation(tx, input, "customer_portal.user.disabled", "PortalUser", user.id, {});
|
||||
});
|
||||
}
|
||||
|
||||
export async function updatePortalInbox(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly itemId: string;
|
||||
readonly status: PortalServiceInboxStatus;
|
||||
readonly ownerUserId?: string | null;
|
||||
}): Promise<void> {
|
||||
await assertPortalAdminWritable(input.tenantId);
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await updatePortalServiceInboxItemWithClient(tx as unknown as PortalInboxClient, {
|
||||
tenantId: input.tenantId,
|
||||
itemId: input.itemId,
|
||||
status: input.status,
|
||||
ownerUserId: input.ownerUserId,
|
||||
});
|
||||
await auditPortalAdminMutation(tx, input, "customer_portal.inbox.updated", "PortalServiceInboxItem", input.itemId, {
|
||||
status: input.status,
|
||||
ownerUserId: input.ownerUserId ?? null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function auditPortalAdminMutation(
|
||||
tx: Parameters<Parameters<typeof withTenantRLS>[1]>[0],
|
||||
input: { readonly tenantId: string; readonly actorUserId: string },
|
||||
action: string,
|
||||
targetType: string,
|
||||
targetId: string,
|
||||
metadata: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.actorUserId,
|
||||
actorType: "user",
|
||||
action,
|
||||
targetType,
|
||||
targetId,
|
||||
sourceModule: "customer_portal",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
metadata: metadata as Prisma.InputJsonValue,
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.actorUserId,
|
||||
actorKind: "user",
|
||||
activityType: "audit_event",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: action,
|
||||
metadata: { targetType, targetId, ...metadata },
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
}
|
||||
|
||||
async function assertPortalAdminWritable(tenantId: string): Promise<void> {
|
||||
if ((await getTenantBillingReadOnlyState(tenantId)).readOnly) throw new PortalAdminError("customerPortal.states.frozen.body", 423);
|
||||
}
|
||||
|
||||
function invalid(): PortalAdminError {
|
||||
return new PortalAdminError("customerPortal.admin.errors.invalidInput", 400);
|
||||
}
|
||||
|
||||
function requireId(value: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 191 || /[\u0000-\u001f\u007f]/u.test(normalized)) throw invalid();
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizeToken(value: string): string {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
return /^[a-z0-9][a-z0-9._-]{0,119}$/u.test(normalized) ? normalized : "";
|
||||
}
|
||||
|
||||
function normalizeLegalUrl(value: string): string {
|
||||
const normalized = value.trim();
|
||||
try {
|
||||
const url = new URL(normalized);
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.hash) throw invalid();
|
||||
return url.toString();
|
||||
} catch (error) {
|
||||
if (error instanceof PortalAdminError) throw error;
|
||||
throw invalid();
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeOptionalLegalUrl(value: string | null | undefined): string | null {
|
||||
return value?.trim() ? normalizeLegalUrl(value) : null;
|
||||
}
|
||||
|
||||
function personLabel(input: { readonly firstName: string; readonly lastName: string; readonly email: string }): string {
|
||||
return `${input.firstName} ${input.lastName}`.trim() || input.email;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { appendPortalAuditEvent, appendPortalSetupDenialAudit, PORTAL_AUDIT_ACTIONS, portalAuditRequestId } from "./portal-audit.server";
|
||||
|
||||
const repositoryRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../..");
|
||||
const portalPolicySql = readFileSync(path.join(repositoryRoot, "prisma/rls/portal-policy-contract-isolation.sql"), "utf8");
|
||||
|
||||
describe("customer portal semantic audit", () => {
|
||||
it("keeps every TypeScript audit action aligned with the database capability allowlist", () => {
|
||||
const appendAuditCapability = portalPolicySql.slice(
|
||||
portalPolicySql.indexOf("CREATE OR REPLACE FUNCTION public.hivegrid_portal_append_audit"),
|
||||
portalPolicySql.indexOf("RESET ROLE;", portalPolicySql.indexOf("CREATE OR REPLACE FUNCTION public.hivegrid_portal_append_audit"))
|
||||
);
|
||||
|
||||
for (const action of Object.values(PORTAL_AUDIT_ACTIONS)) {
|
||||
expect(appendAuditCapability).toContain(`'${action}'`);
|
||||
}
|
||||
});
|
||||
|
||||
it("passes only the reviewed action, target id, and sanitized request id to the database capability", async () => {
|
||||
const queryRaw = vi.fn().mockResolvedValue([{ outboxId: "portal-audit-outbox-1" }]);
|
||||
|
||||
await expect(
|
||||
appendPortalAuditEvent({ $queryRaw: queryRaw } as never, {
|
||||
action: PORTAL_AUDIT_ACTIONS.documentDownloaded,
|
||||
targetId: "release_1",
|
||||
requestId: " request:portal-123 ",
|
||||
})
|
||||
).resolves.toBe("portal-audit-outbox-1");
|
||||
|
||||
expect(queryRaw).toHaveBeenCalledOnce();
|
||||
expect((queryRaw.mock.calls[0]?.[0] as TemplateStringsArray).join("?")).toContain("hivegrid_portal_append_audit");
|
||||
expect(queryRaw.mock.calls[0]?.slice(1)).toEqual([PORTAL_AUDIT_ACTIONS.documentDownloaded, "release_1", "request:portal-123"]);
|
||||
});
|
||||
|
||||
it("drops untrusted request correlation instead of persisting header content", async () => {
|
||||
const request = new Request("https://portal.hivegrid.test/acme", {
|
||||
headers: { "x-request-id": "customer@example.test token=raw-secret" },
|
||||
});
|
||||
expect(portalAuditRequestId(request)).toBeNull();
|
||||
});
|
||||
|
||||
it("fails closed when the database capability returns no append proof", async () => {
|
||||
await expect(
|
||||
appendPortalAuditEvent({ $queryRaw: vi.fn().mockResolvedValue([]) } as never, { action: PORTAL_AUDIT_ACTIONS.logout, targetId: "portal_user_1" })
|
||||
).rejects.toThrow("did not append an event");
|
||||
});
|
||||
|
||||
it("passes only the trusted tenant and portal pair to the pre-auth setup denial capability", async () => {
|
||||
const queryRaw = vi.fn().mockResolvedValue([{ outboxId: "portal-setup-denial-outbox-1" }]);
|
||||
|
||||
await expect(appendPortalSetupDenialAudit({ $queryRaw: queryRaw } as never, { tenantId: "tenant_1", portalId: "portal_1" })).resolves.toBe(
|
||||
"portal-setup-denial-outbox-1"
|
||||
);
|
||||
|
||||
expect((queryRaw.mock.calls[0]?.[0] as TemplateStringsArray).join("?")).toContain("hivegrid_portal_append_setup_denial_audit");
|
||||
expect(queryRaw.mock.calls[0]?.slice(1)).toEqual(["tenant_1", "portal_1"]);
|
||||
});
|
||||
|
||||
it("keeps the pre-auth setup denial capability anonymous, fixed-purpose, and token-free", () => {
|
||||
const start = portalPolicySql.indexOf("CREATE OR REPLACE FUNCTION public.hivegrid_portal_append_setup_denial_audit");
|
||||
const end = portalPolicySql.indexOf("GRANT EXECUTE ON FUNCTION public.hivegrid_portal_append_setup_denial_audit(text,text) TO hivegrid_portal;", start);
|
||||
const capability = portalPolicySql.slice(start, end);
|
||||
|
||||
expect(start).toBeGreaterThanOrEqual(0);
|
||||
expect(end).toBeGreaterThan(start);
|
||||
expect(capability).toContain("session_user <> 'hivegrid_portal'");
|
||||
expect(capability).toContain("current_setting('app.tenant_id', true)");
|
||||
expect(capability).toContain("current_setting('app.portal_user_id', true)");
|
||||
expect(capability).toContain("current_setting('app.user_id', true)");
|
||||
expect(capability).toContain('portal."id" = p_portal_id');
|
||||
expect(capability).toContain('portal."tenantId" = p_tenant_id');
|
||||
expect(capability).toContain('portal."isPublished" = true');
|
||||
expect(capability).toContain("'actorId', NULL");
|
||||
expect(capability).toContain("'targetType', 'Portal'");
|
||||
expect(capability).toContain("'action', 'customer_portal.user.setup_capability_blocked'");
|
||||
expect(capability).toContain("'outcome', 'blocked'");
|
||||
expect(capability).not.toMatch(/p_(?:token|email|ip|request|action|reason|metadata)/u);
|
||||
});
|
||||
});
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
export const PORTAL_AUDIT_ACTIONS = {
|
||||
passwordLogin: "customer_portal.user.password_login",
|
||||
magicLinkLogin: "customer_portal.user.magic_link_login",
|
||||
setupCompleted: "customer_portal.user.setup_completed",
|
||||
emailVerified: "customer_portal.user.email_verified",
|
||||
passwordReset: "customer_portal.user.password_reset",
|
||||
logout: "customer_portal.user.logged_out",
|
||||
documentDownloaded: "customer_portal.document.downloaded",
|
||||
gdprExportRequested: "customer_portal.gdpr_export.requested",
|
||||
gdprExportDownloaded: "customer_portal.gdpr_export.downloaded",
|
||||
deletionRequested: "customer_portal.deletion.requested",
|
||||
deletionCancelled: "customer_portal.deletion.cancelled",
|
||||
} as const;
|
||||
|
||||
export type PortalAuditAction = (typeof PORTAL_AUDIT_ACTIONS)[keyof typeof PORTAL_AUDIT_ACTIONS];
|
||||
export type PortalSessionAuditAction = Exclude<PortalAuditAction, typeof PORTAL_AUDIT_ACTIONS.logout | typeof PORTAL_AUDIT_ACTIONS.documentDownloaded>;
|
||||
|
||||
type PortalAuditClient = Pick<DbClient | Prisma.TransactionClient, "$queryRaw">;
|
||||
|
||||
const SAFE_REQUEST_ID_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
|
||||
|
||||
/**
|
||||
* Appends one purpose-bound portal audit event through the dedicated database
|
||||
* capability. Tenant and actor identity are deliberately not caller inputs:
|
||||
* PostgreSQL derives and verifies both from the transaction-local portal GUCs.
|
||||
*/
|
||||
export async function appendPortalAuditEvent(
|
||||
client: PortalAuditClient,
|
||||
input: {
|
||||
readonly action: PortalAuditAction;
|
||||
readonly targetId: string;
|
||||
readonly requestId?: string | null;
|
||||
}
|
||||
): Promise<string> {
|
||||
const rows = await client.$queryRaw<Array<{ outboxId: string }>>`
|
||||
SELECT public.hivegrid_portal_append_audit(
|
||||
${input.action},
|
||||
${input.targetId},
|
||||
${normalizePortalAuditRequestId(input.requestId)}
|
||||
) AS "outboxId"
|
||||
`;
|
||||
const outboxId = rows[0]?.outboxId;
|
||||
if (!outboxId) throw new Error("Portal audit capability did not append an event.");
|
||||
return outboxId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the one reviewed anonymous pre-auth audit event. PostgreSQL
|
||||
* re-proves the exact active tenant/published portal pair and rejects any
|
||||
* user-bound GUC context. No token-derived or request-derived value crosses
|
||||
* this boundary.
|
||||
*/
|
||||
export async function appendPortalSetupDenialAudit(
|
||||
client: PortalAuditClient,
|
||||
input: {
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
}
|
||||
): Promise<string> {
|
||||
const rows = await client.$queryRaw<Array<{ outboxId: string }>>`
|
||||
SELECT public.hivegrid_portal_append_setup_denial_audit(
|
||||
${input.tenantId},
|
||||
${input.portalId}
|
||||
) AS "outboxId"
|
||||
`;
|
||||
const outboxId = rows[0]?.outboxId;
|
||||
if (!outboxId) throw new Error("Portal setup denial audit capability did not append an event.");
|
||||
return outboxId;
|
||||
}
|
||||
|
||||
export function portalAuditRequestId(request: Request): string | null {
|
||||
return normalizePortalAuditRequestId(request.headers.get("x-request-id"));
|
||||
}
|
||||
|
||||
function normalizePortalAuditRequestId(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
const normalized = value.trim();
|
||||
return SAFE_REQUEST_ID_PATTERN.test(normalized) ? normalized : null;
|
||||
}
|
||||
+793
@@ -0,0 +1,793 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
checkRateLimit: vi.fn(),
|
||||
verifyCaptcha: vi.fn(),
|
||||
resolveUser: vi.fn(),
|
||||
resolveToken: vi.fn(),
|
||||
auditSetupDenial: vi.fn(),
|
||||
issueToken: vi.fn(),
|
||||
consumeToken: vi.fn(),
|
||||
createSession: vi.fn(),
|
||||
createSessionInTransaction: vi.fn(),
|
||||
sendMail: vi.fn(),
|
||||
verifyPassword: vi.fn(),
|
||||
hashPassword: vi.fn(),
|
||||
waitForFloor: vi.fn(),
|
||||
renderMail: vi.fn(),
|
||||
validatePassword: vi.fn(),
|
||||
isPasswordLocked: vi.fn(),
|
||||
recordPasswordFailure: vi.fn(),
|
||||
clearPasswordFailures: vi.fn(),
|
||||
loggerError: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/captcha", () => ({
|
||||
getSecret: () => "captcha-secret",
|
||||
resolveCaptchaConfig: () => ({
|
||||
provider: "mcaptcha",
|
||||
instanceUrl: "https://captcha.example.test",
|
||||
sitekeys: { login: "login-sitekey" },
|
||||
secrets: { login: "captcha-secret" },
|
||||
failOpen: false,
|
||||
}),
|
||||
verifyCaptchaToken: (...args: unknown[]) => mocks.verifyCaptcha(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({
|
||||
runtimeSurface: "portal",
|
||||
i18n: { enabledLocales: ["de", "en"] },
|
||||
portalSessionSecret: "portal-session-secret-with-at-least-32-bytes",
|
||||
routing: { protocol: "https", portalAppHost: "portal.hivegrid.de" },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/mail", () => ({
|
||||
buildBrand: (input: unknown) => input,
|
||||
renderTransactionalEmail: (...args: unknown[]) => mocks.renderMail(...args),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/emails/services/MailjetEmailService", () => ({
|
||||
sendEmailMailjet: (...args: unknown[]) => mocks.sendMail(...args),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/auth/passwordHasher.server", () => ({
|
||||
hashPassword: (...args: unknown[]) => mocks.hashPassword(...args),
|
||||
verifyPassword: (...args: unknown[]) => mocks.verifyPassword(...args),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/auth/password-policy.server", () => ({
|
||||
validatePassword: (...args: unknown[]) => mocks.validatePassword(...args),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/server/IpUtils", () => ({ getTrustedClientIp: () => "203.0.113.42" }));
|
||||
vi.mock("~/utils/logger.server", () => ({
|
||||
createScopedLogger: () => ({ error: mocks.loggerError, warn: vi.fn(), info: vi.fn(), debug: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("./portal-auth-rate-limit.server", () => ({
|
||||
checkPortalAuthRateLimit: (...args: unknown[]) => mocks.checkRateLimit(...args),
|
||||
isPortalPasswordLocked: (...args: unknown[]) => mocks.isPasswordLocked(...args),
|
||||
recordPortalPasswordFailure: (...args: unknown[]) => mocks.recordPasswordFailure(...args),
|
||||
clearPortalPasswordFailures: (...args: unknown[]) => mocks.clearPasswordFailures(...args),
|
||||
}));
|
||||
|
||||
vi.mock("./portal-data.server", () => ({
|
||||
auditPortalSetupCapabilityDenial: (...args: unknown[]) => mocks.auditSetupDenial(...args),
|
||||
resolvePortalUserByEmail: (...args: unknown[]) => mocks.resolveUser(...args),
|
||||
resolvePortalToken: (...args: unknown[]) => mocks.resolveToken(...args),
|
||||
issuePortalAuthToken: (...args: unknown[]) => mocks.issueToken(...args),
|
||||
consumePortalAuthToken: (...args: unknown[]) => mocks.consumeToken(...args),
|
||||
createPortalSession: (...args: unknown[]) => mocks.createSession(...args),
|
||||
createPortalSessionInTransaction: (...args: unknown[]) => mocks.createSessionInTransaction(...args),
|
||||
}));
|
||||
|
||||
vi.mock("./portal-auth-token.server", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("./portal-auth-token.server")>();
|
||||
return { ...actual, waitForPortalAuthResponseFloor: (...args: unknown[]) => mocks.waitForFloor(...args) };
|
||||
});
|
||||
|
||||
import { consumePortalCapability, requestPortalPasswordReset, requestPortalSignInLink, signInPortalWithPassword } from "./portal-auth-flow.server";
|
||||
import { PORTAL_AUDIT_ACTIONS } from "./portal-audit.server";
|
||||
|
||||
const tenant = {
|
||||
tenantId: "tenant_1",
|
||||
portalId: "portal_1",
|
||||
tenantSlug: "acme",
|
||||
tenantName: "Acme",
|
||||
portalTitle: "Acme Portal",
|
||||
imprintUrl: "https://acme.example.test/impressum",
|
||||
privacyUrl: "https://acme.example.test/datenschutz",
|
||||
termsUrl: null,
|
||||
tenantActive: true,
|
||||
tenantFrozen: false,
|
||||
};
|
||||
|
||||
const user = {
|
||||
tenantId: "tenant_1",
|
||||
portalId: "portal_1",
|
||||
portalUserId: "portal_user_1",
|
||||
email: "customer@example.com",
|
||||
emailNormalized: "customer@example.com",
|
||||
firstName: "Karla",
|
||||
lastName: "Kunde",
|
||||
passwordHash: "stored-password-hash",
|
||||
status: "active" as const,
|
||||
locale: "de",
|
||||
emailVerifiedAt: new Date("2026-07-15T10:00:00.000Z"),
|
||||
authRequireEmailVerification: true,
|
||||
};
|
||||
|
||||
const request = new Request("https://portal.hivegrid.de/acme/login", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"user-agent": "Portal test",
|
||||
"cf-connecting-ip": "203.0.113.42",
|
||||
"x-request-id": "portal-auth-request-1",
|
||||
"x-hivegrid-portal-origin": "https://portal.hivegrid.de",
|
||||
"x-hivegrid-portal-tenant": "acme",
|
||||
},
|
||||
});
|
||||
|
||||
const privacyAcknowledgement = {
|
||||
privacyNoticeAcknowledged: true,
|
||||
privacyNoticeUrl: tenant.privacyUrl,
|
||||
} as const;
|
||||
|
||||
const localizedMailCases = [
|
||||
{
|
||||
locale: "de",
|
||||
purpose: "magic_link",
|
||||
template: "magic-link",
|
||||
route: "login/magic",
|
||||
copy: {
|
||||
subject: "Dein Anmeldelink für Acme Portal",
|
||||
previewText: "Sicher bei Acme Portal anmelden",
|
||||
eyebrow: "Sicherer Anmeldelink",
|
||||
title: "Hallo, Karla!",
|
||||
intro: "Über diesen sicheren Link kannst du dein Kundenportal öffnen.",
|
||||
actionLabel: "Kundenportal öffnen",
|
||||
outro: "Wenn du diesen Anmeldelink nicht angefordert hast, kannst du diese E-Mail ignorieren.",
|
||||
expiresText: "Dieser Link ist 15 Minuten gültig und kann nur einmal verwendet werden.",
|
||||
signoffThanks: "Viele Grüße",
|
||||
expiresInMinutes: 15,
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: "de",
|
||||
purpose: "setup",
|
||||
template: "magic-link",
|
||||
route: "setup",
|
||||
copy: {
|
||||
subject: "Richte deinen Zugang zu Acme Portal ein",
|
||||
previewText: "Kundenportal-Zugang sicher einrichten",
|
||||
eyebrow: "Zugang einrichten",
|
||||
title: "Hallo, Karla!",
|
||||
intro: "Lege über diesen sicheren Link dein Passwort fest und aktiviere deinen Kundenportal-Zugang.",
|
||||
actionLabel: "Zugang einrichten",
|
||||
outro: "Wenn du diesen Zugang nicht erwartest, ignoriere diese E-Mail und wende dich an deinen Ansprechpartner.",
|
||||
expiresText: "Dieser Einrichtungslink ist 7 Tage gültig und kann nur einmal verwendet werden.",
|
||||
signoffThanks: "Viele Grüße",
|
||||
expiresInMinutes: 10080,
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: "de",
|
||||
purpose: "verify_email",
|
||||
template: "magic-link",
|
||||
route: "verify-email",
|
||||
copy: {
|
||||
subject: "Bestätige deine E-Mail-Adresse für Acme Portal",
|
||||
previewText: "E-Mail-Adresse für das Kundenportal bestätigen",
|
||||
eyebrow: "E-Mail-Adresse bestätigen",
|
||||
title: "Hallo, Karla!",
|
||||
intro: "Bestätige über diesen sicheren Link deine E-Mail-Adresse und aktiviere deinen Kundenportal-Zugang.",
|
||||
actionLabel: "E-Mail-Adresse bestätigen",
|
||||
outro: "Wenn du diese Bestätigung nicht angefordert hast, kannst du diese E-Mail ignorieren.",
|
||||
expiresText: "Dieser Bestätigungslink ist 24 Stunden gültig und kann nur einmal verwendet werden.",
|
||||
signoffThanks: "Viele Grüße",
|
||||
expiresInMinutes: 1440,
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: "de",
|
||||
purpose: "reset_password",
|
||||
template: "password-reset",
|
||||
route: "reset-password",
|
||||
copy: {
|
||||
subject: "Passwort für Acme Portal zurücksetzen",
|
||||
eyebrow: "Passwort zurücksetzen",
|
||||
title: "Hallo, Karla!",
|
||||
intro: "Über diesen sicheren Link kannst du ein neues Passwort für deinen Kundenportal-Zugang festlegen.",
|
||||
actionLabel: "Neues Passwort festlegen",
|
||||
outro:
|
||||
"Dieser Link ist 1 Stunde gültig und kann nur einmal verwendet werden. Wenn du keine Passwort-Zurücksetzung angefordert hast, kannst du diese E-Mail ignorieren.",
|
||||
signoffThanks: "Viele Grüße",
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: "en",
|
||||
purpose: "magic_link",
|
||||
template: "magic-link",
|
||||
route: "login/magic",
|
||||
copy: {
|
||||
subject: "Your sign-in link for Acme Portal",
|
||||
previewText: "Sign in securely to Acme Portal",
|
||||
eyebrow: "Secure sign-in link",
|
||||
title: "Hello, Karla!",
|
||||
intro: "Use this secure link to open your customer portal.",
|
||||
actionLabel: "Open customer portal",
|
||||
outro: "If you did not request this sign-in link, you can safely ignore this email.",
|
||||
expiresText: "This link is valid for 15 minutes and can only be used once.",
|
||||
signoffThanks: "Kind regards,",
|
||||
expiresInMinutes: 15,
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: "en",
|
||||
purpose: "setup",
|
||||
template: "magic-link",
|
||||
route: "setup",
|
||||
copy: {
|
||||
subject: "Set up your access to Acme Portal",
|
||||
previewText: "Set up your customer portal access securely",
|
||||
eyebrow: "Set up access",
|
||||
title: "Hello, Karla!",
|
||||
intro: "Use this secure link to set your password and activate your customer portal access.",
|
||||
actionLabel: "Set up access",
|
||||
outro: "If you were not expecting this access, ignore this email and contact your point of contact.",
|
||||
expiresText: "This setup link is valid for 7 days and can only be used once.",
|
||||
signoffThanks: "Kind regards,",
|
||||
expiresInMinutes: 10080,
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: "en",
|
||||
purpose: "verify_email",
|
||||
template: "magic-link",
|
||||
route: "verify-email",
|
||||
copy: {
|
||||
subject: "Confirm your email address for Acme Portal",
|
||||
previewText: "Confirm your email address for the customer portal",
|
||||
eyebrow: "Confirm email address",
|
||||
title: "Hello, Karla!",
|
||||
intro: "Use this secure link to confirm your email address and activate your customer portal access.",
|
||||
actionLabel: "Confirm email address",
|
||||
outro: "If you did not request this confirmation, you can safely ignore this email.",
|
||||
expiresText: "This confirmation link is valid for 24 hours and can only be used once.",
|
||||
signoffThanks: "Kind regards,",
|
||||
expiresInMinutes: 1440,
|
||||
},
|
||||
},
|
||||
{
|
||||
locale: "en",
|
||||
purpose: "reset_password",
|
||||
template: "password-reset",
|
||||
route: "reset-password",
|
||||
copy: {
|
||||
subject: "Reset your password for Acme Portal",
|
||||
eyebrow: "Password reset",
|
||||
title: "Hello, Karla!",
|
||||
intro: "Use this secure link to set a new password for your customer portal access.",
|
||||
actionLabel: "Set a new password",
|
||||
outro: "This link is valid for 1 hour and can only be used once. If you did not request a password reset, you can safely ignore this email.",
|
||||
signoffThanks: "Kind regards,",
|
||||
},
|
||||
},
|
||||
] as const;
|
||||
|
||||
describe("portal auth flow", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.checkRateLimit.mockResolvedValue({ allowed: true });
|
||||
mocks.verifyCaptcha.mockResolvedValue(true);
|
||||
mocks.auditSetupDenial.mockResolvedValue(undefined);
|
||||
mocks.waitForFloor.mockResolvedValue(undefined);
|
||||
mocks.issueToken.mockResolvedValue({ rawToken: "t".repeat(43), expiresAt: new Date("2026-07-15T10:15:00.000Z") });
|
||||
mocks.createSession.mockResolvedValue({ rawToken: "session-token", expiresAt: new Date("2026-08-15T10:00:00.000Z") });
|
||||
mocks.createSessionInTransaction.mockResolvedValue({ rawToken: "session-token", expiresAt: new Date("2026-08-15T10:00:00.000Z") });
|
||||
mocks.hashPassword.mockResolvedValue("new-password-hash");
|
||||
mocks.resolveToken.mockResolvedValue({
|
||||
tenantId: user.tenantId,
|
||||
portalId: user.portalId,
|
||||
portalUserId: user.portalUserId,
|
||||
portalTokenId: "token_1",
|
||||
emailNormalized: user.emailNormalized,
|
||||
purpose: "setup",
|
||||
expiresAt: new Date("2026-07-15T10:15:00.000Z"),
|
||||
});
|
||||
mocks.validatePassword.mockResolvedValue({ valid: true, errors: [] });
|
||||
mocks.isPasswordLocked.mockResolvedValue(false);
|
||||
mocks.recordPasswordFailure.mockResolvedValue(false);
|
||||
mocks.clearPasswordFailures.mockResolvedValue(true);
|
||||
mocks.renderMail.mockReturnValue({ html: "<p>secure portal mail</p>", text: "secure portal mail" });
|
||||
mocks.sendMail.mockResolvedValue({ status: "queued" });
|
||||
});
|
||||
|
||||
it("returns the same generic magic-link result for an existing and an unknown address", async () => {
|
||||
mocks.resolveUser.mockResolvedValueOnce(user).mockResolvedValueOnce(null);
|
||||
|
||||
const existing = await requestPortalSignInLink({ request, tenant, email: "Customer@Example.com", captchaToken: "captcha" });
|
||||
const unknown = await requestPortalSignInLink({ request, tenant, email: "unknown@example.com", captchaToken: "captcha" });
|
||||
|
||||
expect(existing).toEqual({ ok: true, kind: "sent" });
|
||||
expect(unknown).toEqual(existing);
|
||||
expect(mocks.issueToken).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.sendMail).toHaveBeenCalledTimes(1);
|
||||
expect(mocks.waitForFloor).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("carries only a canonical same-tenant project continuation into the issued magic link", async () => {
|
||||
mocks.resolveUser.mockResolvedValue(user);
|
||||
|
||||
await requestPortalSignInLink({
|
||||
request,
|
||||
tenant,
|
||||
email: user.email,
|
||||
captchaToken: "captcha",
|
||||
continuePath: "/acme/projects/project_123",
|
||||
});
|
||||
await requestPortalSignInLink({
|
||||
request,
|
||||
tenant,
|
||||
email: user.email,
|
||||
captchaToken: "captcha",
|
||||
continuePath: "/other/projects/project_123",
|
||||
});
|
||||
|
||||
expect(mocks.renderMail).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"magic-link",
|
||||
expect.objectContaining({
|
||||
actionUrl: `https://portal.hivegrid.de/acme/login/magic/${"t".repeat(43)}?continue=%2Facme%2Fprojects%2Fproject_123`,
|
||||
})
|
||||
);
|
||||
expect(mocks.renderMail).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"magic-link",
|
||||
expect.objectContaining({ actionUrl: `https://portal.hivegrid.de/acme/login/magic/${"t".repeat(43)}` })
|
||||
);
|
||||
expect(JSON.stringify(mocks.renderMail.mock.calls[1])).not.toContain("other/projects");
|
||||
});
|
||||
|
||||
it("returns generic success without issuing setup mail for invited users and keeps reset active-only", async () => {
|
||||
mocks.resolveUser.mockResolvedValueOnce({ ...user, status: "invited", emailVerifiedAt: null }).mockResolvedValueOnce(user);
|
||||
|
||||
await requestPortalSignInLink({ request, tenant, email: user.email, captchaToken: "captcha" });
|
||||
await requestPortalPasswordReset({ request, tenant, email: user.email, captchaToken: "captcha" });
|
||||
|
||||
expect(mocks.issueToken).toHaveBeenCalledOnce();
|
||||
expect(mocks.issueToken).toHaveBeenCalledWith(expect.objectContaining({ portalUserId: user.portalUserId }), "reset_password", expect.any(String));
|
||||
expect(mocks.issueToken).not.toHaveBeenCalledWith(expect.anything(), "setup", expect.anything());
|
||||
expect(mocks.sendMail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ to: user.email, body: "<p>secure portal mail</p>", tenantId: tenant.tenantId }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it.each(localizedMailCases.filter(({ purpose }) => purpose !== "setup"))(
|
||||
"renders every visible $locale $purpose template string from the user locale",
|
||||
async ({ locale, purpose, template, route, copy }) => {
|
||||
const localizedUser = {
|
||||
...user,
|
||||
locale,
|
||||
status: "active" as const,
|
||||
emailVerifiedAt: purpose === "verify_email" ? null : user.emailVerifiedAt,
|
||||
};
|
||||
mocks.resolveUser.mockResolvedValue(localizedUser);
|
||||
|
||||
if (purpose === "reset_password") {
|
||||
await requestPortalPasswordReset({ request, tenant, email: localizedUser.email, captchaToken: "captcha" });
|
||||
} else {
|
||||
await requestPortalSignInLink({ request, tenant, email: localizedUser.email, captchaToken: "captcha" });
|
||||
}
|
||||
|
||||
expect(mocks.renderMail).toHaveBeenCalledOnce();
|
||||
expect(mocks.renderMail).toHaveBeenCalledWith(
|
||||
template,
|
||||
expect.objectContaining({
|
||||
brand: { productName: tenant.portalTitle },
|
||||
language: locale,
|
||||
footerCopy: expect.objectContaining({
|
||||
privacyLabel: locale === "de" ? "Datenschutz" : "Privacy",
|
||||
imprintLabel: locale === "de" ? "Impressum" : "Imprint",
|
||||
}),
|
||||
recipientName: localizedUser.firstName,
|
||||
actionUrl: `https://portal.hivegrid.de/${tenant.tenantSlug}/${route}/${"t".repeat(43)}`,
|
||||
...copy,
|
||||
})
|
||||
);
|
||||
expect(mocks.sendMail).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
to: localizedUser.email,
|
||||
subject: copy.subject,
|
||||
body: "<p>secure portal mail</p>",
|
||||
text: "secure portal mail",
|
||||
alias: purpose === "reset_password" ? "password-reset" : "magic-link",
|
||||
source: "portal-auth-mail",
|
||||
}),
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
it("checks a dummy hash for unknown password identities and returns the same credential error", async () => {
|
||||
mocks.resolveUser.mockResolvedValue(null);
|
||||
mocks.verifyPassword.mockResolvedValue({ valid: false });
|
||||
|
||||
await expect(
|
||||
signInPortalWithPassword({ request, tenant, email: "unknown@example.com", password: "wrong-password", captchaToken: "captcha" })
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.invalidCredentials", status: 400 });
|
||||
expect(mocks.verifyPassword).toHaveBeenCalledWith("wrong-password", expect.stringMatching(/^\$argon2id\$/u));
|
||||
expect(mocks.createSession).not.toHaveBeenCalled();
|
||||
expect(mocks.recordPasswordFailure).toHaveBeenCalledWith({
|
||||
secret: "portal-session-secret-with-at-least-32-bytes",
|
||||
tenantSlug: tenant.tenantSlug,
|
||||
identifier: "unknown@example.com",
|
||||
});
|
||||
expect(mocks.waitForFloor).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps locked email identities indistinguishable while skipping password/session mutations", async () => {
|
||||
mocks.isPasswordLocked.mockResolvedValue(true);
|
||||
mocks.resolveUser.mockResolvedValue(user);
|
||||
mocks.verifyPassword.mockResolvedValue({ valid: true, rehashedHash: "rehash-must-not-be-written" });
|
||||
|
||||
await expect(signInPortalWithPassword({ request, tenant, email: user.email, password: "correct-password", captchaToken: "captcha" })).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey: "customerPortal.auth.errors.invalidCredentials",
|
||||
status: 400,
|
||||
});
|
||||
|
||||
expect(mocks.verifyPassword).toHaveBeenCalledOnce();
|
||||
expect(mocks.recordPasswordFailure).not.toHaveBeenCalled();
|
||||
expect(mocks.clearPasswordFailures).not.toHaveBeenCalled();
|
||||
expect(mocks.createSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("creates only a portal session after verified password authentication", async () => {
|
||||
mocks.resolveUser.mockResolvedValue(user);
|
||||
mocks.verifyPassword.mockResolvedValue({ valid: true, rehashedHash: null });
|
||||
|
||||
await expect(signInPortalWithPassword({ request, tenant, email: user.email, password: "correct-password", captchaToken: "captcha" })).resolves.toEqual({
|
||||
ok: true,
|
||||
kind: "session",
|
||||
rawSessionToken: "session-token",
|
||||
expiresAt: new Date("2026-08-15T10:00:00.000Z"),
|
||||
});
|
||||
expect(mocks.createSession).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ portalUserId: user.portalUserId, tenantId: user.tenantId }),
|
||||
expect.objectContaining({
|
||||
userAgent: "Portal test",
|
||||
ipAddressHash: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
audit: { action: PORTAL_AUDIT_ACTIONS.passwordLogin, requestId: "portal-auth-request-1" },
|
||||
})
|
||||
);
|
||||
expect(mocks.clearPasswordFailures).toHaveBeenCalledWith({
|
||||
secret: "portal-session-secret-with-at-least-32-bytes",
|
||||
tenantSlug: tenant.tenantSlug,
|
||||
identifier: user.email,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the M15 magic-link limits of three per email per 15 minutes and ten per IP per hour", async () => {
|
||||
mocks.resolveUser.mockResolvedValue(null);
|
||||
|
||||
await requestPortalSignInLink({ request, tenant, email: user.email, captchaToken: "captcha" });
|
||||
|
||||
expect(mocks.checkRateLimit).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
expect.objectContaining({
|
||||
action: "magic-link",
|
||||
identifier: user.email,
|
||||
limit: 3,
|
||||
identifierLimit: 3,
|
||||
clientLimit: 10,
|
||||
windowMs: 15 * 60 * 1000,
|
||||
clientWindowMs: 60 * 60 * 1000,
|
||||
scopes: ["client"],
|
||||
})
|
||||
);
|
||||
expect(mocks.checkRateLimit).toHaveBeenNthCalledWith(2, expect.objectContaining({ scopes: ["identifier", "pair"] }));
|
||||
expect(mocks.checkRateLimit.mock.invocationCallOrder[0]).toBeLessThan(mocks.verifyCaptcha.mock.invocationCallOrder[0]!);
|
||||
expect(mocks.verifyCaptcha.mock.invocationCallOrder[0]).toBeLessThan(mocks.checkRateLimit.mock.invocationCallOrder[1]!);
|
||||
});
|
||||
|
||||
it("fails closed before identity lookup when rate limiting or captcha fails", async () => {
|
||||
mocks.checkRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 60 });
|
||||
await expect(requestPortalSignInLink({ request, tenant, email: user.email, captchaToken: "captcha" })).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey: "customerPortal.auth.errors.rateLimited",
|
||||
status: 429,
|
||||
});
|
||||
|
||||
mocks.checkRateLimit.mockResolvedValueOnce({ allowed: true });
|
||||
mocks.verifyCaptcha.mockResolvedValueOnce(false);
|
||||
await expect(requestPortalSignInLink({ request, tenant, email: user.email, captchaToken: "invalid" })).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey: "customerPortal.auth.errors.captcha",
|
||||
status: 400,
|
||||
});
|
||||
expect(mocks.checkRateLimit).toHaveBeenCalledTimes(2);
|
||||
expect(mocks.checkRateLimit).toHaveBeenNthCalledWith(2, expect.objectContaining({ scopes: ["client"] }));
|
||||
expect(mocks.checkRateLimit).not.toHaveBeenCalledWith(expect.objectContaining({ scopes: ["identifier", "pair"] }));
|
||||
expect(mocks.resolveUser).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("consumes a single-purpose setup capability atomically with activation and session creation", async () => {
|
||||
const updateMany = vi.fn().mockResolvedValue({ count: 1 });
|
||||
const tx = { portalUser: { updateMany } };
|
||||
mocks.consumeToken.mockImplementation(async (_token, _purpose, _requestedIpHash, effect) =>
|
||||
effect(tx, { tenantId: user.tenantId, portalId: user.portalId, portalUserId: user.portalUserId, portalTokenId: "token_1" })
|
||||
);
|
||||
|
||||
const result = await consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "setup",
|
||||
captchaToken: "captcha",
|
||||
...privacyAcknowledgement,
|
||||
password: "a-secure-password",
|
||||
passwordConfirmation: "a-secure-password",
|
||||
});
|
||||
|
||||
expect(result).toEqual({ ok: true, kind: "session", rawSessionToken: "session-token", expiresAt: new Date("2026-08-15T10:00:00.000Z") });
|
||||
expect(mocks.resolveToken).toHaveBeenCalledWith("t".repeat(43), "setup", expect.stringMatching(/^[a-f0-9]{64}$/u));
|
||||
const requestedIpHash = mocks.resolveToken.mock.calls[0]?.[2];
|
||||
expect(mocks.consumeToken).toHaveBeenCalledWith("t".repeat(43), "setup", requestedIpHash, expect.any(Function), {
|
||||
tenantId: tenant.tenantId,
|
||||
portalId: tenant.portalId,
|
||||
});
|
||||
expect(updateMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: { id: user.portalUserId, tenantId: user.tenantId },
|
||||
data: expect.objectContaining({ status: "active", passwordHash: "new-password-hash", emailVerifiedAt: expect.any(Date) }),
|
||||
})
|
||||
);
|
||||
expect(mocks.createSessionInTransaction).toHaveBeenCalledWith(
|
||||
tx,
|
||||
expect.objectContaining({ portalUserId: user.portalUserId }),
|
||||
expect.objectContaining({ audit: { action: PORTAL_AUDIT_ACTIONS.setupCompleted, requestId: "portal-auth-request-1" } })
|
||||
);
|
||||
expect(mocks.validatePassword).toHaveBeenCalledWith("a-secure-password", { email: user.emailNormalized });
|
||||
});
|
||||
|
||||
it("activates setup in magic-link-only mode without requiring or writing a password", async () => {
|
||||
const updateMany = vi.fn().mockResolvedValue({ count: 1 });
|
||||
const tx = { portalUser: { updateMany } };
|
||||
mocks.consumeToken.mockImplementation(async (_token, _purpose, _requestedIpHash, effect) =>
|
||||
effect(tx, { tenantId: user.tenantId, portalId: user.portalId, portalUserId: user.portalUserId, portalTokenId: "token_1" })
|
||||
);
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "setup",
|
||||
captchaToken: "captcha",
|
||||
...privacyAcknowledgement,
|
||||
})
|
||||
).resolves.toEqual({ ok: true, kind: "session", rawSessionToken: "session-token", expiresAt: new Date("2026-08-15T10:00:00.000Z") });
|
||||
|
||||
expect(mocks.resolveToken).not.toHaveBeenCalled();
|
||||
expect(mocks.validatePassword).not.toHaveBeenCalled();
|
||||
expect(mocks.hashPassword).not.toHaveBeenCalled();
|
||||
expect(updateMany).toHaveBeenCalledWith({
|
||||
where: { id: user.portalUserId, tenantId: user.tenantId },
|
||||
data: {
|
||||
status: "active",
|
||||
emailVerifiedAt: expect.any(Date),
|
||||
privacyNoticeAcknowledgedAt: expect.any(Date),
|
||||
privacyNoticeAcknowledgedUrl: tenant.privacyUrl,
|
||||
},
|
||||
});
|
||||
expect(mocks.consumeToken).toHaveBeenCalledWith("t".repeat(43), "setup", expect.stringMatching(/^[a-f0-9]{64}$/u), expect.any(Function), {
|
||||
tenantId: tenant.tenantId,
|
||||
portalId: tenant.portalId,
|
||||
});
|
||||
});
|
||||
|
||||
it("maps a request-IP token mismatch to the same generic invalid-token response", async () => {
|
||||
mocks.consumeToken.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "magic_link",
|
||||
captchaToken: "captcha",
|
||||
})
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.invalidToken", status: 400 });
|
||||
|
||||
expect(mocks.consumeToken).toHaveBeenCalledWith("t".repeat(43), "magic_link", expect.stringMatching(/^[a-f0-9]{64}$/u), expect.any(Function), {
|
||||
tenantId: tenant.tenantId,
|
||||
portalId: tenant.portalId,
|
||||
});
|
||||
expect(mocks.createSessionInTransaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("audits a failed concurrent setup replay only after the public auth guards and without token or PII", async () => {
|
||||
const rawToken = "replayed-secret-setup-token";
|
||||
mocks.consumeToken.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken,
|
||||
purpose: "setup",
|
||||
captchaToken: "captcha",
|
||||
...privacyAcknowledgement,
|
||||
})
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.invalidToken", status: 400 });
|
||||
|
||||
expect(mocks.auditSetupDenial).toHaveBeenCalledWith({
|
||||
tenantId: tenant.tenantId,
|
||||
portalId: tenant.portalId,
|
||||
});
|
||||
expect(mocks.auditSetupDenial.mock.invocationCallOrder[0]).toBeGreaterThan(mocks.verifyCaptcha.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER);
|
||||
expect(JSON.stringify(mocks.auditSetupDenial.mock.calls)).not.toContain(rawToken);
|
||||
expect(JSON.stringify(mocks.auditSetupDenial.mock.calls)).not.toContain(user.email);
|
||||
expect(mocks.createSessionInTransaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("audits an unresolved password-bearing setup capability before password hashing", async () => {
|
||||
mocks.resolveToken.mockResolvedValueOnce(null);
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "unresolved-setup-token",
|
||||
purpose: "setup",
|
||||
captchaToken: "captcha",
|
||||
...privacyAcknowledgement,
|
||||
password: "a-secure-password",
|
||||
passwordConfirmation: "a-secure-password",
|
||||
})
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.invalidToken", status: 400 });
|
||||
|
||||
expect(mocks.auditSetupDenial).toHaveBeenCalledWith({ tenantId: tenant.tenantId, portalId: tenant.portalId });
|
||||
expect(mocks.hashPassword).not.toHaveBeenCalled();
|
||||
expect(mocks.consumeToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects password capability misuse before hashing or token consumption", async () => {
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "reset_password",
|
||||
captchaToken: "captcha",
|
||||
password: "different-password",
|
||||
passwordConfirmation: "mismatch-password",
|
||||
})
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.passwordPolicy", status: 400 });
|
||||
expect(mocks.hashPassword).not.toHaveBeenCalled();
|
||||
expect(mocks.consumeToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires the current canonical privacy notice before setup can consume the capability", async () => {
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "setup",
|
||||
captchaToken: "captcha",
|
||||
})
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.privacyAcknowledgementRequired", status: 400 });
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "setup",
|
||||
captchaToken: "captcha",
|
||||
privacyNoticeAcknowledged: true,
|
||||
privacyNoticeUrl: "https://stale.example.test/privacy",
|
||||
})
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.privacyNoticeChanged", status: 400 });
|
||||
|
||||
expect(mocks.resolveToken).not.toHaveBeenCalled();
|
||||
expect(mocks.consumeToken).not.toHaveBeenCalled();
|
||||
expect(mocks.createSessionInTransaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the canonical password policy and leaves the capability untouched when it fails", async () => {
|
||||
mocks.validatePassword.mockResolvedValue({
|
||||
valid: false,
|
||||
errors: [{ code: "auth.password.errors.missingDigit" }],
|
||||
});
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "setup",
|
||||
captchaToken: "captcha",
|
||||
...privacyAcknowledgement,
|
||||
password: "Weak-but-long-password",
|
||||
passwordConfirmation: "Weak-but-long-password",
|
||||
})
|
||||
).resolves.toEqual({ ok: false, errorKey: "customerPortal.auth.errors.passwordPolicy", status: 400 });
|
||||
expect(mocks.validatePassword).toHaveBeenCalledWith("Weak-but-long-password", { email: user.emailNormalized });
|
||||
expect(mocks.hashPassword).not.toHaveBeenCalled();
|
||||
expect(mocks.consumeToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("revokes existing sessions and remaining capabilities during password reset before issuing the replacement session", async () => {
|
||||
const updateUser = vi.fn().mockResolvedValue({ count: 1 });
|
||||
const revokeSessions = vi.fn().mockResolvedValue({ count: 2 });
|
||||
const revokeTokens = vi.fn().mockResolvedValue({ count: 1 });
|
||||
const tx = {
|
||||
portalUser: { updateMany: updateUser },
|
||||
portalSession: { updateMany: revokeSessions },
|
||||
portalToken: { updateMany: revokeTokens },
|
||||
};
|
||||
mocks.consumeToken.mockImplementation(async (_token, _purpose, _requestedIpHash, effect) =>
|
||||
effect(tx, { tenantId: user.tenantId, portalId: user.portalId, portalUserId: user.portalUserId, portalTokenId: "token_1" })
|
||||
);
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose: "reset_password",
|
||||
captchaToken: "captcha",
|
||||
password: "a-new-secure-password",
|
||||
passwordConfirmation: "a-new-secure-password",
|
||||
})
|
||||
).resolves.toMatchObject({ ok: true, kind: "session" });
|
||||
|
||||
expect(revokeSessions).toHaveBeenCalledWith({
|
||||
where: { tenantId: user.tenantId, portalUserId: user.portalUserId, revokedAt: null },
|
||||
data: { revokedAt: expect.any(Date) },
|
||||
});
|
||||
expect(revokeTokens).toHaveBeenCalledWith({
|
||||
where: { tenantId: user.tenantId, portalUserId: user.portalUserId, consumedAt: null, revokedAt: null },
|
||||
data: { revokedAt: expect.any(Date) },
|
||||
});
|
||||
expect(mocks.createSessionInTransaction).toHaveBeenCalledAfter(revokeSessions);
|
||||
expect(mocks.createSessionInTransaction).toHaveBeenCalledAfter(revokeTokens);
|
||||
expect(mocks.createSessionInTransaction).toHaveBeenCalledWith(
|
||||
tx,
|
||||
expect.objectContaining({ portalUserId: user.portalUserId }),
|
||||
expect.objectContaining({ audit: { action: PORTAL_AUDIT_ACTIONS.passwordReset, requestId: "portal-auth-request-1" } })
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["magic_link", PORTAL_AUDIT_ACTIONS.magicLinkLogin],
|
||||
["verify_email", PORTAL_AUDIT_ACTIONS.emailVerified],
|
||||
] as const)("attaches the semantic %s success audit to session creation", async (purpose, action) => {
|
||||
const tx = { portalUser: { updateMany: vi.fn().mockResolvedValue({ count: 1 }) } };
|
||||
mocks.consumeToken.mockImplementation(async (_token, _purpose, _requestedIpHash, effect) =>
|
||||
effect(tx, { tenantId: user.tenantId, portalId: user.portalId, portalUserId: user.portalUserId, portalTokenId: "token_1" })
|
||||
);
|
||||
|
||||
await expect(
|
||||
consumePortalCapability({
|
||||
request,
|
||||
tenant,
|
||||
rawToken: "t".repeat(43),
|
||||
purpose,
|
||||
captchaToken: "captcha",
|
||||
})
|
||||
).resolves.toMatchObject({ ok: true, kind: "session" });
|
||||
|
||||
expect(mocks.createSessionInTransaction).toHaveBeenCalledWith(
|
||||
tx,
|
||||
expect.objectContaining({ portalUserId: user.portalUserId }),
|
||||
expect.objectContaining({ audit: { action, requestId: "portal-auth-request-1" } })
|
||||
);
|
||||
});
|
||||
});
|
||||
+606
@@ -0,0 +1,606 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
import { getSecret, resolveCaptchaConfig, verifyCaptchaToken } from "@hivegrid/captcha";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { buildBrand, renderTransactionalEmail } from "@hivegrid/mail";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
|
||||
import { getMailTranslator, type MailTranslator } from "~/locale/mail-translator.server";
|
||||
import { hashPassword, verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
import { validatePassword } from "~/services/auth/password-policy.server";
|
||||
import { getTrustedClientIp } from "~/utils/server/IpUtils";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { localizedMailChrome } from "~/modules/emails/utils/LocalizedMailChrome";
|
||||
|
||||
import {
|
||||
checkPortalAuthRateLimit,
|
||||
clearPortalPasswordFailures,
|
||||
isPortalPasswordLocked,
|
||||
recordPortalPasswordFailure,
|
||||
type PortalAuthThrottleAction,
|
||||
} from "./portal-auth-rate-limit.server";
|
||||
import {
|
||||
auditPortalSetupCapabilityDenial,
|
||||
consumePortalAuthToken,
|
||||
createPortalSession,
|
||||
createPortalSessionInTransaction,
|
||||
issuePortalAuthToken,
|
||||
resolvePortalToken,
|
||||
resolvePortalUserByEmail,
|
||||
type PortalTenantResolution,
|
||||
type PortalUserResolution,
|
||||
} from "./portal-data.server";
|
||||
import { PORTAL_AUDIT_ACTIONS, portalAuditRequestId, type PortalSessionAuditAction } from "./portal-audit.server";
|
||||
import { normalizePortalEmail, PORTAL_AUTH_TOKEN_TTL_MS, waitForPortalAuthResponseFloor, type PortalAuthTokenPurpose } from "./portal-auth-token.server";
|
||||
import { portalPublicPath, requireTrustedPortalOrigin, type TrustedPortalOrigin } from "./portal-origin.server";
|
||||
|
||||
const portalAuthLogger = createScopedLogger("customer-portal.auth");
|
||||
const PORTAL_AUTH_RESPONSE_FLOOR_MS = 1200;
|
||||
const PORTAL_DUMMY_PASSWORD_HASH = "$argon2id$v=19$m=19456,t=2,p=1$CGZ841jS/Rerhh41+cREiw$piaCzFMbzHjq946K2t0iN7iMI/389iUpLNm2HROGO4Y";
|
||||
|
||||
export type PortalAuthFailure = { readonly ok: false; readonly errorKey: string; readonly status: 400 | 429 | 503 };
|
||||
export type PortalAuthSessionSuccess = {
|
||||
readonly ok: true;
|
||||
readonly kind: "session";
|
||||
readonly rawSessionToken: string;
|
||||
readonly expiresAt: Date;
|
||||
};
|
||||
export type PortalAuthSentSuccess = { readonly ok: true; readonly kind: "sent" };
|
||||
export type PortalAuthResult = PortalAuthFailure | PortalAuthSessionSuccess | PortalAuthSentSuccess;
|
||||
|
||||
export async function requestPortalSignInLink(input: {
|
||||
readonly request: Request;
|
||||
readonly tenant: PortalTenantResolution;
|
||||
readonly email: string;
|
||||
readonly captchaToken: string | null;
|
||||
readonly continuePath?: string | null;
|
||||
}): Promise<PortalAuthResult> {
|
||||
const startedAt = Date.now();
|
||||
const email = safeNormalizeEmail(input.email);
|
||||
const guard = await guardPortalAuthMutation({
|
||||
request: input.request,
|
||||
tenantSlug: input.tenant.tenantSlug,
|
||||
action: "magic-link",
|
||||
identifier: email,
|
||||
captchaToken: input.captchaToken,
|
||||
});
|
||||
if (guard) return guard;
|
||||
|
||||
try {
|
||||
const user = email ? await resolvePortalUserByEmail(input.tenant.tenantSlug, email) : null;
|
||||
if (user?.status === "active") {
|
||||
const purpose = resolveSignInPurpose(user);
|
||||
const token = await issuePortalAuthToken(user, purpose, hashPortalClientIp(input.request));
|
||||
await sendPortalAuthMail({
|
||||
tenant: input.tenant,
|
||||
user,
|
||||
purpose,
|
||||
rawToken: token.rawToken,
|
||||
continuePath: input.continuePath,
|
||||
origin: requireTrustedPortalOrigin(input.request, input.tenant.tenantSlug),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
portalAuthLogger.error(
|
||||
{ event: "customer_portal.auth.link_issue_failed", errorName: error instanceof Error ? error.name : "UnknownError" },
|
||||
"Portal auth link issuance failed"
|
||||
);
|
||||
} finally {
|
||||
await waitForPortalAuthResponseFloor(startedAt, PORTAL_AUTH_RESPONSE_FLOOR_MS);
|
||||
}
|
||||
return { ok: true, kind: "sent" };
|
||||
}
|
||||
|
||||
export async function requestPortalPasswordReset(input: {
|
||||
readonly request: Request;
|
||||
readonly tenant: PortalTenantResolution;
|
||||
readonly email: string;
|
||||
readonly captchaToken: string | null;
|
||||
}): Promise<PortalAuthResult> {
|
||||
const startedAt = Date.now();
|
||||
const email = safeNormalizeEmail(input.email);
|
||||
const guard = await guardPortalAuthMutation({
|
||||
request: input.request,
|
||||
tenantSlug: input.tenant.tenantSlug,
|
||||
action: "forgot-password",
|
||||
identifier: email,
|
||||
captchaToken: input.captchaToken,
|
||||
});
|
||||
if (guard) return guard;
|
||||
|
||||
try {
|
||||
const user = email ? await resolvePortalUserByEmail(input.tenant.tenantSlug, email) : null;
|
||||
if (user?.status === "active") {
|
||||
const token = await issuePortalAuthToken(user, "reset_password", hashPortalClientIp(input.request));
|
||||
await sendPortalAuthMail({
|
||||
tenant: input.tenant,
|
||||
user,
|
||||
purpose: "reset_password",
|
||||
rawToken: token.rawToken,
|
||||
origin: requireTrustedPortalOrigin(input.request, input.tenant.tenantSlug),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
portalAuthLogger.error(
|
||||
{ event: "customer_portal.auth.reset_issue_failed", errorName: error instanceof Error ? error.name : "UnknownError" },
|
||||
"Portal password reset issuance failed"
|
||||
);
|
||||
} finally {
|
||||
await waitForPortalAuthResponseFloor(startedAt, PORTAL_AUTH_RESPONSE_FLOOR_MS);
|
||||
}
|
||||
return { ok: true, kind: "sent" };
|
||||
}
|
||||
|
||||
export async function signInPortalWithPassword(input: {
|
||||
readonly request: Request;
|
||||
readonly tenant: PortalTenantResolution;
|
||||
readonly email: string;
|
||||
readonly password: string;
|
||||
readonly captchaToken: string | null;
|
||||
}): Promise<PortalAuthResult> {
|
||||
const startedAt = Date.now();
|
||||
const email = safeNormalizeEmail(input.email);
|
||||
const guard = await guardPortalAuthMutation({
|
||||
request: input.request,
|
||||
tenantSlug: input.tenant.tenantSlug,
|
||||
action: "login",
|
||||
identifier: email,
|
||||
captchaToken: input.captchaToken,
|
||||
});
|
||||
if (guard) return guard;
|
||||
|
||||
try {
|
||||
const secret = loadRequiredWebConfig().portalSessionSecret;
|
||||
if (!secret) return { ok: false, errorKey: "customerPortal.auth.errors.unavailable", status: 503 };
|
||||
const locked = email ? await isPortalPasswordLocked({ secret, tenantSlug: input.tenant.tenantSlug, identifier: email }) : false;
|
||||
const user = email ? await resolvePortalUserByEmail(input.tenant.tenantSlug, email) : null;
|
||||
const verified = await verifyPassword(input.password, user?.passwordHash ?? PORTAL_DUMMY_PASSWORD_HASH);
|
||||
const mayLogin = Boolean(
|
||||
user && user.status === "active" && user.passwordHash && verified.valid && (!user.authRequireEmailVerification || user.emailVerifiedAt)
|
||||
);
|
||||
if (!email || locked || !user || !mayLogin) {
|
||||
if (email && !locked) {
|
||||
await recordPortalPasswordFailure({ secret, tenantSlug: input.tenant.tenantSlug, identifier: email });
|
||||
}
|
||||
return invalidCredentials();
|
||||
}
|
||||
|
||||
const cleared = await clearPortalPasswordFailures({ secret, tenantSlug: input.tenant.tenantSlug, identifier: email });
|
||||
if (!cleared) return { ok: false, errorKey: "customerPortal.auth.errors.unavailable", status: 503 };
|
||||
|
||||
if (verified.rehashedHash) {
|
||||
const { runWithPortalRlsContext } = await import("@hivegrid/db/rls-context.server");
|
||||
const { getWriteDbClient } = await import("@hivegrid/db/client.server");
|
||||
await runWithPortalRlsContext(user, () =>
|
||||
getWriteDbClient().portalUser.updateMany({
|
||||
where: { id: user.portalUserId, tenantId: user.tenantId },
|
||||
data: { passwordHash: verified.rehashedHash },
|
||||
})
|
||||
);
|
||||
}
|
||||
const session = await createPortalSession(user, portalSessionMetadata(input.request, input.tenant.tenantSlug, PORTAL_AUDIT_ACTIONS.passwordLogin));
|
||||
return { ok: true, kind: "session", rawSessionToken: session.rawToken, expiresAt: session.expiresAt };
|
||||
} finally {
|
||||
await waitForPortalAuthResponseFloor(startedAt, PORTAL_AUTH_RESPONSE_FLOOR_MS);
|
||||
}
|
||||
}
|
||||
|
||||
export async function consumePortalCapability(input: {
|
||||
readonly request: Request;
|
||||
readonly tenant: PortalTenantResolution;
|
||||
readonly rawToken: string;
|
||||
readonly purpose: PortalAuthTokenPurpose;
|
||||
readonly captchaToken: string | null;
|
||||
readonly password?: string;
|
||||
readonly passwordConfirmation?: string;
|
||||
readonly privacyNoticeAcknowledged?: boolean;
|
||||
readonly privacyNoticeUrl?: string;
|
||||
}): Promise<PortalAuthResult> {
|
||||
const guard = await guardPortalAuthMutation({
|
||||
request: input.request,
|
||||
tenantSlug: input.tenant.tenantSlug,
|
||||
action: throttleActionForPurpose(input.purpose),
|
||||
captchaToken: input.captchaToken,
|
||||
});
|
||||
if (guard) return guard;
|
||||
const requestedIpHash = hashPortalClientIp(input.request);
|
||||
|
||||
const privacyAcknowledgement =
|
||||
input.purpose === "setup"
|
||||
? validatePrivacyAcknowledgement({
|
||||
acknowledged: input.privacyNoticeAcknowledged,
|
||||
submittedUrl: input.privacyNoticeUrl,
|
||||
canonicalUrl: input.tenant.privacyUrl,
|
||||
})
|
||||
: null;
|
||||
if (privacyAcknowledgement && !privacyAcknowledgement.ok) return privacyAcknowledgement.failure;
|
||||
|
||||
let passwordHash: string | null = null;
|
||||
const passwordRequested = Boolean(input.password || input.passwordConfirmation);
|
||||
if (input.purpose === "reset_password" || (input.purpose === "setup" && passwordRequested)) {
|
||||
if (!input.password || input.password !== input.passwordConfirmation) {
|
||||
return { ok: false, errorKey: "customerPortal.auth.errors.passwordPolicy", status: 400 };
|
||||
}
|
||||
const tokenIdentity = await resolvePortalToken(input.rawToken, input.purpose, requestedIpHash);
|
||||
if (!tokenIdentity || tokenIdentity.tenantId !== input.tenant.tenantId || tokenIdentity.portalId !== input.tenant.portalId) {
|
||||
if (input.purpose === "setup") await auditDeniedPortalSetupCapability(input.tenant);
|
||||
return { ok: false, errorKey: "customerPortal.auth.errors.invalidToken", status: 400 };
|
||||
}
|
||||
const passwordPolicy = await validatePassword(input.password, { email: tokenIdentity.emailNormalized });
|
||||
if (!passwordPolicy.valid) {
|
||||
return { ok: false, errorKey: "customerPortal.auth.errors.passwordPolicy", status: 400 };
|
||||
}
|
||||
if (passwordPolicy.hibpBypassed) {
|
||||
portalAuthLogger.warn?.(
|
||||
{ event: "customer_portal.auth.password_hibp_bypassed", tenantId: input.tenant.tenantId },
|
||||
"Portal password breach check was unavailable"
|
||||
);
|
||||
}
|
||||
passwordHash = await hashPassword(input.password);
|
||||
}
|
||||
const session = await consumePortalAuthToken(
|
||||
input.rawToken,
|
||||
input.purpose,
|
||||
requestedIpHash,
|
||||
async (tx, identity) => {
|
||||
await applyPortalCapability(tx, identity, input.purpose, passwordHash, privacyAcknowledgement?.ok ? privacyAcknowledgement.value : null);
|
||||
return createPortalSessionInTransaction(
|
||||
tx,
|
||||
identity,
|
||||
portalSessionMetadata(input.request, input.tenant.tenantSlug, auditActionForPurpose(input.purpose))
|
||||
);
|
||||
},
|
||||
{ tenantId: input.tenant.tenantId, portalId: input.tenant.portalId }
|
||||
);
|
||||
if (!session) {
|
||||
if (input.purpose === "setup") await auditDeniedPortalSetupCapability(input.tenant);
|
||||
return { ok: false, errorKey: "customerPortal.auth.errors.invalidToken", status: 400 };
|
||||
}
|
||||
return { ok: true, kind: "session", rawSessionToken: session.rawToken, expiresAt: session.expiresAt };
|
||||
}
|
||||
|
||||
async function auditDeniedPortalSetupCapability(tenant: Pick<PortalTenantResolution, "tenantId" | "portalId">): Promise<void> {
|
||||
try {
|
||||
await auditPortalSetupCapabilityDenial({
|
||||
tenantId: tenant.tenantId,
|
||||
portalId: tenant.portalId,
|
||||
});
|
||||
} catch (error) {
|
||||
portalAuthLogger.error(
|
||||
{
|
||||
event: "customer_portal.auth.setup_denial_audit_failed",
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
},
|
||||
"Portal setup denial audit could not be appended"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function applyPortalCapability(
|
||||
tx: Prisma.TransactionClient,
|
||||
identity: { readonly tenantId: string; readonly portalUserId: string },
|
||||
purpose: PortalAuthTokenPurpose,
|
||||
passwordHash: string | null,
|
||||
privacyAcknowledgement: { readonly acknowledgedAt: Date; readonly privacyNoticeUrl: string } | null
|
||||
): Promise<void> {
|
||||
if (purpose === "magic_link") return;
|
||||
const common = { emailVerifiedAt: new Date(), status: "active" as const };
|
||||
if (purpose === "setup" || purpose === "reset_password") {
|
||||
if (purpose === "reset_password" && !passwordHash) throw new Error("Portal password reset capability requires a hash.");
|
||||
if (purpose === "setup" && !privacyAcknowledgement) throw new Error("Portal setup requires a canonical privacy acknowledgement.");
|
||||
await tx.portalUser.updateMany({
|
||||
where: { id: identity.portalUserId, tenantId: identity.tenantId },
|
||||
data: {
|
||||
...common,
|
||||
...(passwordHash ? { passwordHash } : {}),
|
||||
...(purpose === "setup" && privacyAcknowledgement
|
||||
? {
|
||||
privacyNoticeAcknowledgedAt: privacyAcknowledgement.acknowledgedAt,
|
||||
privacyNoticeAcknowledgedUrl: privacyAcknowledgement.privacyNoticeUrl,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
if (purpose === "reset_password") {
|
||||
const revokedAt = new Date();
|
||||
await Promise.all([
|
||||
tx.portalSession.updateMany({
|
||||
where: {
|
||||
tenantId: identity.tenantId,
|
||||
portalUserId: identity.portalUserId,
|
||||
revokedAt: null,
|
||||
},
|
||||
data: { revokedAt },
|
||||
}),
|
||||
tx.portalToken.updateMany({
|
||||
where: {
|
||||
tenantId: identity.tenantId,
|
||||
portalUserId: identity.portalUserId,
|
||||
consumedAt: null,
|
||||
revokedAt: null,
|
||||
},
|
||||
data: { revokedAt },
|
||||
}),
|
||||
]);
|
||||
}
|
||||
return;
|
||||
}
|
||||
await tx.portalUser.updateMany({
|
||||
where: { id: identity.portalUserId, tenantId: identity.tenantId },
|
||||
data: common,
|
||||
});
|
||||
}
|
||||
|
||||
function validatePrivacyAcknowledgement(input: {
|
||||
readonly acknowledged: boolean | undefined;
|
||||
readonly submittedUrl: string | undefined;
|
||||
readonly canonicalUrl: string;
|
||||
}):
|
||||
| { readonly ok: true; readonly value: { readonly acknowledgedAt: Date; readonly privacyNoticeUrl: string } }
|
||||
| { readonly ok: false; readonly failure: PortalAuthFailure } {
|
||||
if (input.acknowledged !== true) {
|
||||
return {
|
||||
ok: false,
|
||||
failure: { ok: false, errorKey: "customerPortal.auth.errors.privacyAcknowledgementRequired", status: 400 },
|
||||
};
|
||||
}
|
||||
if (!input.submittedUrl || input.submittedUrl !== input.canonicalUrl) {
|
||||
return {
|
||||
ok: false,
|
||||
failure: { ok: false, errorKey: "customerPortal.auth.errors.privacyNoticeChanged", status: 400 },
|
||||
};
|
||||
}
|
||||
return { ok: true, value: { acknowledgedAt: new Date(), privacyNoticeUrl: input.canonicalUrl } };
|
||||
}
|
||||
|
||||
async function guardPortalAuthMutation(input: {
|
||||
readonly request: Request;
|
||||
readonly tenantSlug: string;
|
||||
readonly action: PortalAuthThrottleAction;
|
||||
readonly identifier?: string | null;
|
||||
readonly captchaToken: string | null;
|
||||
}): Promise<PortalAuthFailure | null> {
|
||||
const config = loadRequiredWebConfig();
|
||||
const secret = config.portalSessionSecret;
|
||||
if (config.runtimeSurface !== "portal" || !secret) {
|
||||
return { ok: false, errorKey: "customerPortal.auth.errors.unavailable", status: 503 };
|
||||
}
|
||||
const rateLimitOptions = {
|
||||
request: input.request,
|
||||
secret,
|
||||
tenantSlug: input.tenantSlug,
|
||||
action: input.action,
|
||||
identifier: input.identifier,
|
||||
limit: input.action === "magic-link" ? 3 : input.action === "login" ? 10 : 5,
|
||||
identifierLimit: input.action === "magic-link" ? 3 : input.action === "login" ? 20 : 10,
|
||||
clientLimit: input.action === "magic-link" ? 10 : 50,
|
||||
windowMs: 15 * 60 * 1000,
|
||||
clientWindowMs: input.action === "magic-link" ? 60 * 60 * 1000 : 15 * 60 * 1000,
|
||||
} as const;
|
||||
const clientRateLimit = await checkPortalAuthRateLimit({ ...rateLimitOptions, scopes: ["client"] });
|
||||
if (!clientRateLimit.allowed) return { ok: false, errorKey: "customerPortal.auth.errors.rateLimited", status: 429 };
|
||||
|
||||
const captcha = resolveCaptchaConfig(process.env);
|
||||
const captchaOk = await verifyCaptchaToken({
|
||||
token: input.captchaToken,
|
||||
sitekey: captcha.sitekeys.login,
|
||||
secret: getSecret(captcha, "login"),
|
||||
instanceUrl: captcha.instanceUrl,
|
||||
provider: captcha.provider,
|
||||
failOpen: captcha.failOpen,
|
||||
logger: portalAuthLogger,
|
||||
});
|
||||
if (!captchaOk) return { ok: false, errorKey: "customerPortal.auth.errors.captcha", status: 400 };
|
||||
|
||||
const identityRateLimit = await checkPortalAuthRateLimit({ ...rateLimitOptions, scopes: ["identifier", "pair"] });
|
||||
return identityRateLimit.allowed ? null : { ok: false, errorKey: "customerPortal.auth.errors.rateLimited", status: 429 };
|
||||
}
|
||||
|
||||
async function sendPortalAuthMail(input: {
|
||||
readonly tenant: PortalTenantResolution;
|
||||
readonly user: PortalUserResolution;
|
||||
readonly purpose: PortalAuthTokenPurpose;
|
||||
readonly rawToken: string;
|
||||
readonly continuePath?: string | null;
|
||||
readonly origin: TrustedPortalOrigin;
|
||||
}): Promise<void> {
|
||||
const route = routeForPurpose(input.purpose, input.rawToken);
|
||||
const continueQuery = buildPortalContinueQuery(input.tenant.tenantSlug, input.continuePath, input.origin.customHost);
|
||||
const actionUrl = `${input.origin.origin}${portalPublicPath(input.origin, route)}${continueQuery}`;
|
||||
const recipientName = input.user.firstName.trim() || undefined;
|
||||
const brand = buildBrand({ productName: input.tenant.portalTitle });
|
||||
const { t, locale } = await getMailTranslator(input.user.locale);
|
||||
const expiresInMinutes = PORTAL_AUTH_TOKEN_TTL_MS[input.purpose] / 60_000;
|
||||
const copy = portalAuthMailCopy({
|
||||
t,
|
||||
purpose: input.purpose,
|
||||
recipientName,
|
||||
productName: input.tenant.portalTitle,
|
||||
expiresInMinutes,
|
||||
});
|
||||
const isReset = input.purpose === "reset_password";
|
||||
const rendered = isReset
|
||||
? renderTransactionalEmail("password-reset", {
|
||||
brand,
|
||||
...localizedMailChrome(t, locale),
|
||||
recipientName,
|
||||
actionUrl,
|
||||
subject: copy.subject,
|
||||
eyebrow: copy.eyebrow,
|
||||
title: copy.title,
|
||||
intro: copy.intro,
|
||||
actionLabel: copy.actionLabel,
|
||||
outro: copy.outro,
|
||||
signoffThanks: copy.signoffThanks,
|
||||
})
|
||||
: renderTransactionalEmail("magic-link", {
|
||||
brand,
|
||||
...localizedMailChrome(t, locale),
|
||||
recipientName,
|
||||
actionUrl,
|
||||
expiresInMinutes,
|
||||
subject: copy.subject,
|
||||
previewText: copy.previewText,
|
||||
eyebrow: copy.eyebrow,
|
||||
title: copy.title,
|
||||
intro: copy.intro,
|
||||
actionLabel: copy.actionLabel,
|
||||
outro: copy.outro,
|
||||
expiresText: copy.expiresText,
|
||||
signoffThanks: copy.signoffThanks,
|
||||
});
|
||||
await sendEmailMailjet({
|
||||
data: {
|
||||
to: input.user.email,
|
||||
subject: copy.subject,
|
||||
body: rendered.html,
|
||||
text: rendered.text,
|
||||
alias: isReset ? "password-reset" : "magic-link",
|
||||
source: "portal-auth-mail",
|
||||
tenantId: input.tenant.tenantId,
|
||||
priorityOverride: "critical",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
type PortalAuthMailCopy = {
|
||||
readonly subject: string;
|
||||
readonly previewText?: string;
|
||||
readonly eyebrow: string;
|
||||
readonly title: string;
|
||||
readonly intro: string;
|
||||
readonly actionLabel: string;
|
||||
readonly outro: string;
|
||||
readonly expiresText?: string;
|
||||
readonly signoffThanks: string;
|
||||
};
|
||||
|
||||
function portalAuthMailCopy(input: {
|
||||
readonly t: MailTranslator;
|
||||
readonly purpose: PortalAuthTokenPurpose;
|
||||
readonly recipientName?: string;
|
||||
readonly productName: string;
|
||||
readonly expiresInMinutes: number;
|
||||
}): PortalAuthMailCopy {
|
||||
const vars = {
|
||||
productName: input.productName,
|
||||
name: input.recipientName,
|
||||
expiresInMinutes: input.expiresInMinutes,
|
||||
expiresInHours: input.expiresInMinutes / 60,
|
||||
expiresInDays: input.expiresInMinutes / (60 * 24),
|
||||
};
|
||||
const signoffThanks = input.t("common.signoff.thanks");
|
||||
|
||||
if (input.purpose === "magic_link") {
|
||||
return {
|
||||
subject: input.t("customerPortalAuth.magicLink.subject", vars),
|
||||
previewText: input.t("customerPortalAuth.magicLink.previewText", vars),
|
||||
eyebrow: input.t("customerPortalAuth.magicLink.eyebrow", vars),
|
||||
title: input.recipientName ? input.t("customerPortalAuth.magicLink.title_named", vars) : input.t("customerPortalAuth.magicLink.title", vars),
|
||||
intro: input.t("customerPortalAuth.magicLink.intro", vars),
|
||||
actionLabel: input.t("customerPortalAuth.magicLink.actionLabel", vars),
|
||||
outro: input.t("customerPortalAuth.magicLink.outro", vars),
|
||||
expiresText: input.t("customerPortalAuth.magicLink.expiresText", vars),
|
||||
signoffThanks,
|
||||
};
|
||||
}
|
||||
if (input.purpose === "setup") {
|
||||
return {
|
||||
subject: input.t("customerPortalAuth.setup.subject", vars),
|
||||
previewText: input.t("customerPortalAuth.setup.previewText", vars),
|
||||
eyebrow: input.t("customerPortalAuth.setup.eyebrow", vars),
|
||||
title: input.recipientName ? input.t("customerPortalAuth.setup.title_named", vars) : input.t("customerPortalAuth.setup.title", vars),
|
||||
intro: input.t("customerPortalAuth.setup.intro", vars),
|
||||
actionLabel: input.t("customerPortalAuth.setup.actionLabel", vars),
|
||||
outro: input.t("customerPortalAuth.setup.outro", vars),
|
||||
expiresText: input.t("customerPortalAuth.setup.expiresText", vars),
|
||||
signoffThanks,
|
||||
};
|
||||
}
|
||||
if (input.purpose === "verify_email") {
|
||||
return {
|
||||
subject: input.t("customerPortalAuth.verifyEmail.subject", vars),
|
||||
previewText: input.t("customerPortalAuth.verifyEmail.previewText", vars),
|
||||
eyebrow: input.t("customerPortalAuth.verifyEmail.eyebrow", vars),
|
||||
title: input.recipientName ? input.t("customerPortalAuth.verifyEmail.title_named", vars) : input.t("customerPortalAuth.verifyEmail.title", vars),
|
||||
intro: input.t("customerPortalAuth.verifyEmail.intro", vars),
|
||||
actionLabel: input.t("customerPortalAuth.verifyEmail.actionLabel", vars),
|
||||
outro: input.t("customerPortalAuth.verifyEmail.outro", vars),
|
||||
expiresText: input.t("customerPortalAuth.verifyEmail.expiresText", vars),
|
||||
signoffThanks,
|
||||
};
|
||||
}
|
||||
return {
|
||||
subject: input.t("customerPortalAuth.resetPassword.subject", vars),
|
||||
eyebrow: input.t("customerPortalAuth.resetPassword.eyebrow", vars),
|
||||
title: input.recipientName ? input.t("customerPortalAuth.resetPassword.title_named", vars) : input.t("customerPortalAuth.resetPassword.title", vars),
|
||||
intro: input.t("customerPortalAuth.resetPassword.intro", vars),
|
||||
actionLabel: input.t("customerPortalAuth.resetPassword.actionLabel", vars),
|
||||
outro: input.t("customerPortalAuth.resetPassword.outro", vars),
|
||||
signoffThanks,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveSignInPurpose(user: PortalUserResolution): PortalAuthTokenPurpose {
|
||||
if (user.authRequireEmailVerification && !user.emailVerifiedAt) return "verify_email";
|
||||
return "magic_link";
|
||||
}
|
||||
|
||||
function routeForPurpose(purpose: PortalAuthTokenPurpose, rawToken: string): string {
|
||||
const encoded = encodeURIComponent(rawToken);
|
||||
if (purpose === "magic_link") return `login/magic/${encoded}`;
|
||||
if (purpose === "setup") return `setup/${encoded}`;
|
||||
if (purpose === "verify_email") return `verify-email/${encoded}`;
|
||||
return `reset-password/${encoded}`;
|
||||
}
|
||||
|
||||
function buildPortalContinueQuery(tenantSlug: string, continuePath: string | null | undefined, customHost: boolean): string {
|
||||
if (!continuePath) return "";
|
||||
const escapedTenant = tenantSlug.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
||||
const pattern = customHost ? /^\/projects\/[A-Za-z0-9_-]{1,128}$/u : new RegExp(`^/${escapedTenant}/projects/[A-Za-z0-9_-]{1,128}$`, "u");
|
||||
if (!pattern.test(continuePath)) return "";
|
||||
return `?continue=${encodeURIComponent(continuePath)}`;
|
||||
}
|
||||
|
||||
function throttleActionForPurpose(purpose: PortalAuthTokenPurpose): PortalAuthThrottleAction {
|
||||
if (purpose === "magic_link") return "magic-link";
|
||||
if (purpose === "verify_email") return "verify-email";
|
||||
if (purpose === "reset_password") return "reset-password";
|
||||
return "setup";
|
||||
}
|
||||
|
||||
function portalSessionMetadata(request: Request, tenantSlug: string, action: PortalSessionAuditAction) {
|
||||
return {
|
||||
origin: requireTrustedPortalOrigin(request, tenantSlug).origin,
|
||||
userAgent: request.headers.get("user-agent"),
|
||||
ipAddressHash: hashPortalClientIp(request),
|
||||
audit: { action, requestId: portalAuditRequestId(request) },
|
||||
};
|
||||
}
|
||||
|
||||
function auditActionForPurpose(purpose: PortalAuthTokenPurpose): PortalSessionAuditAction {
|
||||
if (purpose === "magic_link") return PORTAL_AUDIT_ACTIONS.magicLinkLogin;
|
||||
if (purpose === "setup") return PORTAL_AUDIT_ACTIONS.setupCompleted;
|
||||
if (purpose === "verify_email") return PORTAL_AUDIT_ACTIONS.emailVerified;
|
||||
return PORTAL_AUDIT_ACTIONS.passwordReset;
|
||||
}
|
||||
|
||||
function hashPortalClientIp(request: Request): string {
|
||||
const secret = loadRequiredWebConfig().portalSessionSecret;
|
||||
if (!secret) throw new Error("Portal signing secret is unavailable.");
|
||||
return createHmac("sha256", secret)
|
||||
.update(getTrustedClientIp(request) || "unknown")
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
function safeNormalizeEmail(value: string): string | null {
|
||||
try {
|
||||
return normalizePortalEmail(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function invalidCredentials(): PortalAuthFailure {
|
||||
return { ok: false, errorKey: "customerPortal.auth.errors.invalidCredentials", status: 400 };
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
__resetPortalAuthRateLimitStoreForTests,
|
||||
__setPortalAuthRateLimitStoreForTests,
|
||||
checkPortalAuthRateLimit,
|
||||
clearPortalPasswordFailures,
|
||||
getPortalAuthRateLimitKey,
|
||||
isPortalPasswordLocked,
|
||||
recordPortalPasswordFailure,
|
||||
} from "./portal-auth-rate-limit.server";
|
||||
|
||||
const SECRET = "portal-only-rate-limit-secret-at-least-32-bytes";
|
||||
|
||||
describe("portal auth rate limit", () => {
|
||||
let adapter: MemoryAdapter;
|
||||
let nowMs: number;
|
||||
|
||||
beforeEach(() => {
|
||||
nowMs = Date.parse("2026-07-15T10:00:00.000Z");
|
||||
adapter = new MemoryAdapter({ now: () => nowMs });
|
||||
__setPortalAuthRateLimitStoreForTests(createSharedStore({ namespace: "portal-auth-rate-test", adapter }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__resetPortalAuthRateLimitStoreForTests();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("uses a portal-only pseudonymous tenant/action/client/identifier key", () => {
|
||||
const request = new Request("https://portal.hivegrid.de/acme/login", { headers: { "cf-connecting-ip": "203.0.113.10" } });
|
||||
const key = getPortalAuthRateLimitKey({ request, secret: SECRET, tenantSlug: "acme", action: "login", identifier: " Customer@Example.com " });
|
||||
expect(key).toMatch(/^[a-f0-9]{64}$/u);
|
||||
expect(key).not.toContain("customer@example.com");
|
||||
expect(key).not.toContain("203.0.113.10");
|
||||
expect(getPortalAuthRateLimitKey({ request, secret: SECRET, tenantSlug: "other", action: "login", identifier: "customer@example.com" })).not.toBe(key);
|
||||
});
|
||||
|
||||
it("allows exactly the configured pair limit", async () => {
|
||||
const options = {
|
||||
request: new Request("https://portal.hivegrid.de/acme/login", { headers: { "cf-connecting-ip": "203.0.113.10" } }),
|
||||
secret: SECRET,
|
||||
tenantSlug: "acme",
|
||||
action: "login" as const,
|
||||
identifier: "customer@example.com",
|
||||
limit: 2,
|
||||
windowMs: 30_000,
|
||||
};
|
||||
await expect(checkPortalAuthRateLimit(options)).resolves.toEqual({ allowed: true });
|
||||
await expect(checkPortalAuthRateLimit(options)).resolves.toEqual({ allowed: true });
|
||||
await expect(checkPortalAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
|
||||
});
|
||||
|
||||
it("keeps raw identifiers out of the Redis keyspace", async () => {
|
||||
const identifier = "enumerable-customer@example.com";
|
||||
await checkPortalAuthRateLimit({
|
||||
request: new Request("https://portal.hivegrid.de/acme/login"),
|
||||
secret: SECRET,
|
||||
tenantSlug: "acme",
|
||||
action: "magic-link",
|
||||
identifier,
|
||||
limit: 1,
|
||||
windowMs: 30_000,
|
||||
});
|
||||
const keys = [];
|
||||
for await (const key of adapter.scan("*")) keys.push(key);
|
||||
expect(JSON.stringify(keys)).not.toContain(identifier);
|
||||
expect(JSON.stringify(keys)).toContain("portal-auth-v1");
|
||||
});
|
||||
|
||||
it("can consume only the client bucket before captcha verification", async () => {
|
||||
await expect(
|
||||
checkPortalAuthRateLimit({
|
||||
request: new Request("https://portal.hivegrid.de/acme/login", { headers: { "cf-connecting-ip": "203.0.113.10" } }),
|
||||
secret: SECRET,
|
||||
tenantSlug: "acme",
|
||||
action: "magic-link",
|
||||
identifier: "customer@example.com",
|
||||
limit: 3,
|
||||
identifierLimit: 3,
|
||||
clientLimit: 10,
|
||||
windowMs: 15 * 60 * 1000,
|
||||
clientWindowMs: 60 * 60 * 1000,
|
||||
scopes: ["client"],
|
||||
})
|
||||
).resolves.toEqual({ allowed: true });
|
||||
|
||||
const keys = [];
|
||||
for await (const key of adapter.scan("*")) keys.push(key);
|
||||
expect(keys).toHaveLength(1);
|
||||
expect(keys[0]).toContain("portal-auth-v1-client");
|
||||
expect(keys[0]).not.toContain("portal-auth-v1-identifier");
|
||||
expect(keys[0]).not.toContain("portal-auth-v1-pair");
|
||||
});
|
||||
|
||||
it("allows exactly three magic-link requests per email in 15 minutes across client IPs", async () => {
|
||||
const base = {
|
||||
secret: SECRET,
|
||||
tenantSlug: "acme",
|
||||
action: "magic-link" as const,
|
||||
identifier: "customer@example.com",
|
||||
limit: 3,
|
||||
identifierLimit: 3,
|
||||
clientLimit: 10,
|
||||
windowMs: 15 * 60 * 1000,
|
||||
clientWindowMs: 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
for (let index = 1; index <= 3; index += 1) {
|
||||
await expect(
|
||||
checkPortalAuthRateLimit({
|
||||
...base,
|
||||
request: new Request("https://portal.hivegrid.de/acme/login", { headers: { "cf-connecting-ip": `203.0.113.${index}` } }),
|
||||
})
|
||||
).resolves.toEqual({ allowed: true });
|
||||
}
|
||||
await expect(
|
||||
checkPortalAuthRateLimit({
|
||||
...base,
|
||||
request: new Request("https://portal.hivegrid.de/acme/login", { headers: { "cf-connecting-ip": "203.0.113.4" } }),
|
||||
})
|
||||
).resolves.toEqual({ allowed: false, retryAfterSeconds: 15 * 60 });
|
||||
});
|
||||
|
||||
it("allows exactly ten magic-link requests per IP in one hour across emails", async () => {
|
||||
const request = new Request("https://portal.hivegrid.de/acme/login", { headers: { "cf-connecting-ip": "203.0.113.20" } });
|
||||
const base = {
|
||||
request,
|
||||
secret: SECRET,
|
||||
tenantSlug: "acme",
|
||||
action: "magic-link" as const,
|
||||
limit: 3,
|
||||
identifierLimit: 3,
|
||||
clientLimit: 10,
|
||||
windowMs: 15 * 60 * 1000,
|
||||
clientWindowMs: 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
for (let index = 1; index <= 10; index += 1) {
|
||||
await expect(checkPortalAuthRateLimit({ ...base, identifier: `customer-${index}@example.com` })).resolves.toEqual({ allowed: true });
|
||||
}
|
||||
await expect(checkPortalAuthRateLimit({ ...base, identifier: "customer-11@example.com" })).resolves.toEqual({
|
||||
allowed: false,
|
||||
retryAfterSeconds: 60 * 60,
|
||||
});
|
||||
});
|
||||
|
||||
it("locks on the fifth password failure for 15 minutes and clears after a successful login", async () => {
|
||||
const input = { secret: SECRET, tenantSlug: "acme", identifier: "customer@example.com" };
|
||||
|
||||
for (let index = 1; index <= 4; index += 1) {
|
||||
await expect(recordPortalPasswordFailure(input)).resolves.toBe(false);
|
||||
}
|
||||
await expect(recordPortalPasswordFailure(input)).resolves.toBe(true);
|
||||
await expect(isPortalPasswordLocked(input)).resolves.toBe(true);
|
||||
|
||||
const keys = [];
|
||||
for await (const key of adapter.scan("*")) keys.push(key);
|
||||
expect(JSON.stringify(keys)).not.toContain(input.identifier);
|
||||
|
||||
nowMs += 15 * 60 * 1000 - 1;
|
||||
await expect(isPortalPasswordLocked(input)).resolves.toBe(true);
|
||||
nowMs += 2;
|
||||
await expect(isPortalPasswordLocked(input)).resolves.toBe(false);
|
||||
|
||||
await expect(clearPortalPasswordFailures(input)).resolves.toBe(true);
|
||||
await expect(isPortalPasswordLocked(input)).resolves.toBe(false);
|
||||
await expect(recordPortalPasswordFailure(input)).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it("fails closed when the shared store is unavailable", async () => {
|
||||
vi.spyOn(adapter, "incr").mockRejectedValueOnce(new Error("redis unavailable"));
|
||||
await expect(
|
||||
checkPortalAuthRateLimit({
|
||||
request: new Request("https://portal.hivegrid.de/acme/login"),
|
||||
secret: SECRET,
|
||||
tenantSlug: "acme",
|
||||
action: "login",
|
||||
identifier: "customer@example.com",
|
||||
limit: 2,
|
||||
windowMs: 30_000,
|
||||
})
|
||||
).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
|
||||
});
|
||||
});
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
import { createFixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { getTrustedClientIp } from "~/utils/server/IpUtils";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
export type PortalAuthThrottleAction = "login" | "magic-link" | "forgot-password" | "reset-password" | "setup" | "verify-email";
|
||||
export type PortalAuthThrottleScope = "client" | "identifier" | "pair";
|
||||
|
||||
export type PortalAuthRateLimitOptions = {
|
||||
readonly request: Request;
|
||||
readonly secret: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly action: PortalAuthThrottleAction;
|
||||
readonly identifier?: string | null;
|
||||
readonly limit: number;
|
||||
readonly windowMs: number;
|
||||
readonly pairWindowMs?: number;
|
||||
readonly identifierLimit?: number | null;
|
||||
readonly identifierWindowMs?: number;
|
||||
readonly clientLimit?: number;
|
||||
readonly clientWindowMs?: number;
|
||||
readonly scopes?: readonly PortalAuthThrottleScope[];
|
||||
};
|
||||
|
||||
export type PortalAuthRateLimitResult = { readonly allowed: true } | { readonly allowed: false; readonly retryAfterSeconds: number };
|
||||
|
||||
const MAX_WINDOW_MS = 24 * 60 * 60 * 1000;
|
||||
const MAX_LIMIT = 10_000;
|
||||
const portalRateLimitLogger = createScopedLogger("customer-portal.auth-rate-limit");
|
||||
const PORTAL_PASSWORD_FAILURE_LIMIT = 5;
|
||||
const PORTAL_PASSWORD_LOCKOUT_SECONDS = 15 * 60;
|
||||
let storeFactory: () => SharedStore = () => getSharedStore();
|
||||
|
||||
function normalizeSlug(value: string): string {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!/^[a-z0-9][a-z0-9-]{0,62}$/u.test(normalized)) throw new Error("Portal tenant slug is invalid.");
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizeLimit(value: number): number {
|
||||
if (!Number.isSafeInteger(value) || value < 1 || value > MAX_LIMIT) throw new Error("Portal auth rate-limit maximum is invalid.");
|
||||
return value;
|
||||
}
|
||||
|
||||
function normalizeWindowSeconds(windowMs: number): number {
|
||||
if (!Number.isSafeInteger(windowMs) || windowMs < 1000 || windowMs > MAX_WINDOW_MS) throw new Error("Portal auth rate-limit window is invalid.");
|
||||
return Math.ceil(windowMs / 1000);
|
||||
}
|
||||
|
||||
export function getPortalAuthRateLimitKey(input: {
|
||||
readonly request: Request;
|
||||
readonly secret: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly action: PortalAuthThrottleAction;
|
||||
readonly identifier?: string | null;
|
||||
readonly scope?: PortalAuthThrottleScope;
|
||||
}): string {
|
||||
if (input.secret.length < 32) throw new Error("Portal auth rate-limit secret is invalid.");
|
||||
const scope = input.scope ?? "pair";
|
||||
const client = scope === "identifier" ? "" : getTrustedClientIp(input.request) || "unknown";
|
||||
const identifier = scope === "client" ? "" : input.identifier?.trim().toLowerCase() || "";
|
||||
return createHmac("sha256", input.secret)
|
||||
.update(`portal-auth-v1\0${normalizeSlug(input.tenantSlug)}\0${input.action}\0${scope}\0${client}\0${identifier}`)
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
/**
|
||||
* Portal-only distributed throttling. Its keys and HMAC secret never overlap
|
||||
* with core auth; any Redis/configuration failure denies the request.
|
||||
*/
|
||||
export async function checkPortalAuthRateLimit(options: PortalAuthRateLimitOptions): Promise<PortalAuthRateLimitResult> {
|
||||
const safeRetryAfterSeconds = Math.max(1, Math.ceil(Math.min(Math.max(options.windowMs || 0, 1000), MAX_WINDOW_MS) / 1000));
|
||||
try {
|
||||
const limit = normalizeLimit(options.limit);
|
||||
const clientLimit = normalizeLimit(options.clientLimit ?? Math.min(MAX_LIMIT, limit * 10));
|
||||
const identifierLimit = options.identifierLimit === null ? null : normalizeLimit(options.identifierLimit ?? Math.min(MAX_LIMIT, limit * 3));
|
||||
const pairWindowSeconds = normalizeWindowSeconds(options.pairWindowMs ?? options.windowMs);
|
||||
const clientWindowSeconds = normalizeWindowSeconds(options.clientWindowMs ?? options.windowMs);
|
||||
const identifierWindowSeconds = normalizeWindowSeconds(options.identifierWindowMs ?? options.windowMs);
|
||||
const scopes = normalizeScopes(options.scopes);
|
||||
const keyInput = {
|
||||
request: options.request,
|
||||
secret: options.secret,
|
||||
tenantSlug: options.tenantSlug,
|
||||
action: options.action,
|
||||
identifier: options.identifier,
|
||||
} as const;
|
||||
const store = storeFactory();
|
||||
const decisions: Array<{ decision: { readonly allowed: boolean }; windowSeconds: number }> = [];
|
||||
if (scopes.has("client")) {
|
||||
decisions.push({
|
||||
decision: await createFixedWindowRateLimiter({ store, prefix: "portal-auth-v1-client", windowSeconds: clientWindowSeconds, max: clientLimit }).consume(
|
||||
getPortalAuthRateLimitKey({ ...keyInput, scope: "client" })
|
||||
),
|
||||
windowSeconds: clientWindowSeconds,
|
||||
});
|
||||
}
|
||||
if (scopes.has("identifier") && identifierLimit !== null && options.identifier?.trim()) {
|
||||
decisions.push({
|
||||
decision: await createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "portal-auth-v1-identifier",
|
||||
windowSeconds: identifierWindowSeconds,
|
||||
max: identifierLimit,
|
||||
}).consume(getPortalAuthRateLimitKey({ ...keyInput, scope: "identifier" })),
|
||||
windowSeconds: identifierWindowSeconds,
|
||||
});
|
||||
}
|
||||
if (scopes.has("pair")) {
|
||||
decisions.push({
|
||||
decision: await createFixedWindowRateLimiter({ store, prefix: "portal-auth-v1-pair", windowSeconds: pairWindowSeconds, max: limit }).consume(
|
||||
getPortalAuthRateLimitKey({ ...keyInput, scope: "pair" })
|
||||
),
|
||||
windowSeconds: pairWindowSeconds,
|
||||
});
|
||||
}
|
||||
const denied = decisions.filter(({ decision }) => !decision.allowed);
|
||||
return denied.length === 0 ? { allowed: true } : { allowed: false, retryAfterSeconds: Math.max(...denied.map(({ windowSeconds }) => windowSeconds)) };
|
||||
} catch (error) {
|
||||
portalRateLimitLogger.error(
|
||||
{ event: "customer_portal.auth.rate_limit_unavailable", action: options.action, errorName: error instanceof Error ? error.name : "UnknownError" },
|
||||
"Portal auth rate limit unavailable; request denied"
|
||||
);
|
||||
return { allowed: false, retryAfterSeconds: safeRetryAfterSeconds };
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeScopes(scopes: readonly PortalAuthThrottleScope[] | undefined): ReadonlySet<PortalAuthThrottleScope> {
|
||||
const requested = scopes ?? (["client", "identifier", "pair"] as const);
|
||||
if (requested.length === 0 || requested.some((scope) => scope !== "client" && scope !== "identifier" && scope !== "pair")) {
|
||||
throw new Error("Portal auth rate-limit scopes are invalid.");
|
||||
}
|
||||
return new Set(requested);
|
||||
}
|
||||
|
||||
export async function isPortalPasswordLocked(input: { readonly secret: string; readonly tenantSlug: string; readonly identifier: string }): Promise<boolean> {
|
||||
try {
|
||||
const store = storeFactory();
|
||||
return (await store.get(portalPasswordLockKey(input))) !== null;
|
||||
} catch (error) {
|
||||
logPasswordThrottleFailure("check", error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records password failures only after password verification failed. The fifth
|
||||
* failure starts a 15-minute per-email lock; successful authentication clears
|
||||
* both the failure window and lock marker.
|
||||
*/
|
||||
export async function recordPortalPasswordFailure(input: {
|
||||
readonly secret: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly identifier: string;
|
||||
}): Promise<boolean> {
|
||||
try {
|
||||
const store = storeFactory();
|
||||
const key = portalPasswordFailureKey(input);
|
||||
const decision = await createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "portal-auth-v1-password-failure",
|
||||
windowSeconds: PORTAL_PASSWORD_LOCKOUT_SECONDS,
|
||||
max: PORTAL_PASSWORD_FAILURE_LIMIT,
|
||||
}).consume(key);
|
||||
const locked = !decision.allowed || decision.remaining === 0;
|
||||
if (locked) {
|
||||
await store.set(portalPasswordLockKey(input), "1", { ttlSeconds: PORTAL_PASSWORD_LOCKOUT_SECONDS });
|
||||
}
|
||||
return locked;
|
||||
} catch (error) {
|
||||
logPasswordThrottleFailure("record", error);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearPortalPasswordFailures(input: {
|
||||
readonly secret: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly identifier: string;
|
||||
}): Promise<boolean> {
|
||||
try {
|
||||
const store = storeFactory();
|
||||
const key = portalPasswordFailureKey(input);
|
||||
await Promise.all([
|
||||
createFixedWindowRateLimiter({
|
||||
store,
|
||||
prefix: "portal-auth-v1-password-failure",
|
||||
windowSeconds: PORTAL_PASSWORD_LOCKOUT_SECONDS,
|
||||
max: PORTAL_PASSWORD_FAILURE_LIMIT,
|
||||
}).reset(key),
|
||||
store.del(portalPasswordLockKey(input)),
|
||||
]);
|
||||
return true;
|
||||
} catch (error) {
|
||||
logPasswordThrottleFailure("clear", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function portalPasswordFailureKey(input: { readonly secret: string; readonly tenantSlug: string; readonly identifier: string }): string {
|
||||
return getPortalAuthRateLimitKey({
|
||||
request: new Request("https://portal.invalid"),
|
||||
secret: input.secret,
|
||||
tenantSlug: input.tenantSlug,
|
||||
action: "login",
|
||||
identifier: input.identifier,
|
||||
scope: "identifier",
|
||||
});
|
||||
}
|
||||
|
||||
function portalPasswordLockKey(input: { readonly secret: string; readonly tenantSlug: string; readonly identifier: string }): string {
|
||||
return `portal-auth-v1-password-lock:${portalPasswordFailureKey(input)}`;
|
||||
}
|
||||
|
||||
function logPasswordThrottleFailure(operation: "check" | "record" | "clear", error: unknown): void {
|
||||
portalRateLimitLogger.error(
|
||||
{
|
||||
event: "customer_portal.auth.password_lockout_unavailable",
|
||||
operation,
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
},
|
||||
"Portal password lockout unavailable; request denied"
|
||||
);
|
||||
}
|
||||
|
||||
export function __setPortalAuthRateLimitStoreForTests(store: SharedStore): void {
|
||||
storeFactory = () => store;
|
||||
}
|
||||
|
||||
export function __resetPortalAuthRateLimitStoreForTests(): void {
|
||||
storeFactory = () => getSharedStore();
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createPortalAuthToken,
|
||||
createPortalOpaqueToken,
|
||||
createPortalSessionToken,
|
||||
hashPortalOpaqueToken,
|
||||
normalizePortalEmail,
|
||||
PORTAL_AUTH_TOKEN_TTL_MS,
|
||||
PORTAL_SESSION_INACTIVITY_TTL_MS,
|
||||
PORTAL_SESSION_TTL_MS,
|
||||
waitForPortalAuthResponseFloor,
|
||||
} from "./portal-auth-token.server";
|
||||
|
||||
describe("portal auth token contract", () => {
|
||||
it("persists only a one-way hash of an opaque 256-bit token", () => {
|
||||
const token = createPortalOpaqueToken({ rawToken: "opaque-token-fixture-with-at-least-32-bytes" });
|
||||
expect(token.tokenHash).toBe(hashPortalOpaqueToken(token.rawToken));
|
||||
expect(token.tokenHash).toMatch(/^[a-f0-9]{64}$/);
|
||||
expect(token.tokenHash).not.toContain(token.rawToken);
|
||||
});
|
||||
|
||||
it("rejects entropy budgets below 256 bits", () => {
|
||||
expect(() => createPortalOpaqueToken({ bytes: 31 })).toThrow(/256 bits/);
|
||||
});
|
||||
|
||||
it("uses purpose-bound expiries", () => {
|
||||
expect(PORTAL_AUTH_TOKEN_TTL_MS).toEqual({
|
||||
magic_link: 15 * 60 * 1000,
|
||||
setup: 7 * 24 * 60 * 60 * 1000,
|
||||
verify_email: 24 * 60 * 60 * 1000,
|
||||
reset_password: 60 * 60 * 1000,
|
||||
});
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
for (const [purpose, ttl] of Object.entries(PORTAL_AUTH_TOKEN_TTL_MS)) {
|
||||
const token = createPortalAuthToken(purpose as keyof typeof PORTAL_AUTH_TOKEN_TTL_MS, { now, rawToken: `token-${purpose}` });
|
||||
expect(token.expiresAt.getTime()).toBe(now.getTime() + ttl);
|
||||
expect(token.purpose).toBe(purpose);
|
||||
}
|
||||
});
|
||||
|
||||
it("creates independently hashed server-side session tokens", () => {
|
||||
expect(PORTAL_SESSION_TTL_MS).toBe(30 * 24 * 60 * 60 * 1000);
|
||||
expect(PORTAL_SESSION_INACTIVITY_TTL_MS).toBe(7 * 24 * 60 * 60 * 1000);
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
const session = createPortalSessionToken({ now, rawToken: "portal-session-token" });
|
||||
expect(session.expiresAt.getTime()).toBe(now.getTime() + PORTAL_SESSION_TTL_MS);
|
||||
expect(session.tokenHash).toBe(hashPortalOpaqueToken("portal-session-token"));
|
||||
});
|
||||
|
||||
it("normalizes email without retaining attacker-controlled casing or whitespace", () => {
|
||||
expect(normalizePortalEmail(" Customer@Example.COM ")).toBe("customer@example.com");
|
||||
expect(() => normalizePortalEmail("invalid")).toThrow(/invalid/);
|
||||
});
|
||||
|
||||
it("applies the same response floor independent of identity outcome", async () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-07-15T12:00:00.000Z"));
|
||||
const pending = waitForPortalAuthResponseFloor(Date.now(), 1200);
|
||||
await vi.advanceTimersByTimeAsync(1199);
|
||||
let settled = false;
|
||||
void pending.then(() => {
|
||||
settled = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await expect(pending).resolves.toBeUndefined();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
|
||||
export const PORTAL_OPAQUE_TOKEN_BYTES = 32;
|
||||
export const PORTAL_SESSION_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
export const PORTAL_SESSION_INACTIVITY_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export const PORTAL_AUTH_TOKEN_TTL_MS = {
|
||||
magic_link: 15 * 60 * 1000,
|
||||
setup: 7 * 24 * 60 * 60 * 1000,
|
||||
verify_email: 24 * 60 * 60 * 1000,
|
||||
reset_password: 60 * 60 * 1000,
|
||||
} as const;
|
||||
|
||||
export type PortalAuthTokenPurpose = keyof typeof PORTAL_AUTH_TOKEN_TTL_MS;
|
||||
|
||||
export function hashPortalOpaqueToken(rawToken: string): string {
|
||||
return createHash("sha256").update(rawToken).digest("hex");
|
||||
}
|
||||
|
||||
export function createPortalOpaqueToken(options: { readonly rawToken?: string; readonly bytes?: number } = {}): {
|
||||
readonly rawToken: string;
|
||||
readonly tokenHash: string;
|
||||
} {
|
||||
const bytes = options.bytes ?? PORTAL_OPAQUE_TOKEN_BYTES;
|
||||
if (!Number.isSafeInteger(bytes) || bytes < PORTAL_OPAQUE_TOKEN_BYTES) {
|
||||
throw new Error("Portal auth tokens require at least 256 bits of entropy.");
|
||||
}
|
||||
const rawToken = options.rawToken ?? randomBytes(bytes).toString("base64url");
|
||||
if (!rawToken) throw new Error("Portal auth token must not be empty.");
|
||||
return { rawToken, tokenHash: hashPortalOpaqueToken(rawToken) };
|
||||
}
|
||||
|
||||
export function createPortalAuthToken(
|
||||
purpose: PortalAuthTokenPurpose,
|
||||
options: { readonly now?: Date; readonly rawToken?: string } = {}
|
||||
): { readonly rawToken: string; readonly tokenHash: string; readonly expiresAt: Date; readonly purpose: PortalAuthTokenPurpose } {
|
||||
const now = options.now ?? new Date();
|
||||
const token = createPortalOpaqueToken({ rawToken: options.rawToken });
|
||||
return {
|
||||
...token,
|
||||
expiresAt: new Date(now.getTime() + PORTAL_AUTH_TOKEN_TTL_MS[purpose]),
|
||||
purpose,
|
||||
};
|
||||
}
|
||||
|
||||
export function createPortalSessionToken(options: { readonly now?: Date; readonly rawToken?: string } = {}): {
|
||||
readonly rawToken: string;
|
||||
readonly tokenHash: string;
|
||||
readonly expiresAt: Date;
|
||||
} {
|
||||
const now = options.now ?? new Date();
|
||||
const token = createPortalOpaqueToken({ rawToken: options.rawToken });
|
||||
return { ...token, expiresAt: new Date(now.getTime() + PORTAL_SESSION_TTL_MS) };
|
||||
}
|
||||
|
||||
export function normalizePortalEmail(value: string): string {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!normalized || normalized.length > 320 || !normalized.includes("@")) {
|
||||
throw new Error("Portal email is invalid.");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export async function waitForPortalAuthResponseFloor(startedAt: number, floorMs = 1200): Promise<void> {
|
||||
if (!Number.isFinite(startedAt) || !Number.isSafeInteger(floorMs) || floorMs < 0) {
|
||||
throw new Error("Portal auth response floor is invalid.");
|
||||
}
|
||||
const remaining = floorMs - (Date.now() - startedAt);
|
||||
if (remaining > 0) await new Promise((resolve) => setTimeout(resolve, remaining));
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
createDownloadUrl: vi.fn(),
|
||||
deleteFile: vi.fn(),
|
||||
resolveStorageBucket: vi.fn(),
|
||||
storeFile: vi.fn(),
|
||||
loadConfig: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: mocks.loadConfig }));
|
||||
vi.mock("~/utils/integrations/mediaSigning.server", () => ({ createMediaDownloadUrl: mocks.createDownloadUrl }));
|
||||
vi.mock("~/utils/integrations/storageService", () => ({
|
||||
AVATAR_UPLOAD_CONTENT_MAX_BYTES: 5 * 1024 * 1024,
|
||||
deleteFile: mocks.deleteFile,
|
||||
resolveStorageBucket: mocks.resolveStorageBucket,
|
||||
storeFile: mocks.storeFile,
|
||||
}));
|
||||
|
||||
import {
|
||||
PORTAL_BRANDING_LOGO_MAX_BYTES,
|
||||
PORTAL_BRANDING_LOGO_SIGNED_URL_TTL_SECONDS,
|
||||
PortalBrandingValidationError,
|
||||
createPortalBrandingLogoDownloadUrl,
|
||||
portalBrandingLogoPreviewHref,
|
||||
portalBrandingLogoStorageKey,
|
||||
removePortalBrandingLogo,
|
||||
storePortalBrandingLogo,
|
||||
} from "./portal-branding.server";
|
||||
|
||||
describe("customer portal branding storage", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.resolveStorageBucket.mockReturnValue("private-media");
|
||||
mocks.loadConfig.mockReturnValue({ routing: { protocol: "https", portalAppHost: "portal.example.test" } });
|
||||
mocks.createDownloadUrl.mockResolvedValue("https://objects.example.test/signed-logo");
|
||||
mocks.storeFile.mockResolvedValue("");
|
||||
mocks.deleteFile.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("builds one traversal-safe private logo key per tenant", () => {
|
||||
expect(portalBrandingLogoStorageKey("tenant_123")).toBe("tenants/tenant_123/portal/branding/logo");
|
||||
expect(() => portalBrandingLogoStorageKey("../other")).toThrow(PortalBrandingValidationError);
|
||||
expect(() => portalBrandingLogoStorageKey("tenant/other")).toThrow(PortalBrandingValidationError);
|
||||
expect(PORTAL_BRANDING_LOGO_MAX_BYTES).toBe(5 * 1024 * 1024);
|
||||
});
|
||||
|
||||
it("stores only inline PNG/JPEG/WebP bytes with avatar and fail-closed malware scans", async () => {
|
||||
const onReject = vi.fn();
|
||||
await storePortalBrandingLogo({
|
||||
tenantId: "tenant_123",
|
||||
upload: {
|
||||
content: " data:image/png;base64,iVBORw0KGgo= ",
|
||||
declaredMimeType: " IMAGE/PNG; charset=binary ",
|
||||
filename: "tenant-logo.png",
|
||||
onReject,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mocks.storeFile).toHaveBeenCalledWith({
|
||||
bucket: "private-media",
|
||||
content: "data:image/png;base64,iVBORw0KGgo=",
|
||||
id: "tenants/tenant_123/portal/branding/logo",
|
||||
replace: true,
|
||||
throwOnFailure: true,
|
||||
scan: {
|
||||
context: "avatar",
|
||||
declaredMimeType: "image/png",
|
||||
filename: "tenant-logo.png",
|
||||
onReject,
|
||||
requireMalwareScan: true,
|
||||
tenantId: "tenant_123",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["image/svg+xml", "image/gif", "application/pdf"])("rejects %s before touching storage", async (declaredMimeType) => {
|
||||
await expect(
|
||||
storePortalBrandingLogo({
|
||||
tenantId: "tenant_123",
|
||||
upload: { content: "data:image/svg+xml;base64,AAAA", declaredMimeType, filename: "logo" },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "invalid_mime_type" });
|
||||
expect(mocks.storeFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects arbitrary remote URLs instead of opening an upload-side fetch surface", async () => {
|
||||
await expect(
|
||||
storePortalBrandingLogo({
|
||||
tenantId: "tenant_123",
|
||||
upload: { content: "https://example.test/logo.png", declaredMimeType: "image/png", filename: "logo.png" },
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "invalid_content" });
|
||||
expect(mocks.storeFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("removes and signs only the deterministic tenant object", async () => {
|
||||
await removePortalBrandingLogo("tenant_123");
|
||||
await expect(createPortalBrandingLogoDownloadUrl("tenant_123")).resolves.toBe("https://objects.example.test/signed-logo");
|
||||
|
||||
expect(mocks.deleteFile).toHaveBeenCalledWith({
|
||||
bucket: "private-media",
|
||||
key: "tenants/tenant_123/portal/branding/logo",
|
||||
});
|
||||
expect(mocks.createDownloadUrl).toHaveBeenCalledWith({
|
||||
key: "tenants/tenant_123/portal/branding/logo",
|
||||
ttlSeconds: PORTAL_BRANDING_LOGO_SIGNED_URL_TTL_SECONDS,
|
||||
});
|
||||
});
|
||||
|
||||
it("builds an absolute standard-host preview URL without trusting a stored URL", () => {
|
||||
expect(portalBrandingLogoPreviewHref("demo-pro-crm")).toBe("https://portal.example.test/demo-pro-crm/branding/logo");
|
||||
expect(() => portalBrandingLogoPreviewHref("../other")).toThrow(PortalBrandingValidationError);
|
||||
});
|
||||
});
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import type { PreUploadScanResult } from "@hivegrid/storage";
|
||||
|
||||
import { createMediaDownloadUrl } from "~/utils/integrations/mediaSigning.server";
|
||||
import {
|
||||
AVATAR_UPLOAD_CONTENT_MAX_BYTES,
|
||||
deleteFile,
|
||||
resolveStorageBucket,
|
||||
storeFile,
|
||||
} from "~/utils/integrations/storageService";
|
||||
|
||||
const PORTAL_LOGO_MIME_TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);
|
||||
const TENANT_ID_PATTERN = /^[A-Za-z0-9_-]{1,191}$/u;
|
||||
const TENANT_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,62}$/u;
|
||||
|
||||
export const PORTAL_BRANDING_LOGO_MAX_BYTES = AVATAR_UPLOAD_CONTENT_MAX_BYTES;
|
||||
export const PORTAL_BRANDING_LOGO_SIGNED_URL_TTL_SECONDS = 60;
|
||||
|
||||
export class PortalBrandingValidationError extends Error {
|
||||
override readonly name = "PortalBrandingValidationError";
|
||||
|
||||
constructor(readonly code: "invalid_content" | "invalid_mime_type" | "invalid_tenant") {
|
||||
super(`Invalid portal branding logo (${code}).`);
|
||||
}
|
||||
}
|
||||
|
||||
export type PortalBrandingLogoUpload = {
|
||||
readonly content: string;
|
||||
readonly declaredMimeType: string;
|
||||
readonly filename: string;
|
||||
readonly onReject?: (verdict: PreUploadScanResult) => void | Promise<void>;
|
||||
};
|
||||
|
||||
/**
|
||||
* One private, deterministic object per tenant. The tenant segment is kept
|
||||
* deliberately opaque and may never contain a slash or traversal token.
|
||||
*/
|
||||
export function portalBrandingLogoStorageKey(tenantId: string): string {
|
||||
const normalizedTenantId = tenantId.trim();
|
||||
if (!TENANT_ID_PATTERN.test(normalizedTenantId)) {
|
||||
throw new PortalBrandingValidationError("invalid_tenant");
|
||||
}
|
||||
return `tenants/${normalizedTenantId}/portal/branding/logo`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin previews always use the canonical standard portal host. That keeps the
|
||||
* URL stable even before a custom domain is activated and avoids exposing a
|
||||
* private storage URL in a view-model.
|
||||
*/
|
||||
export function portalBrandingLogoPreviewHref(tenantSlug: string): string {
|
||||
const normalizedTenantSlug = tenantSlug.trim().toLowerCase();
|
||||
if (!TENANT_SLUG_PATTERN.test(normalizedTenantSlug)) {
|
||||
throw new PortalBrandingValidationError("invalid_tenant");
|
||||
}
|
||||
const { routing } = loadRequiredWebConfig();
|
||||
return new URL(
|
||||
`/${normalizedTenantSlug}/branding/logo`,
|
||||
`${routing.protocol}://${routing.portalAppHost}`,
|
||||
).href;
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist untrusted logo bytes only after the restrictive avatar magic-byte
|
||||
* allow-list and a fail-closed ClamAV buffer scan have both accepted them.
|
||||
*/
|
||||
export async function storePortalBrandingLogo(input: {
|
||||
readonly tenantId: string;
|
||||
readonly upload: PortalBrandingLogoUpload;
|
||||
}): Promise<void> {
|
||||
const content = input.upload.content.trim();
|
||||
if (!content.toLowerCase().startsWith("data:")) {
|
||||
throw new PortalBrandingValidationError("invalid_content");
|
||||
}
|
||||
const declaredMimeType = normalizeMimeType(input.upload.declaredMimeType);
|
||||
if (!PORTAL_LOGO_MIME_TYPES.has(declaredMimeType)) {
|
||||
throw new PortalBrandingValidationError("invalid_mime_type");
|
||||
}
|
||||
|
||||
await storeFile({
|
||||
bucket: resolveStorageBucket(),
|
||||
content,
|
||||
id: portalBrandingLogoStorageKey(input.tenantId),
|
||||
replace: true,
|
||||
throwOnFailure: true,
|
||||
scan: {
|
||||
context: "avatar",
|
||||
declaredMimeType,
|
||||
filename: input.upload.filename,
|
||||
requireMalwareScan: true,
|
||||
tenantId: input.tenantId,
|
||||
...(input.upload.onReject ? { onReject: input.upload.onReject } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function removePortalBrandingLogo(tenantId: string): Promise<void> {
|
||||
await deleteFile({
|
||||
bucket: resolveStorageBucket(),
|
||||
key: portalBrandingLogoStorageKey(tenantId),
|
||||
});
|
||||
}
|
||||
|
||||
export async function createPortalBrandingLogoDownloadUrl(tenantId: string): Promise<string> {
|
||||
return createMediaDownloadUrl({
|
||||
key: portalBrandingLogoStorageKey(tenantId),
|
||||
ttlSeconds: PORTAL_BRANDING_LOGO_SIGNED_URL_TTL_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeMimeType(value: string): string {
|
||||
return value.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
portalPublicPath,
|
||||
requireTrustedPortalOrigin,
|
||||
type TrustedPortalOrigin,
|
||||
} from "./portal-origin.server";
|
||||
|
||||
/**
|
||||
* Capability links may deep-link only to one project detail inside the same
|
||||
* tenant. URLSearchParams performs exactly one decode; encoded or double-
|
||||
* encoded bypass attempts therefore fail the canonical path expression.
|
||||
*/
|
||||
export function resolvePortalCapabilityContinuePath(request: Request, tenantSlug: string): string {
|
||||
const origin = requireTrustedPortalOrigin(request, tenantSlug);
|
||||
return readPortalProjectContinuePath(request, origin) ?? portalPublicPath(origin);
|
||||
}
|
||||
|
||||
export function readPortalProjectContinuePath(request: Request, origin: TrustedPortalOrigin): string | null {
|
||||
const values = new URL(request.url).searchParams.getAll("continue");
|
||||
if (values.length !== 1) return null;
|
||||
const candidate = values[0];
|
||||
if (!candidate) return null;
|
||||
const escapedTenant = origin.tenantSlug.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
||||
const pattern = origin.customHost
|
||||
? /^\/projects\/[A-Za-z0-9_-]{1,128}$/u
|
||||
: new RegExp(`^/${escapedTenant}/projects/[A-Za-z0-9_-]{1,128}$`, "u");
|
||||
return pattern.test(candidate) ? candidate : null;
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
PORTAL_COMPLAINT_ACTIVITY_SUMMARY_KEY,
|
||||
PortalComplaintError,
|
||||
submitPortalComplaint,
|
||||
type PortalComplaintPersistence,
|
||||
} from "./portal-complaint.server";
|
||||
import type { PortalSessionIdentity } from "./portal-data.server";
|
||||
|
||||
const identity: PortalSessionIdentity = {
|
||||
portalUserId: "portal-user-1",
|
||||
portalId: "portal-1",
|
||||
tenantId: "tenant-1",
|
||||
tenantSlug: "acme",
|
||||
tenantFrozen: false,
|
||||
portalSessionId: "session-1",
|
||||
portalTitle: "Acme Portal",
|
||||
viewerFirstName: "Karla",
|
||||
viewerLastName: "Kunde",
|
||||
viewerLocale: "de",
|
||||
createdAt: new Date("2026-07-16T10:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-16T10:00:00.000Z"),
|
||||
expiresAt: new Date("2026-07-17T10:00:00.000Z"),
|
||||
origin: "https://portal.example.de",
|
||||
};
|
||||
|
||||
const definition = {
|
||||
title: "Reklamation",
|
||||
gdprConsentLabel: "Einverstanden",
|
||||
fields: [
|
||||
{ key: "subject", type: "text", label: "Betreff", required: true, validationRules: { minLength: 3 } },
|
||||
{ key: "details", type: "textarea", label: "Details", required: true },
|
||||
],
|
||||
};
|
||||
|
||||
function persistence(): PortalComplaintPersistence {
|
||||
return {
|
||||
loadForm: vi.fn().mockResolvedValue({ id: "form-1", definition }),
|
||||
create: vi.fn().mockResolvedValue({ complaintId: "complaint-1", submissionId: "submission-1", projectLeaderUserId: "leader-1", effectsCompleted: false }),
|
||||
appendActivity: vi.fn().mockResolvedValue(undefined),
|
||||
notifyProjectLeader: vi.fn().mockResolvedValue(undefined),
|
||||
recordInbox: vi.fn().mockResolvedValue(undefined),
|
||||
markEffectsCompleted: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
describe("submitPortalComplaint", () => {
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
it("uses a locale-independent activity summary key", () => {
|
||||
expect(PORTAL_COMPLAINT_ACTIVITY_SUMMARY_KEY).toBe("activity.runtime.customerPortal.complaintSubmitted");
|
||||
});
|
||||
|
||||
it("validates the shared portal_form contract and attributes the PortalUser", async () => {
|
||||
const store = persistence();
|
||||
const result = await submitPortalComplaint({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
formId: "form-1",
|
||||
payload: { values: { subject: "Dach undicht", details: "Bitte prüfen" }, gdprAccepted: true, idempotencyKey: "complaint-123" },
|
||||
persistence: store,
|
||||
});
|
||||
|
||||
expect(result).toEqual({ complaintId: "complaint-1", submissionId: "submission-1" });
|
||||
expect(store.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
identity: expect.objectContaining({ portalUserId: "portal-user-1" }),
|
||||
projectId: "project-1",
|
||||
formId: "form-1",
|
||||
subject: "Dach undicht",
|
||||
idempotencyKey: "complaint-123",
|
||||
values: { subject: "Dach undicht", details: "Bitte prüfen" },
|
||||
}));
|
||||
expect(store.appendActivity).toHaveBeenCalledOnce();
|
||||
expect(store.recordInbox).toHaveBeenCalledOnce();
|
||||
expect(store.notifyProjectLeader).toHaveBeenCalledWith(expect.objectContaining({ projectLeaderUserId: "leader-1" }));
|
||||
expect(store.markEffectsCompleted).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("rejects unknown and conditionally hidden values before persistence", async () => {
|
||||
const store = persistence();
|
||||
vi.mocked(store.loadForm).mockResolvedValue({
|
||||
id: "form-1",
|
||||
definition: {
|
||||
...definition,
|
||||
fields: [
|
||||
...definition.fields,
|
||||
{
|
||||
key: "internalNote",
|
||||
type: "text",
|
||||
label: "Interne Notiz",
|
||||
conditionalLogic: [{ fieldKey: "subject", operator: "equals", value: "show" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
for (const values of [
|
||||
{ subject: "Dach", details: "Prüfen", injected: "must-not-persist" },
|
||||
{ subject: "Dach", details: "Prüfen", internalNote: "hidden" },
|
||||
]) {
|
||||
await expect(
|
||||
submitPortalComplaint({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
formId: "form-1",
|
||||
payload: { values, gdprAccepted: true },
|
||||
persistence: store,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "INVALID_PAYLOAD" } satisfies Partial<PortalComplaintError>);
|
||||
}
|
||||
expect(store.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed before persistence for invalid payloads and frozen tenants", async () => {
|
||||
const store = persistence();
|
||||
await expect(submitPortalComplaint({ identity, projectId: "project-1", formId: "form-1", payload: { values: {}, gdprAccepted: true }, persistence: store }))
|
||||
.rejects.toMatchObject({ code: "INVALID_PAYLOAD" } satisfies Partial<PortalComplaintError>);
|
||||
await expect(submitPortalComplaint({ identity: { ...identity, tenantFrozen: true }, projectId: "project-1", formId: "form-1", payload: {}, persistence: store }))
|
||||
.rejects.toMatchObject({ code: "PORTAL_FROZEN" } satisfies Partial<PortalComplaintError>);
|
||||
expect(store.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not emit success effects when the atomic capability fails", async () => {
|
||||
const store = persistence();
|
||||
vi.mocked(store.create).mockRejectedValue(new Error("rls denied"));
|
||||
await expect(submitPortalComplaint({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
formId: "form-1",
|
||||
payload: { values: { subject: "Dach", details: "Prüfen" }, gdprAccepted: true },
|
||||
persistence: store,
|
||||
})).rejects.toMatchObject({ code: "SUBMISSION_FAILED" } satisfies Partial<PortalComplaintError>);
|
||||
expect(store.appendActivity).not.toHaveBeenCalled();
|
||||
expect(store.recordInbox).not.toHaveBeenCalled();
|
||||
expect(store.notifyProjectLeader).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("skips completed effects on an identical complaint retry", async () => {
|
||||
const store = persistence();
|
||||
vi.mocked(store.create).mockResolvedValue({
|
||||
complaintId: "complaint-1",
|
||||
submissionId: "submission-1",
|
||||
projectLeaderUserId: "leader-1",
|
||||
effectsCompleted: true,
|
||||
});
|
||||
|
||||
await expect(submitPortalComplaint({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
formId: "form-1",
|
||||
payload: { values: { subject: "Dach", details: "Prüfen" }, gdprAccepted: true, idempotencyKey: "complaint-123" },
|
||||
persistence: store,
|
||||
})).resolves.toEqual({ complaintId: "complaint-1", submissionId: "submission-1" });
|
||||
expect(store.appendActivity).not.toHaveBeenCalled();
|
||||
expect(store.recordInbox).not.toHaveBeenCalled();
|
||||
expect(store.notifyProjectLeader).not.toHaveBeenCalled();
|
||||
expect(store.markEffectsCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps pending effects repairable when one auxiliary write fails", async () => {
|
||||
const store = persistence();
|
||||
vi.mocked(store.recordInbox).mockRejectedValueOnce(new Error("inbox unavailable"));
|
||||
|
||||
await expect(submitPortalComplaint({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
formId: "form-1",
|
||||
payload: { values: { subject: "Dach", details: "Prüfen" }, gdprAccepted: true, idempotencyKey: "complaint-123" },
|
||||
persistence: store,
|
||||
})).rejects.toMatchObject({ code: "SUBMISSION_FAILED" } satisfies Partial<PortalComplaintError>);
|
||||
expect(store.markEffectsCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { logActivity, type ActivityWriteClient } from "@hivegrid/activity";
|
||||
import { getWriteDbClient, type DbClient } from "@hivegrid/db/client.server";
|
||||
import { runWithPortalRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import {
|
||||
filterVisibleFields,
|
||||
FormDefinitionSchema,
|
||||
FormSubmissionPayloadSchema,
|
||||
isHoneypotTriggered,
|
||||
validateFormValues,
|
||||
type FormDefinition,
|
||||
} from "@hivegrid/form-widget";
|
||||
import { notify, requirePortalUserActor, type NotificationClient } from "@hivegrid/foundation";
|
||||
|
||||
import type { PortalSessionIdentity } from "./portal-data.server";
|
||||
|
||||
export const PORTAL_COMPLAINT_ACTIVITY_SUMMARY_KEY = "activity.runtime.customerPortal.complaintSubmitted";
|
||||
|
||||
export class PortalComplaintError extends Error {
|
||||
override readonly name = "PortalComplaintError";
|
||||
|
||||
constructor(
|
||||
readonly code:
|
||||
| "PORTAL_FROZEN"
|
||||
| "PROJECT_ACCESS_DENIED"
|
||||
| "FORM_NOT_FOUND"
|
||||
| "FORM_MISCONFIGURED"
|
||||
| "INVALID_PAYLOAD"
|
||||
| "GDPR_REQUIRED"
|
||||
| "SUBMISSION_FAILED",
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
type PortalComplaintForm = {
|
||||
readonly id: string;
|
||||
readonly definition: unknown;
|
||||
};
|
||||
|
||||
type CreatedPortalComplaint = {
|
||||
readonly complaintId: string;
|
||||
readonly submissionId: string;
|
||||
readonly projectLeaderUserId: string | null;
|
||||
readonly effectsCompleted: boolean;
|
||||
};
|
||||
|
||||
export type PortalComplaintPersistence = {
|
||||
loadForm(input: { readonly identity: PortalSessionIdentity; readonly projectId: string; readonly formId: string }): Promise<PortalComplaintForm | null>;
|
||||
create(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly formId: string;
|
||||
readonly values: Readonly<Record<string, string | number | boolean | readonly string[] | null>>;
|
||||
readonly subject: string | null;
|
||||
readonly idempotencyKey: string;
|
||||
readonly complaintId: string;
|
||||
readonly submissionId: string;
|
||||
}): Promise<CreatedPortalComplaint>;
|
||||
appendActivity(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly complaintId: string;
|
||||
readonly subject: string | null;
|
||||
}): Promise<void>;
|
||||
notifyProjectLeader(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly complaintId: string;
|
||||
readonly projectLeaderUserId: string;
|
||||
}): Promise<void>;
|
||||
recordInbox(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly complaintId: string;
|
||||
readonly subject: string | null;
|
||||
}): Promise<void>;
|
||||
markEffectsCompleted(input: { readonly identity: PortalSessionIdentity; readonly complaintId: string }): Promise<void>;
|
||||
};
|
||||
|
||||
export async function submitPortalComplaint(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly formId: string;
|
||||
readonly payload: unknown;
|
||||
readonly persistence?: PortalComplaintPersistence;
|
||||
}): Promise<{ readonly complaintId: string; readonly submissionId: string }> {
|
||||
if (input.identity.tenantFrozen) throw new PortalComplaintError("PORTAL_FROZEN");
|
||||
const projectId = requireIdentifier(input.projectId, "PROJECT_ACCESS_DENIED");
|
||||
const formId = requireIdentifier(input.formId, "FORM_NOT_FOUND");
|
||||
requirePortalUserActor({ createdByPortalUserId: input.identity.portalUserId });
|
||||
|
||||
const parsedPayload = FormSubmissionPayloadSchema.safeParse(input.payload);
|
||||
if (!parsedPayload.success) throw new PortalComplaintError("INVALID_PAYLOAD");
|
||||
if (parsedPayload.data.gdprAccepted !== true) throw new PortalComplaintError("GDPR_REQUIRED");
|
||||
if (isHoneypotTriggered(parsedPayload.data.values)) throw new PortalComplaintError("INVALID_PAYLOAD");
|
||||
|
||||
const persistence = input.persistence ?? createPortalComplaintPersistence();
|
||||
const form = await persistence.loadForm({ identity: input.identity, projectId, formId });
|
||||
if (!form) throw new PortalComplaintError("FORM_NOT_FOUND");
|
||||
const parsedDefinition = FormDefinitionSchema.safeParse(form.definition);
|
||||
if (!parsedDefinition.success) throw new PortalComplaintError("FORM_MISCONFIGURED");
|
||||
|
||||
const visibleDefinition: FormDefinition = {
|
||||
...parsedDefinition.data,
|
||||
fields: filterVisibleFields(parsedDefinition.data.fields, parsedPayload.data.values),
|
||||
};
|
||||
const visibleFieldKeys = new Set(
|
||||
visibleDefinition.fields.filter((field) => field.type !== "honeypot").map((field) => field.key),
|
||||
);
|
||||
const submittedFieldKeys = Object.keys(parsedPayload.data.values).filter((key) =>
|
||||
parsedDefinition.data.fields.every((field) => field.type !== "honeypot" || field.key !== key),
|
||||
);
|
||||
if (submittedFieldKeys.some((key) => !visibleFieldKeys.has(key))) {
|
||||
throw new PortalComplaintError("INVALID_PAYLOAD");
|
||||
}
|
||||
const sanitizedValues = Object.fromEntries(
|
||||
submittedFieldKeys.map((key) => [key, parsedPayload.data.values[key] ?? null]),
|
||||
) as Readonly<Record<string, string | number | boolean | readonly string[] | null>>;
|
||||
if (validateFormValues(sanitizedValues, visibleDefinition)) throw new PortalComplaintError("INVALID_PAYLOAD");
|
||||
|
||||
const subjectValue = sanitizedValues.subject;
|
||||
const subject = typeof subjectValue === "string" && subjectValue.trim() ? subjectValue.trim().slice(0, 200) : null;
|
||||
const idempotencyKey = parsedPayload.data.idempotencyKey ?? randomUUID();
|
||||
let created: CreatedPortalComplaint;
|
||||
try {
|
||||
created = await persistence.create({
|
||||
identity: input.identity,
|
||||
projectId,
|
||||
formId,
|
||||
values: sanitizedValues,
|
||||
subject,
|
||||
idempotencyKey,
|
||||
complaintId: randomUUID(),
|
||||
submissionId: randomUUID(),
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PortalComplaintError) throw error;
|
||||
throw new PortalComplaintError("SUBMISSION_FAILED");
|
||||
}
|
||||
|
||||
if (!created.effectsCompleted) {
|
||||
try {
|
||||
await Promise.all([
|
||||
persistence.appendActivity({ identity: input.identity, projectId, complaintId: created.complaintId, subject }),
|
||||
persistence.recordInbox({ identity: input.identity, projectId, complaintId: created.complaintId, subject }),
|
||||
created.projectLeaderUserId
|
||||
? persistence.notifyProjectLeader({
|
||||
identity: input.identity,
|
||||
projectId,
|
||||
complaintId: created.complaintId,
|
||||
projectLeaderUserId: created.projectLeaderUserId,
|
||||
})
|
||||
: Promise.resolve(),
|
||||
]);
|
||||
await persistence.markEffectsCompleted({ identity: input.identity, complaintId: created.complaintId });
|
||||
} catch {
|
||||
throw new PortalComplaintError("SUBMISSION_FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
return { complaintId: created.complaintId, submissionId: created.submissionId };
|
||||
}
|
||||
|
||||
function createPortalComplaintPersistence(db: DbClient = getWriteDbClient()): PortalComplaintPersistence {
|
||||
const activityClient: ActivityWriteClient = {
|
||||
activity: {
|
||||
async create({ data }) {
|
||||
const rows = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT id FROM public.hivegrid_portal_append_activity(
|
||||
${data.tenantId}, ${data.subjectId}, ${data.summaryText}, ${data.metadata ?? null}
|
||||
)
|
||||
`;
|
||||
const id = rows[0]?.id;
|
||||
if (!id) throw new Error("portal activity capability failed");
|
||||
return { id };
|
||||
},
|
||||
},
|
||||
};
|
||||
const notificationClient: NotificationClient = {
|
||||
notificationDelivery: {
|
||||
async create({ data }) {
|
||||
await appendNotification(db, data);
|
||||
return data;
|
||||
},
|
||||
async upsert({ create }) {
|
||||
await appendNotification(db, create);
|
||||
return create;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
async loadForm({ identity, projectId, formId }) {
|
||||
return runWithPortalRlsContext(identity, async () => {
|
||||
const rows = await db.$queryRaw<Array<{ id: string; definition: unknown }>>`
|
||||
SELECT * FROM public.hivegrid_portal_resolve_complaint_form(${projectId}, ${formId})
|
||||
`;
|
||||
return rows[0] ?? null;
|
||||
});
|
||||
},
|
||||
async create({ identity, projectId, formId, values, subject, idempotencyKey, complaintId, submissionId }) {
|
||||
return runWithPortalRlsContext(identity, async () => {
|
||||
const rows = await db.$queryRaw<CreatedPortalComplaint[]>`
|
||||
SELECT * FROM public.hivegrid_portal_submit_complaint(
|
||||
${complaintId}, ${submissionId}, ${projectId}, ${formId}, ${values}, ${subject}, ${idempotencyKey}
|
||||
)
|
||||
`;
|
||||
const created = rows[0];
|
||||
if (!created) throw new PortalComplaintError("PROJECT_ACCESS_DENIED");
|
||||
return created;
|
||||
});
|
||||
},
|
||||
async appendActivity({ identity, projectId, complaintId, subject }) {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
logActivity(
|
||||
{
|
||||
tenantId: identity.tenantId,
|
||||
actorUserId: null,
|
||||
actorKind: "system",
|
||||
activityType: "portal_complaint_submitted",
|
||||
subjectType: "project",
|
||||
subjectId: projectId,
|
||||
summaryText: PORTAL_COMPLAINT_ACTIVITY_SUMMARY_KEY,
|
||||
metadata: { portalUserId: identity.portalUserId, complaintId, subject },
|
||||
},
|
||||
{ client: activityClient },
|
||||
),
|
||||
);
|
||||
},
|
||||
async notifyProjectLeader({ identity, projectId, complaintId, projectLeaderUserId }) {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
notify(
|
||||
{
|
||||
tenantId: identity.tenantId,
|
||||
userId: projectLeaderUserId,
|
||||
channel: "IN_APP",
|
||||
category: "customer_portal",
|
||||
messageKey: "customerPortal.notifications.complaintReceived",
|
||||
sourceKey: `portal-complaint:${complaintId}`,
|
||||
payloadMetadata: { projectId, complaintId },
|
||||
},
|
||||
notificationClient,
|
||||
),
|
||||
);
|
||||
},
|
||||
async recordInbox({ identity, projectId, complaintId, subject }) {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
db.$queryRaw`SELECT public.hivegrid_portal_record_inbox_event('complaint', ${projectId}, ${complaintId}, ${subject})`,
|
||||
);
|
||||
},
|
||||
async markEffectsCompleted({ identity, complaintId }) {
|
||||
const rows = await runWithPortalRlsContext(identity, () =>
|
||||
db.$queryRaw<Array<{ completed: boolean }>>`SELECT completed FROM public.hivegrid_portal_mark_effects_completed('complaint', ${complaintId})`,
|
||||
);
|
||||
if (!rows[0]?.completed) throw new Error("portal complaint effects capability failed");
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function appendNotification(
|
||||
db: DbClient,
|
||||
data: {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
channel: string;
|
||||
category: string;
|
||||
messageKey: string;
|
||||
sourceKey: string | null;
|
||||
payloadMetadata: unknown;
|
||||
},
|
||||
): Promise<void> {
|
||||
const rows = await db.$queryRaw<Array<{ created: boolean }>>`
|
||||
SELECT created FROM public.hivegrid_portal_notify_project_leader(
|
||||
${data.tenantId}, ${data.userId}, ${data.channel}, ${data.category}, ${data.messageKey}, ${data.sourceKey}, ${data.payloadMetadata}
|
||||
)
|
||||
`;
|
||||
if (!rows[0]?.created) throw new Error("portal notification capability failed");
|
||||
}
|
||||
|
||||
function requireIdentifier(value: string, code: PortalComplaintError["code"]): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 191 || /[\u0000-\u001f\u007f]/u.test(normalized)) throw new PortalComplaintError(code);
|
||||
return normalized;
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const config = {
|
||||
runtimeSurface: "portal" as "core" | "portal",
|
||||
nodeEnv: "production",
|
||||
portalSessionSecret: "p".repeat(48),
|
||||
};
|
||||
|
||||
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: () => config }));
|
||||
|
||||
import { getPortalCsrfToken, PORTAL_CSRF_COOKIE_NAME, validatePortalCsrfToken } from "./portal-csrf.server";
|
||||
|
||||
describe("portal CSRF boundary", () => {
|
||||
beforeEach(() => {
|
||||
config.runtimeSurface = "portal";
|
||||
config.portalSessionSecret = "p".repeat(48);
|
||||
});
|
||||
|
||||
it("issues a signed, host-only portal cookie", async () => {
|
||||
const result = await getPortalCsrfToken(new Request("https://portal.hivegrid.de/acme/login"));
|
||||
expect(result.token).toMatch(/^[A-Za-z0-9_-]{43}$/u);
|
||||
expect(result.setCookie).toContain(`${PORTAL_CSRF_COOKIE_NAME}=`);
|
||||
expect(result.setCookie).toContain("HttpOnly");
|
||||
expect(result.setCookie).toContain("Secure");
|
||||
expect(result.setCookie).not.toContain("Domain=");
|
||||
});
|
||||
|
||||
it("accepts only an exact cookie/form token pair", async () => {
|
||||
const issued = await getPortalCsrfToken(new Request("https://portal.hivegrid.de/acme/login"));
|
||||
const cookie = issued.setCookie!.split(";", 1)[0]!;
|
||||
const form = new FormData();
|
||||
form.set("csrf", issued.token);
|
||||
await expect(
|
||||
validatePortalCsrfToken(
|
||||
new Request("https://portal.hivegrid.de/acme/login", { method: "POST", headers: { Cookie: cookie }, body: form }),
|
||||
form,
|
||||
),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns the same opaque 404 for missing or mismatched tokens", async () => {
|
||||
const form = new FormData();
|
||||
form.set("csrf", "wrong");
|
||||
const request = new Request("https://portal.hivegrid.de/acme/login", { method: "POST", body: form });
|
||||
await expect(validatePortalCsrfToken(request, form)).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("cannot be created by the core runtime", async () => {
|
||||
config.runtimeSurface = "core";
|
||||
await expect(getPortalCsrfToken(new Request("https://app.hivegrid.de"))).rejects.toThrow(/portal runtime surface/u);
|
||||
});
|
||||
});
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { createCookie } from "react-router";
|
||||
|
||||
export const PORTAL_CSRF_COOKIE_NAME = "__Host-hivegrid_portal_csrf";
|
||||
|
||||
function portalCsrfCookie() {
|
||||
const config = loadRequiredWebConfig();
|
||||
if (config.runtimeSurface !== "portal" || !config.portalSessionSecret) {
|
||||
throw new Error("Portal CSRF is available only in the portal runtime surface.");
|
||||
}
|
||||
|
||||
return createCookie(PORTAL_CSRF_COOKIE_NAME, {
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
secrets: [config.portalSessionSecret],
|
||||
maxAge: 60 * 60 * 12,
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPortalCsrfToken(request: Request): Promise<{ token: string; setCookie?: string }> {
|
||||
const cookie = portalCsrfCookie();
|
||||
const parsed = await cookie.parse(request.headers.get("Cookie"));
|
||||
if (typeof parsed === "string" && /^[A-Za-z0-9_-]{43}$/u.test(parsed)) {
|
||||
return { token: parsed };
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
return { token, setCookie: await cookie.serialize(token) };
|
||||
}
|
||||
|
||||
export async function validatePortalCsrfToken(request: Request, formData?: FormData): Promise<void> {
|
||||
const cookieValue = await portalCsrfCookie().parse(request.headers.get("Cookie"));
|
||||
const submitted = (formData ?? (await request.clone().formData())).get("csrf");
|
||||
if (typeof cookieValue !== "string" || typeof submitted !== "string" || !safeEqual(cookieValue, submitted)) {
|
||||
throw new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
}
|
||||
|
||||
function safeEqual(left: string, right: string): boolean {
|
||||
const leftBuffer = Buffer.from(left);
|
||||
const rightBuffer = Buffer.from(right);
|
||||
return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isPortalCustomDomainRuntimeEnabled } from "./portal-custom-domain-runtime.server";
|
||||
|
||||
describe("portal custom-domain runtime gate", () => {
|
||||
it.each(["development", "test"])("defaults to enabled for local %s mode", (nodeEnv) => {
|
||||
expect(isPortalCustomDomainRuntimeEnabled({ NODE_ENV: nodeEnv })).toBe(true);
|
||||
});
|
||||
|
||||
it.each([undefined, "staging", "preview", " production "])("defaults unknown runtime mode %s to disabled", (nodeEnv) => {
|
||||
expect(isPortalCustomDomainRuntimeEnabled({ NODE_ENV: nodeEnv })).toBe(false);
|
||||
});
|
||||
|
||||
it("requires the exact lowercase true value in production", () => {
|
||||
expect(isPortalCustomDomainRuntimeEnabled({ NODE_ENV: "production", PORTAL_CUSTOM_DOMAIN_RUNTIME_ENABLED: "true" })).toBe(true);
|
||||
for (const value of [undefined, "", "1", "TRUE", "false", " true "]) {
|
||||
expect(isPortalCustomDomainRuntimeEnabled({ NODE_ENV: "production", PORTAL_CUSTOM_DOMAIN_RUNTIME_ENABLED: value })).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("honours an explicit fail-closed value during development and tests", () => {
|
||||
expect(isPortalCustomDomainRuntimeEnabled({ NODE_ENV: "development", PORTAL_CUSTOM_DOMAIN_RUNTIME_ENABLED: "false" })).toBe(false);
|
||||
expect(isPortalCustomDomainRuntimeEnabled({ NODE_ENV: "test", PORTAL_CUSTOM_DOMAIN_RUNTIME_ENABLED: "1" })).toBe(false);
|
||||
});
|
||||
});
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
export const portalCustomDomainRuntimeEnabledEnv = "PORTAL_CUSTOM_DOMAIN_RUNTIME_ENABLED" as const;
|
||||
|
||||
type PortalCustomDomainRuntimeEnv = Readonly<Record<string, string | undefined>>;
|
||||
|
||||
/**
|
||||
* Keeps local development and tests usable without extra setup while making
|
||||
* every other runtime mode opt in explicitly. Values other than the
|
||||
* exact lowercase string `true` are fail-closed when the variable is set.
|
||||
*/
|
||||
export function isPortalCustomDomainRuntimeEnabled(env: PortalCustomDomainRuntimeEnv = process.env): boolean {
|
||||
const configured = env[portalCustomDomainRuntimeEnabledEnv];
|
||||
if (configured !== undefined) return configured === "true";
|
||||
return env.NODE_ENV === "development" || env.NODE_ENV === "test";
|
||||
}
|
||||
+398
@@ -0,0 +1,398 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
auditPortalSetupCapabilityDenial,
|
||||
auditPortalDocumentDownload,
|
||||
consumePortalAuthToken,
|
||||
createPortalSessionInTransaction,
|
||||
getPortalReleasedFile,
|
||||
mapPortalProjectRows,
|
||||
refreshPortalSession,
|
||||
revokePortalSession,
|
||||
resolvePortalSession,
|
||||
resolvePortalToken,
|
||||
} from "./portal-data.server";
|
||||
import { PORTAL_AUDIT_ACTIONS } from "./portal-audit.server";
|
||||
import { PORTAL_SESSION_TTL_MS } from "./portal-auth-token.server";
|
||||
|
||||
const sessionResolverIdentity = {
|
||||
tenantId: "tenant_a",
|
||||
portalId: "portal_a",
|
||||
portalUserId: "portal_user_a",
|
||||
portalSessionId: "session_a",
|
||||
tenantSlug: "acme",
|
||||
tenantFrozen: false,
|
||||
portalTitle: "Acme Portal",
|
||||
viewerFirstName: "Karla",
|
||||
viewerLastName: "Kunde",
|
||||
viewerLocale: "de",
|
||||
expiresAt: new Date("2026-08-14T12:00:00.000Z"),
|
||||
origin: "https://portal.acme.test",
|
||||
} as const;
|
||||
|
||||
describe("portal project data boundary", () => {
|
||||
it("maps only explicitly supplied visible stages and released rows", () => {
|
||||
const projects = mapPortalProjectRows({
|
||||
tenantSlug: "acme",
|
||||
pipelineIds: ["pipeline-1"],
|
||||
projectRows: [
|
||||
{
|
||||
id: "project-1",
|
||||
projektNummer: "P-1001",
|
||||
projektname: "Heizung",
|
||||
updatedAt: new Date("2026-07-15T12:00:00.000Z"),
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-visible",
|
||||
},
|
||||
],
|
||||
visibilityRows: [{ customerLabel: "Montage vor Ort", stage: { id: "stage-visible", pipelineId: "pipeline-1", name: "Montage", position: 20 } }],
|
||||
documentRows: [
|
||||
{
|
||||
id: "release-1",
|
||||
projectId: "project-1",
|
||||
releasedAt: new Date("2026-07-15T11:00:00.000Z"),
|
||||
revokedAt: null,
|
||||
file: { displayName: "Freigabe.pdf", mimeType: "application/pdf" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(projects).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "project-1",
|
||||
currentStageOrder: 20,
|
||||
hasActiveAccess: true,
|
||||
stages: [{ id: "stage-visible", label: "Montage vor Ort", order: 20, visible: true }],
|
||||
documents: [expect.objectContaining({ id: "release-1", downloadHref: "/acme/documents/release-1" })],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not infer hidden current-stage data", () => {
|
||||
const [project] = mapPortalProjectRows({
|
||||
tenantSlug: "acme",
|
||||
pipelineIds: ["pipeline-1"],
|
||||
projectRows: [
|
||||
{
|
||||
id: "project-1",
|
||||
projektNummer: "P-1001",
|
||||
projektname: "Heizung",
|
||||
updatedAt: new Date("2026-07-15T12:00:00.000Z"),
|
||||
pipelineId: "pipeline-1",
|
||||
stageId: "stage-hidden",
|
||||
},
|
||||
],
|
||||
visibilityRows: [{ customerLabel: null, stage: { id: "stage-visible", pipelineId: "pipeline-1", name: "Planung", position: 10 } }],
|
||||
documentRows: [],
|
||||
});
|
||||
expect(project?.currentStageOrder).toBe(-1);
|
||||
expect(project?.stages).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not consume a valid capability through a different tenant path", async () => {
|
||||
const transaction = vi.fn();
|
||||
const db = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([
|
||||
{
|
||||
tenantId: "tenant_a",
|
||||
portalId: "portal_a",
|
||||
portalUserId: "portal_user_a",
|
||||
portalTokenId: "token_a",
|
||||
purpose: "magic_link",
|
||||
expiresAt: new Date("2026-07-15T13:00:00.000Z"),
|
||||
},
|
||||
]),
|
||||
$transaction: transaction,
|
||||
};
|
||||
const effect = vi.fn();
|
||||
|
||||
await expect(
|
||||
consumePortalAuthToken("opaque-token", "magic_link", "a".repeat(64), effect, { tenantId: "tenant_b", portalId: "portal_b" }, db as never)
|
||||
).resolves.toBeNull();
|
||||
expect(transaction).not.toHaveBeenCalled();
|
||||
expect(effect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("claims and consumes a system-issued setup capability through the atomic scoped SQL function", async () => {
|
||||
const boundIpHash = "a".repeat(64);
|
||||
const identity = {
|
||||
tenantId: "tenant_a",
|
||||
portalId: "portal_a",
|
||||
portalUserId: "portal_user_a",
|
||||
portalTokenId: "token_a",
|
||||
emailNormalized: "customer@example.test",
|
||||
purpose: "setup",
|
||||
expiresAt: new Date("2026-07-15T13:00:00.000Z"),
|
||||
};
|
||||
const consumeRaw = vi.fn().mockResolvedValue([{ consumed: true }]);
|
||||
const tx = { $queryRaw: consumeRaw };
|
||||
const transaction = vi.fn(async (callback: (value: typeof tx) => Promise<unknown>) => callback(tx));
|
||||
const queryRaw = vi.fn((_parts: TemplateStringsArray, _tokenHash: string, _purpose: string, requestedIpHash: string) =>
|
||||
requestedIpHash === boundIpHash ? [identity] : []
|
||||
);
|
||||
const db = { $queryRaw: queryRaw, $transaction: transaction };
|
||||
|
||||
await expect(resolvePortalToken("opaque-token", "setup", "b".repeat(64), db as never)).resolves.toBeNull();
|
||||
expect(queryRaw.mock.calls.at(-1)?.[3]).toBe("b".repeat(64));
|
||||
|
||||
const effect = vi.fn().mockResolvedValue("consumed");
|
||||
await expect(
|
||||
consumePortalAuthToken("opaque-token", "setup", boundIpHash, effect, { tenantId: "tenant_a", portalId: "portal_a" }, db as never)
|
||||
).resolves.toBe("consumed");
|
||||
expect((consumeRaw.mock.calls[0]?.[0] as TemplateStringsArray).join("?")).toContain("hivegrid_portal_consume_token");
|
||||
expect(consumeRaw.mock.calls[0]?.slice(2)).toEqual([identity.portalTokenId, "setup", boundIpHash, identity.tenantId, identity.portalId]);
|
||||
expect(effect).toHaveBeenCalledWith(tx, identity);
|
||||
});
|
||||
|
||||
it("does not apply an effect when the atomic consume function loses the one-time claim", async () => {
|
||||
const identity = {
|
||||
tenantId: "tenant_a",
|
||||
portalId: "portal_a",
|
||||
portalUserId: "portal_user_a",
|
||||
portalTokenId: "token_a",
|
||||
emailNormalized: "customer@example.test",
|
||||
purpose: "setup",
|
||||
expiresAt: new Date("2026-07-15T13:00:00.000Z"),
|
||||
};
|
||||
const tx = { $queryRaw: vi.fn().mockResolvedValue([{ consumed: false }]) };
|
||||
const db = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([identity]),
|
||||
$transaction: vi.fn(async (callback: (value: typeof tx) => Promise<unknown>) => callback(tx)),
|
||||
};
|
||||
const effect = vi.fn();
|
||||
|
||||
await expect(
|
||||
consumePortalAuthToken("opaque-token", "setup", "a".repeat(64), effect, { tenantId: "tenant_a", portalId: "portal_a" }, db as never)
|
||||
).resolves.toBeNull();
|
||||
expect(effect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not start token consumption when the request IP hash mismatches", async () => {
|
||||
const transaction = vi.fn();
|
||||
const db = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([]),
|
||||
$transaction: transaction,
|
||||
};
|
||||
const effect = vi.fn();
|
||||
|
||||
await expect(
|
||||
consumePortalAuthToken("opaque-token", "magic_link", "b".repeat(64), effect, { tenantId: "tenant_a", portalId: "portal_a" }, db as never)
|
||||
).resolves.toBeNull();
|
||||
expect(transaction).not.toHaveBeenCalled();
|
||||
expect(effect).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("audits a denied setup capability without passing the opaque token or portal-user data", async () => {
|
||||
const queryRaw = vi.fn().mockResolvedValue([{ outboxId: "setup-denial-audit-1" }]);
|
||||
|
||||
await auditPortalSetupCapabilityDenial({ tenantId: "tenant_a", portalId: "portal_a" }, { $queryRaw: queryRaw } as never);
|
||||
|
||||
expect((queryRaw.mock.calls[0]?.[0] as TemplateStringsArray).join("?")).toContain("hivegrid_portal_append_setup_denial_audit");
|
||||
expect(queryRaw.mock.calls[0]?.slice(1)).toEqual(["tenant_a", "portal_a"]);
|
||||
expect(JSON.stringify(queryRaw.mock.calls)).not.toContain("opaque-token");
|
||||
});
|
||||
|
||||
it("resolves a download only through the purpose-bound document capability", async () => {
|
||||
const queryRaw = vi.fn().mockResolvedValue([
|
||||
{
|
||||
storageKey: "tenants/tenant_a/files/release.pdf",
|
||||
displayName: "Freigabe.pdf",
|
||||
scanStatus: "clean",
|
||||
},
|
||||
]);
|
||||
const identity = {
|
||||
tenantId: "tenant_a",
|
||||
portalId: "portal_a",
|
||||
portalUserId: "portal_user_a",
|
||||
} as never;
|
||||
|
||||
await expect(getPortalReleasedFile(identity, "release_a", { $queryRaw: queryRaw } as never)).resolves.toEqual({
|
||||
storageKey: "tenants/tenant_a/files/release.pdf",
|
||||
displayName: "Freigabe.pdf",
|
||||
scanStatus: "clean",
|
||||
});
|
||||
|
||||
expect(queryRaw).toHaveBeenCalledOnce();
|
||||
expect((queryRaw.mock.calls[0]?.[0] as TemplateStringsArray).join("?")).toContain("hivegrid_portal_resolve_project_document(?)");
|
||||
expect(queryRaw.mock.calls[0]?.[1]).toBe("release_a");
|
||||
});
|
||||
|
||||
it("re-checks the session row with an exclusive seven-day inactivity boundary", async () => {
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
const findFirst = vi.fn().mockResolvedValue(null);
|
||||
const db = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([sessionResolverIdentity]),
|
||||
portalSession: { findFirst },
|
||||
};
|
||||
|
||||
await expect(resolvePortalSession("opaque-session", db as never, now)).resolves.toBeNull();
|
||||
expect(findFirst).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: sessionResolverIdentity.portalSessionId,
|
||||
tenantId: sessionResolverIdentity.tenantId,
|
||||
portalUserId: sessionResolverIdentity.portalUserId,
|
||||
revokedAt: null,
|
||||
expiresAt: { gt: now },
|
||||
OR: [{ lastSeenAt: { gt: new Date("2026-07-08T12:00:00.000Z") } }, { lastSeenAt: null, createdAt: { gt: new Date("2026-07-08T12:00:00.000Z") } }],
|
||||
},
|
||||
select: { createdAt: true, lastSeenAt: true, expiresAt: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("hydrates active session timestamps only after the portal-scoped row check", async () => {
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
const sessionState = {
|
||||
createdAt: new Date("2026-07-01T12:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-15T11:00:00.000Z"),
|
||||
expiresAt: new Date("2026-08-14T11:00:00.000Z"),
|
||||
};
|
||||
const db = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([sessionResolverIdentity]),
|
||||
portalSession: { findFirst: vi.fn().mockResolvedValue(sessionState) },
|
||||
};
|
||||
|
||||
await expect(resolvePortalSession("opaque-session", db as never, now)).resolves.toEqual({
|
||||
...sessionResolverIdentity,
|
||||
...sessionState,
|
||||
});
|
||||
});
|
||||
|
||||
it("creates a 30-day session whose inactivity clock starts immediately", async () => {
|
||||
vi.useFakeTimers();
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
vi.setSystemTime(now);
|
||||
const create = vi.fn().mockResolvedValue({ id: "session_a" });
|
||||
|
||||
try {
|
||||
const session = await createPortalSessionInTransaction(
|
||||
{ portalSession: { create } } as never,
|
||||
{ tenantId: "tenant_a", portalUserId: "portal_user_a" },
|
||||
{ userAgent: "Portal browser", ipAddressHash: "ip-hash", origin: "https://portal.acme.test" }
|
||||
);
|
||||
|
||||
expect(session.expiresAt).toEqual(new Date(now.getTime() + PORTAL_SESSION_TTL_MS));
|
||||
expect(create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant_a",
|
||||
portalUserId: "portal_user_a",
|
||||
tokenHash: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
lastSeenAt: now,
|
||||
expiresAt: new Date(now.getTime() + PORTAL_SESSION_TTL_MS),
|
||||
userAgent: "Portal browser",
|
||||
ipAddressHash: "ip-hash",
|
||||
origin: "https://portal.acme.test",
|
||||
}),
|
||||
select: { id: true },
|
||||
});
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("appends the successful login audit and workflow trigger in the same transaction after session creation", async () => {
|
||||
const create = vi.fn().mockResolvedValue({ id: "session_a" });
|
||||
const queryRaw = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce([{ outboxId: "portal-audit-login" }])
|
||||
.mockResolvedValueOnce([{ outboxId: "portal-workflow-login", event: "portal.logged_in" }]);
|
||||
|
||||
await createPortalSessionInTransaction(
|
||||
{ portalSession: { create }, $queryRaw: queryRaw } as never,
|
||||
{ tenantId: "tenant_a", portalUserId: "portal_user_a" },
|
||||
{
|
||||
origin: "https://portal.acme.test",
|
||||
audit: {
|
||||
action: PORTAL_AUDIT_ACTIONS.passwordLogin,
|
||||
requestId: "request-login-1",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
expect(queryRaw.mock.invocationCallOrder[0]).toBeGreaterThan(create.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER);
|
||||
expect(queryRaw.mock.calls[0]?.slice(1)).toEqual([PORTAL_AUDIT_ACTIONS.passwordLogin, "portal_user_a", "request-login-1"]);
|
||||
expect(queryRaw.mock.calls[1]?.slice(1)).toEqual(["session_a", PORTAL_AUDIT_ACTIONS.passwordLogin]);
|
||||
});
|
||||
|
||||
it("revokes logout and appends its audit event atomically", async () => {
|
||||
const updateMany = vi.fn().mockResolvedValue({ count: 1 });
|
||||
const queryRaw = vi.fn().mockResolvedValue([{ outboxId: "portal-audit-logout" }]);
|
||||
const transaction = vi.fn(async (effect) => effect({ portalSession: { updateMany }, $queryRaw: queryRaw }));
|
||||
const request = new Request("https://portal.hivegrid.test/acme/logout", { headers: { "x-request-id": "request-logout-1" } });
|
||||
|
||||
await revokePortalSession(sessionResolverIdentity as never, request, { $transaction: transaction } as never);
|
||||
|
||||
expect(transaction).toHaveBeenCalledOnce();
|
||||
expect(queryRaw.mock.invocationCallOrder[0]).toBeGreaterThan(updateMany.mock.invocationCallOrder[0] ?? Number.MAX_SAFE_INTEGER);
|
||||
expect(queryRaw.mock.calls[0]?.slice(1)).toEqual([PORTAL_AUDIT_ACTIONS.logout, "portal_user_a", "request-logout-1"]);
|
||||
});
|
||||
|
||||
it("audits a document release id without passing storage metadata", async () => {
|
||||
const queryRaw = vi.fn().mockResolvedValue([{ outboxId: "portal-audit-download" }]);
|
||||
const request = new Request("https://portal.hivegrid.test/acme/documents/release_a", {
|
||||
headers: { "x-request-id": "request-download-1" },
|
||||
});
|
||||
|
||||
await auditPortalDocumentDownload(sessionResolverIdentity as never, "release_a", request, { $queryRaw: queryRaw } as never);
|
||||
|
||||
expect(queryRaw.mock.calls[0]?.slice(1)).toEqual([PORTAL_AUDIT_ACTIONS.documentDownloaded, "release_a", "request-download-1"]);
|
||||
});
|
||||
|
||||
it("slides both server expiry and last activity only for the same live opaque session", async () => {
|
||||
const now = new Date("2026-07-15T12:00:00.000Z");
|
||||
const identity = {
|
||||
...sessionResolverIdentity,
|
||||
createdAt: new Date("2026-07-01T12:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-15T11:00:00.000Z"),
|
||||
};
|
||||
const updateMany = vi.fn().mockResolvedValue({ count: 1 });
|
||||
const queryRaw = vi.fn().mockResolvedValue([sessionResolverIdentity]);
|
||||
const db = { $queryRaw: queryRaw, portalSession: { updateMany } };
|
||||
|
||||
await expect(refreshPortalSession(identity, "opaque-session", db as never, now)).resolves.toEqual({
|
||||
...identity,
|
||||
lastSeenAt: now,
|
||||
expiresAt: new Date(now.getTime() + PORTAL_SESSION_TTL_MS),
|
||||
});
|
||||
expect(updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
id: identity.portalSessionId,
|
||||
tenantId: identity.tenantId,
|
||||
portalUserId: identity.portalUserId,
|
||||
revokedAt: null,
|
||||
expiresAt: { gt: now },
|
||||
OR: [{ lastSeenAt: { gt: new Date("2026-07-08T12:00:00.000Z") } }, { lastSeenAt: null, createdAt: { gt: new Date("2026-07-08T12:00:00.000Z") } }],
|
||||
},
|
||||
data: { lastSeenAt: now, expiresAt: new Date(now.getTime() + PORTAL_SESSION_TTL_MS) },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not slide a session when the opaque token resolves to another session", async () => {
|
||||
const identity = {
|
||||
...sessionResolverIdentity,
|
||||
createdAt: new Date("2026-07-01T12:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-15T11:00:00.000Z"),
|
||||
};
|
||||
const updateMany = vi.fn();
|
||||
const db = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([{ ...sessionResolverIdentity, portalSessionId: "session_b" }]),
|
||||
portalSession: { updateMany },
|
||||
};
|
||||
|
||||
await expect(refreshPortalSession(identity, "wrong-session", db as never, new Date("2026-07-15T12:00:00.000Z"))).resolves.toBeNull();
|
||||
expect(updateMany).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed when the conditional sliding update no longer matches", async () => {
|
||||
const identity = {
|
||||
...sessionResolverIdentity,
|
||||
createdAt: new Date("2026-07-01T12:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-15T11:00:00.000Z"),
|
||||
};
|
||||
const db = {
|
||||
$queryRaw: vi.fn().mockResolvedValue([sessionResolverIdentity]),
|
||||
portalSession: { updateMany: vi.fn().mockResolvedValue({ count: 0 }) },
|
||||
};
|
||||
|
||||
await expect(refreshPortalSession(identity, "opaque-session", db as never, new Date("2026-07-15T12:00:00.000Z"))).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
+545
@@ -0,0 +1,545 @@
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { getWriteDbClient, type DbClient } from "@hivegrid/db/client.server";
|
||||
import { runWithPortalRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import type { PortalProjectInput } from "@hivegrid/view-models";
|
||||
|
||||
import { readPortalSessionCookie, serializePortalSessionCookie } from "./portal-session-cookie.server";
|
||||
import {
|
||||
createPortalAuthToken,
|
||||
createPortalSessionToken,
|
||||
hashPortalOpaqueToken,
|
||||
PORTAL_SESSION_INACTIVITY_TTL_MS,
|
||||
PORTAL_SESSION_TTL_MS,
|
||||
type PortalAuthTokenPurpose,
|
||||
} from "./portal-auth-token.server";
|
||||
import {
|
||||
appendPortalAuditEvent,
|
||||
appendPortalSetupDenialAudit,
|
||||
PORTAL_AUDIT_ACTIONS,
|
||||
portalAuditRequestId,
|
||||
type PortalSessionAuditAction,
|
||||
} from "./portal-audit.server";
|
||||
import { requirePortalRouteTenantSlug, requireTrustedPortalOrigin, type TrustedPortalOrigin } from "./portal-origin.server";
|
||||
|
||||
const TENANT_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,62}$/u;
|
||||
const PORTAL_IP_HASH_PATTERN = /^[a-f0-9]{64}$/u;
|
||||
|
||||
export type PortalTenantResolution = {
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly tenantName: string;
|
||||
readonly portalTitle: string;
|
||||
readonly imprintUrl: string;
|
||||
readonly privacyUrl: string;
|
||||
readonly termsUrl: string | null;
|
||||
readonly tenantActive: boolean;
|
||||
readonly tenantFrozen: boolean;
|
||||
};
|
||||
|
||||
export type PortalUserResolution = {
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
readonly portalUserId: string;
|
||||
readonly email: string;
|
||||
readonly emailNormalized: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly passwordHash: string | null;
|
||||
readonly status: "invited" | "active";
|
||||
readonly locale: string;
|
||||
readonly emailVerifiedAt: Date | null;
|
||||
readonly authRequireEmailVerification: boolean;
|
||||
};
|
||||
|
||||
export type PortalSessionIdentity = {
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
readonly portalUserId: string;
|
||||
readonly portalSessionId: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly tenantFrozen: boolean;
|
||||
readonly portalTitle: string;
|
||||
readonly viewerFirstName: string;
|
||||
readonly viewerLastName: string;
|
||||
readonly viewerLocale: string;
|
||||
readonly createdAt: Date;
|
||||
readonly lastSeenAt: Date | null;
|
||||
readonly expiresAt: Date;
|
||||
readonly origin: string;
|
||||
};
|
||||
|
||||
type PortalSessionResolverIdentity = Omit<PortalSessionIdentity, "createdAt" | "lastSeenAt">;
|
||||
|
||||
export type PortalSessionContext = {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly origin: TrustedPortalOrigin;
|
||||
readonly responseHeaders: Headers;
|
||||
};
|
||||
|
||||
export type PortalTokenResolution = {
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
readonly portalUserId: string;
|
||||
readonly portalTokenId: string;
|
||||
readonly emailNormalized: string;
|
||||
readonly purpose: PortalAuthTokenPurpose;
|
||||
readonly expiresAt: Date;
|
||||
};
|
||||
|
||||
export type PortalProjectDataset = {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projects: readonly PortalProjectInput[];
|
||||
};
|
||||
|
||||
type PortalTransaction = Prisma.TransactionClient;
|
||||
|
||||
type PortalSessionMetadata = {
|
||||
readonly origin?: string;
|
||||
readonly userAgent?: string | null;
|
||||
readonly ipAddressHash?: string | null;
|
||||
readonly audit?: {
|
||||
readonly action: PortalSessionAuditAction;
|
||||
readonly requestId?: string | null;
|
||||
};
|
||||
};
|
||||
|
||||
export async function resolvePortalTenant(tenantSlug: string, db: DbClient = getWriteDbClient()): Promise<PortalTenantResolution | null> {
|
||||
const slug = normalizeTenantSlug(tenantSlug);
|
||||
const rows = await db.$queryRaw<PortalTenantResolution[]>`SELECT * FROM public.hivegrid_portal_resolve_tenant_slug(${slug})`;
|
||||
const tenant = rows[0] ?? null;
|
||||
return tenant?.tenantActive && normalizeTenantSlug(tenant.tenantSlug) === slug ? tenant : null;
|
||||
}
|
||||
|
||||
export async function resolvePortalUserByEmail(
|
||||
tenantSlug: string,
|
||||
emailNormalized: string,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<PortalUserResolution | null> {
|
||||
const rows = await db.$queryRaw<
|
||||
PortalUserResolution[]
|
||||
>`SELECT * FROM public.hivegrid_portal_resolve_user_email(${normalizeTenantSlug(tenantSlug)}, ${emailNormalized})`;
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function resolvePortalSession(
|
||||
rawSessionToken: string,
|
||||
db: DbClient = getWriteDbClient(),
|
||||
now: Date = new Date()
|
||||
): Promise<PortalSessionIdentity | null> {
|
||||
const tokenHash = hashPortalOpaqueToken(rawSessionToken);
|
||||
const rows = await db.$queryRaw<PortalSessionResolverIdentity[]>`SELECT * FROM public.hivegrid_portal_resolve_session(${tokenHash})`;
|
||||
const resolved = rows[0] ?? null;
|
||||
if (!resolved || !isCanonicalPortalOrigin(resolved.origin)) return null;
|
||||
|
||||
const inactivityCutoff = new Date(now.getTime() - PORTAL_SESSION_INACTIVITY_TTL_MS);
|
||||
const session = await runWithPortalRlsContext(resolved, () =>
|
||||
db.portalSession.findFirst({
|
||||
where: {
|
||||
id: resolved.portalSessionId,
|
||||
tenantId: resolved.tenantId,
|
||||
portalUserId: resolved.portalUserId,
|
||||
revokedAt: null,
|
||||
expiresAt: { gt: now },
|
||||
OR: [{ lastSeenAt: { gt: inactivityCutoff } }, { lastSeenAt: null, createdAt: { gt: inactivityCutoff } }],
|
||||
},
|
||||
select: { createdAt: true, lastSeenAt: true, expiresAt: true },
|
||||
})
|
||||
);
|
||||
return session ? { ...resolved, ...session } : null;
|
||||
}
|
||||
|
||||
export async function resolvePortalToken(
|
||||
rawToken: string,
|
||||
purpose: PortalAuthTokenPurpose,
|
||||
requestedIpHash: string,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<PortalTokenResolution | null> {
|
||||
if (!PORTAL_IP_HASH_PATTERN.test(requestedIpHash)) return null;
|
||||
const rows = await db.$queryRaw<PortalTokenResolution[]>`SELECT * FROM public.hivegrid_portal_resolve_token(${hashPortalOpaqueToken(
|
||||
rawToken
|
||||
)}, ${purpose}, ${requestedIpHash})`;
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export async function auditPortalSetupCapabilityDenial(
|
||||
expectedScope: Pick<PortalTenantResolution, "tenantId" | "portalId">,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<void> {
|
||||
await appendPortalSetupDenialAudit(db, expectedScope);
|
||||
}
|
||||
|
||||
export async function requirePortalTenantFromRequest(
|
||||
request: Request,
|
||||
routeTenantSlug: string | undefined,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<PortalTenantResolution> {
|
||||
const trustedTenantSlug = requirePortalRouteTenantSlug(request, routeTenantSlug);
|
||||
requireTrustedPortalOrigin(request, trustedTenantSlug);
|
||||
const tenant = await resolvePortalTenant(trustedTenantSlug, db);
|
||||
if (!tenant) throw portalNotFound();
|
||||
return tenant;
|
||||
}
|
||||
|
||||
export async function requirePortalSessionIdentity(
|
||||
request: Request,
|
||||
routeTenantSlug: string | undefined,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<PortalSessionIdentity> {
|
||||
const { identity } = await requirePortalSessionRequest(request, routeTenantSlug, db);
|
||||
return identity;
|
||||
}
|
||||
|
||||
export async function requirePortalSessionContext(
|
||||
request: Request,
|
||||
routeTenantSlug: string | undefined,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<PortalSessionContext> {
|
||||
const { identity, origin, rawSession } = await requirePortalSessionRequest(request, routeTenantSlug, db);
|
||||
const refreshedIdentity = await refreshPortalSession(identity, rawSession, db);
|
||||
if (!refreshedIdentity) throw portalNotFound();
|
||||
|
||||
const responseHeaders = new Headers({ "Cache-Control": "no-store" });
|
||||
responseHeaders.append("Set-Cookie", await serializePortalSessionCookie(rawSession, refreshedIdentity.expiresAt));
|
||||
return { identity: refreshedIdentity, origin, responseHeaders };
|
||||
}
|
||||
|
||||
async function requirePortalSessionRequest(
|
||||
request: Request,
|
||||
routeTenantSlug: string | undefined,
|
||||
db: DbClient
|
||||
): Promise<{ readonly identity: PortalSessionIdentity; readonly origin: TrustedPortalOrigin; readonly rawSession: string }> {
|
||||
const trustedTenantSlug = requirePortalRouteTenantSlug(request, routeTenantSlug);
|
||||
const origin = requireTrustedPortalOrigin(request, trustedTenantSlug);
|
||||
const rawSession = await readPortalSessionCookie(request);
|
||||
if (!rawSession) throw portalNotFound();
|
||||
const identity = await resolvePortalSession(rawSession, db);
|
||||
if (!identity || normalizeTenantSlug(identity.tenantSlug) !== trustedTenantSlug || identity.origin !== origin.origin) throw portalNotFound();
|
||||
return { identity, origin, rawSession };
|
||||
}
|
||||
|
||||
export async function issuePortalAuthToken(
|
||||
user: Pick<PortalUserResolution, "tenantId" | "portalUserId">,
|
||||
purpose: PortalAuthTokenPurpose,
|
||||
requestedIpHash: string,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<{ rawToken: string; expiresAt: Date }> {
|
||||
if (!PORTAL_IP_HASH_PATTERN.test(requestedIpHash)) throw new Error("Portal auth token IP binding is invalid.");
|
||||
const token = createPortalAuthToken(purpose);
|
||||
await runWithPortalRlsContext(user, () =>
|
||||
db.$transaction(async (tx) => {
|
||||
await tx.portalToken.updateMany({
|
||||
where: { tenantId: user.tenantId, portalUserId: user.portalUserId, purpose, consumedAt: null, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
await tx.portalToken.create({
|
||||
data: {
|
||||
tenantId: user.tenantId,
|
||||
portalUserId: user.portalUserId,
|
||||
purpose,
|
||||
tokenHash: token.tokenHash,
|
||||
expiresAt: token.expiresAt,
|
||||
requestedIpHash,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
})
|
||||
);
|
||||
return { rawToken: token.rawToken, expiresAt: token.expiresAt };
|
||||
}
|
||||
|
||||
export async function consumePortalAuthToken<T>(
|
||||
rawToken: string,
|
||||
purpose: PortalAuthTokenPurpose,
|
||||
requestedIpHash: string,
|
||||
effect: (tx: PortalTransaction, identity: PortalTokenResolution) => Promise<T>,
|
||||
expectedScope: Pick<PortalTenantResolution, "tenantId" | "portalId">,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<T | null> {
|
||||
const identity = await resolvePortalToken(rawToken, purpose, requestedIpHash, db);
|
||||
if (!identity || identity.tenantId !== expectedScope.tenantId || identity.portalId !== expectedScope.portalId) {
|
||||
return null;
|
||||
}
|
||||
return runWithPortalRlsContext(identity, () =>
|
||||
db.$transaction(async (tx) => {
|
||||
const consumedRows = await tx.$queryRaw<Array<{ consumed: boolean }>>`
|
||||
SELECT public.hivegrid_portal_consume_token(
|
||||
${hashPortalOpaqueToken(rawToken)},
|
||||
${identity.portalTokenId},
|
||||
${purpose},
|
||||
${requestedIpHash},
|
||||
${expectedScope.tenantId},
|
||||
${expectedScope.portalId}
|
||||
) AS consumed
|
||||
`;
|
||||
if (consumedRows[0]?.consumed !== true) return null;
|
||||
return effect(tx, identity);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function createPortalSession(
|
||||
identity: Pick<PortalTokenResolution | PortalUserResolution, "tenantId" | "portalUserId">,
|
||||
metadata: PortalSessionMetadata = {},
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<{ rawToken: string; expiresAt: Date }> {
|
||||
if (!isCanonicalPortalOrigin(metadata.origin)) throw new Error("Portal session requires a canonical trusted origin.");
|
||||
return runWithPortalRlsContext(identity, () => db.$transaction((tx) => createPortalSessionInTransaction(tx, identity, metadata)));
|
||||
}
|
||||
|
||||
export async function createPortalSessionInTransaction(
|
||||
tx: PortalTransaction,
|
||||
identity: Pick<PortalTokenResolution | PortalUserResolution, "tenantId" | "portalUserId">,
|
||||
metadata: PortalSessionMetadata = {}
|
||||
): Promise<{ rawToken: string; expiresAt: Date }> {
|
||||
if (!isCanonicalPortalOrigin(metadata.origin)) throw new Error("Portal session requires a canonical trusted origin.");
|
||||
const now = new Date();
|
||||
const token = createPortalSessionToken({ now });
|
||||
const session = await tx.portalSession.create({
|
||||
data: {
|
||||
tenantId: identity.tenantId,
|
||||
portalUserId: identity.portalUserId,
|
||||
tokenHash: token.tokenHash,
|
||||
expiresAt: token.expiresAt,
|
||||
lastSeenAt: now,
|
||||
userAgent: metadata.userAgent?.slice(0, 512) ?? null,
|
||||
ipAddressHash: metadata.ipAddressHash ?? null,
|
||||
origin: metadata.origin,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
if (metadata.audit) {
|
||||
await appendPortalAuditEvent(tx, {
|
||||
action: metadata.audit.action,
|
||||
targetId: identity.portalUserId,
|
||||
requestId: metadata.audit.requestId,
|
||||
});
|
||||
const workflowRows = await tx.$queryRaw<Array<{ outboxId: string; event: string }>>`
|
||||
SELECT *
|
||||
FROM public.hivegrid_portal_emit_auth_event(${session.id}, ${metadata.audit.action})
|
||||
`;
|
||||
if (workflowRows.length !== 1 || !workflowRows[0]?.outboxId || !workflowRows[0].event) {
|
||||
throw new Error("Portal auth event capability did not append exactly one workflow trigger.");
|
||||
}
|
||||
}
|
||||
return { rawToken: token.rawToken, expiresAt: token.expiresAt };
|
||||
}
|
||||
|
||||
export async function refreshPortalSession(
|
||||
identity: PortalSessionIdentity,
|
||||
rawSessionToken: string,
|
||||
db: DbClient = getWriteDbClient(),
|
||||
now: Date = new Date()
|
||||
): Promise<PortalSessionIdentity | null> {
|
||||
const tokenHash = hashPortalOpaqueToken(rawSessionToken);
|
||||
const rows = await db.$queryRaw<PortalSessionResolverIdentity[]>`SELECT * FROM public.hivegrid_portal_resolve_session(${tokenHash})`;
|
||||
const resolved = rows[0] ?? null;
|
||||
if (
|
||||
!resolved ||
|
||||
resolved.portalSessionId !== identity.portalSessionId ||
|
||||
resolved.tenantId !== identity.tenantId ||
|
||||
resolved.portalUserId !== identity.portalUserId ||
|
||||
resolved.origin !== identity.origin
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const inactivityCutoff = new Date(now.getTime() - PORTAL_SESSION_INACTIVITY_TTL_MS);
|
||||
const expiresAt = new Date(now.getTime() + PORTAL_SESSION_TTL_MS);
|
||||
const refreshed = await runWithPortalRlsContext(identity, () =>
|
||||
db.portalSession.updateMany({
|
||||
where: {
|
||||
id: identity.portalSessionId,
|
||||
tenantId: identity.tenantId,
|
||||
portalUserId: identity.portalUserId,
|
||||
revokedAt: null,
|
||||
expiresAt: { gt: now },
|
||||
OR: [{ lastSeenAt: { gt: inactivityCutoff } }, { lastSeenAt: null, createdAt: { gt: inactivityCutoff } }],
|
||||
},
|
||||
data: { lastSeenAt: now, expiresAt },
|
||||
})
|
||||
);
|
||||
return refreshed.count === 1 ? { ...identity, lastSeenAt: now, expiresAt } : null;
|
||||
}
|
||||
|
||||
export async function revokePortalSession(identity: PortalSessionIdentity, request: Request, db: DbClient = getWriteDbClient()): Promise<void> {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
db.$transaction(async (tx) => {
|
||||
const revoked = await tx.portalSession.updateMany({
|
||||
where: { id: identity.portalSessionId, tenantId: identity.tenantId, portalUserId: identity.portalUserId, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
if (revoked.count !== 1) throw portalNotFound();
|
||||
await appendPortalAuditEvent(tx, {
|
||||
action: PORTAL_AUDIT_ACTIONS.logout,
|
||||
targetId: identity.portalUserId,
|
||||
requestId: portalAuditRequestId(request),
|
||||
});
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function loadPortalProjectDataset(
|
||||
identity: PortalSessionIdentity,
|
||||
db: DbClient = getWriteDbClient(),
|
||||
publicBasePath = `/${identity.tenantSlug}`
|
||||
): Promise<PortalProjectDataset> {
|
||||
const projects = await runWithPortalRlsContext(identity, async () => {
|
||||
const accessRows = await db.portalProjectAccess.findMany({
|
||||
where: { tenantId: identity.tenantId, portalId: identity.portalId, portalUserId: identity.portalUserId, active: true, revokedAt: null },
|
||||
select: {
|
||||
project: {
|
||||
select: {
|
||||
id: true,
|
||||
projektNummer: true,
|
||||
projektname: true,
|
||||
updatedAt: true,
|
||||
pipelineId: true,
|
||||
stageId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const projectRows = accessRows.map((row) => row.project);
|
||||
if (projectRows.length === 0) return [];
|
||||
const pipelineIds = [...new Set(projectRows.map((project) => project.pipelineId))];
|
||||
const projectIds = projectRows.map((project) => project.id);
|
||||
const [visibilityRows, documentRows] = await Promise.all([
|
||||
db.portalStageVisibility.findMany({
|
||||
where: { tenantId: identity.tenantId, portalId: identity.portalId, visible: true },
|
||||
select: { customerLabel: true, stage: { select: { id: true, pipelineId: true, name: true, position: true } } },
|
||||
orderBy: { stage: { position: "asc" } },
|
||||
}),
|
||||
db.portalProjectDocument.findMany({
|
||||
where: {
|
||||
tenantId: identity.tenantId,
|
||||
portalId: identity.portalId,
|
||||
projectId: { in: projectIds },
|
||||
releasedAt: { lte: new Date() },
|
||||
revokedAt: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
projectId: true,
|
||||
releasedAt: true,
|
||||
revokedAt: true,
|
||||
file: { select: { displayName: true, mimeType: true } },
|
||||
},
|
||||
orderBy: { releasedAt: "desc" },
|
||||
}),
|
||||
]);
|
||||
return mapPortalProjectRows({ projectRows, visibilityRows, documentRows, tenantSlug: identity.tenantSlug, publicBasePath, pipelineIds });
|
||||
});
|
||||
return { identity, projects };
|
||||
}
|
||||
|
||||
export async function getPortalReleasedFile(
|
||||
identity: PortalSessionIdentity,
|
||||
releaseId: string,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<{ storageKey: string; displayName: string; scanStatus: string } | null> {
|
||||
return runWithPortalRlsContext(identity, async () => {
|
||||
const rows = await db.$queryRaw<Array<{ storageKey: string; displayName: string; scanStatus: string }>>`
|
||||
SELECT "storageKey", "displayName", "scanStatus"
|
||||
FROM public.hivegrid_portal_resolve_project_document(${releaseId})
|
||||
`;
|
||||
return rows[0] ?? null;
|
||||
});
|
||||
}
|
||||
|
||||
export async function auditPortalDocumentDownload(
|
||||
identity: PortalSessionIdentity,
|
||||
releaseId: string,
|
||||
request: Request,
|
||||
db: DbClient = getWriteDbClient()
|
||||
): Promise<void> {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
appendPortalAuditEvent(db, {
|
||||
action: PORTAL_AUDIT_ACTIONS.documentDownloaded,
|
||||
targetId: releaseId,
|
||||
requestId: portalAuditRequestId(request),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export function mapPortalProjectRows(input: {
|
||||
readonly tenantSlug: string;
|
||||
readonly publicBasePath?: string;
|
||||
readonly pipelineIds: readonly string[];
|
||||
readonly projectRows: readonly {
|
||||
readonly id: string;
|
||||
readonly projektNummer: string;
|
||||
readonly projektname: string;
|
||||
readonly updatedAt: Date;
|
||||
readonly pipelineId: string;
|
||||
readonly stageId: string;
|
||||
}[];
|
||||
readonly visibilityRows: readonly {
|
||||
readonly customerLabel: string | null;
|
||||
readonly stage: { readonly id: string; readonly pipelineId: string; readonly name: string; readonly position: number };
|
||||
}[];
|
||||
readonly documentRows: readonly {
|
||||
readonly id: string;
|
||||
readonly projectId: string;
|
||||
readonly releasedAt: Date;
|
||||
readonly revokedAt: Date | null;
|
||||
readonly file: { readonly displayName: string; readonly mimeType: string };
|
||||
}[];
|
||||
}): PortalProjectInput[] {
|
||||
const allowedPipelines = new Set(input.pipelineIds);
|
||||
return input.projectRows.map((project) => {
|
||||
const stages = input.visibilityRows
|
||||
.filter((visibility) => allowedPipelines.has(visibility.stage.pipelineId) && visibility.stage.pipelineId === project.pipelineId)
|
||||
.map((visibility) => ({
|
||||
id: visibility.stage.id,
|
||||
label: visibility.customerLabel?.trim() || visibility.stage.name,
|
||||
order: visibility.stage.position,
|
||||
visible: true,
|
||||
}));
|
||||
const currentStage = stages.find((stage) => stage.id === project.stageId);
|
||||
const documents = input.documentRows
|
||||
.filter((document) => document.projectId === project.id)
|
||||
.map((document) => ({
|
||||
id: document.id,
|
||||
name: document.file.displayName,
|
||||
mimeType: document.file.mimeType,
|
||||
releasedAt: document.releasedAt.toISOString(),
|
||||
revokedAt: document.revokedAt?.toISOString() ?? null,
|
||||
downloadHref: `${normalizePortalPublicBasePath(input.publicBasePath ?? `/${input.tenantSlug}`)}/documents/${document.id}`,
|
||||
}));
|
||||
return {
|
||||
id: project.id,
|
||||
projectNumber: project.projektNummer,
|
||||
name: project.projektname,
|
||||
updatedAt: project.updatedAt.toISOString(),
|
||||
currentStageOrder: currentStage?.order ?? -1,
|
||||
hasActiveAccess: true,
|
||||
stages,
|
||||
documents,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeTenantSlug(value: string): string {
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!TENANT_SLUG_PATTERN.test(normalized)) throw portalNotFound();
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizePortalPublicBasePath(value: string): string {
|
||||
const normalized = `/${value}`.replace(/\/{2,}/gu, "/").replace(/\/+$/gu, "");
|
||||
return normalized === "/" ? "" : normalized;
|
||||
}
|
||||
|
||||
function isCanonicalPortalOrigin(value: string | null | undefined): value is string {
|
||||
if (!value) return false;
|
||||
try {
|
||||
const origin = new URL(value);
|
||||
return origin.origin === value && origin.pathname === "/" && !origin.username && !origin.password && !origin.search && !origin.hash;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function portalNotFound(): Response {
|
||||
return new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
__resetPortalDomainAdminRateLimitStoreForTests,
|
||||
__setPortalDomainAdminRateLimitStoreForTests,
|
||||
checkPortalDomainAdminRateLimit,
|
||||
portalDomainAdminRateLimitKey,
|
||||
} from "./portal-domain-admin-rate-limit.server";
|
||||
|
||||
const secret = "portal-domain-rate-limit-secret-32-bytes-long";
|
||||
|
||||
describe("portal-domain admin rate limit", () => {
|
||||
beforeEach(() => {
|
||||
__setPortalDomainAdminRateLimitStoreForTests(
|
||||
createSharedStore({ namespace: "portal-domain-admin-rate-limit-test", adapter: new MemoryAdapter() }),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
__resetPortalDomainAdminRateLimitStoreForTests();
|
||||
});
|
||||
|
||||
it("allows five claim attempts and denies the sixth", async () => {
|
||||
const input = { tenantId: "tenant-a1", userId: "user-admin-a", action: "claim-domain", secret } as const;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
await expect(checkPortalDomainAdminRateLimit(input)).resolves.toEqual({ allowed: true });
|
||||
}
|
||||
await expect(checkPortalDomainAdminRateLimit(input)).resolves.toEqual({ allowed: false, retryAfterSeconds: 900 });
|
||||
});
|
||||
|
||||
it("uses the stricter one-hour bucket for recurring add-on cancellation", async () => {
|
||||
const input = { tenantId: "tenant-a1", userId: "user-admin-a", action: "cancel-portal", secret } as const;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
await expect(checkPortalDomainAdminRateLimit(input)).resolves.toEqual({ allowed: true });
|
||||
}
|
||||
await expect(checkPortalDomainAdminRateLimit(input)).resolves.toEqual({ allowed: false, retryAfterSeconds: 3600 });
|
||||
});
|
||||
|
||||
it("limits proof reissues independently to five per hour", async () => {
|
||||
const input = { tenantId: "tenant-a1", userId: "user-admin-a", action: "reissue-proof", secret } as const;
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
await expect(checkPortalDomainAdminRateLimit(input)).resolves.toEqual({ allowed: true });
|
||||
}
|
||||
await expect(checkPortalDomainAdminRateLimit(input)).resolves.toEqual({ allowed: false, retryAfterSeconds: 3600 });
|
||||
});
|
||||
|
||||
it("isolates buckets by tenant, user, and intent without exposing ids", async () => {
|
||||
const first = portalDomainAdminRateLimitKey({ tenantId: "tenant-a1", userId: "user-admin-a", action: "claim-domain", secret });
|
||||
const anotherTenant = portalDomainAdminRateLimitKey({ tenantId: "tenant-b2", userId: "user-admin-a", action: "claim-domain", secret });
|
||||
const anotherUser = portalDomainAdminRateLimitKey({ tenantId: "tenant-a1", userId: "user-admin-b", action: "claim-domain", secret });
|
||||
const anotherIntent = portalDomainAdminRateLimitKey({ tenantId: "tenant-a1", userId: "user-admin-a", action: "verify-dns", secret });
|
||||
|
||||
expect(new Set([first, anotherTenant, anotherUser, anotherIntent])).toHaveLength(4);
|
||||
expect(first).not.toContain("tenant-a1");
|
||||
expect(first).not.toContain("user-admin-a");
|
||||
});
|
||||
|
||||
it("fails closed for unsafe principals and secrets", async () => {
|
||||
await expect(
|
||||
checkPortalDomainAdminRateLimit({ tenantId: "bad", userId: "user-admin-a", action: "remove-domain", secret }),
|
||||
).resolves.toEqual({ allowed: false, retryAfterSeconds: 3600 });
|
||||
await expect(
|
||||
checkPortalDomainAdminRateLimit({ tenantId: "tenant-a1", userId: "user-admin-a", action: "remove-domain", secret: "short" }),
|
||||
).resolves.toEqual({ allowed: false, retryAfterSeconds: 3600 });
|
||||
});
|
||||
});
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
import { createFixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
|
||||
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
export const portalDomainAdminRateLimitActions = [
|
||||
"buy-portal",
|
||||
"cancel-portal",
|
||||
"claim-domain",
|
||||
"buy-domain-setup",
|
||||
"reissue-proof",
|
||||
"verify-dns",
|
||||
"retry-domain",
|
||||
"remove-domain",
|
||||
"switch-domain",
|
||||
"activate-switch",
|
||||
] as const;
|
||||
|
||||
export type PortalDomainAdminRateLimitAction = (typeof portalDomainAdminRateLimitActions)[number];
|
||||
|
||||
export type PortalDomainAdminRateLimitResult =
|
||||
| { readonly allowed: true }
|
||||
| { readonly allowed: false; readonly retryAfterSeconds: number };
|
||||
|
||||
const limits = {
|
||||
"buy-portal": { max: 5, windowSeconds: 15 * 60 },
|
||||
"cancel-portal": { max: 5, windowSeconds: 60 * 60 },
|
||||
"claim-domain": { max: 5, windowSeconds: 15 * 60 },
|
||||
"buy-domain-setup": { max: 5, windowSeconds: 15 * 60 },
|
||||
"reissue-proof": { max: 5, windowSeconds: 60 * 60 },
|
||||
"verify-dns": { max: 10, windowSeconds: 15 * 60 },
|
||||
"retry-domain": { max: 5, windowSeconds: 60 * 60 },
|
||||
"remove-domain": { max: 5, windowSeconds: 60 * 60 },
|
||||
"switch-domain": { max: 5, windowSeconds: 60 * 60 },
|
||||
"activate-switch": { max: 5, windowSeconds: 60 * 60 },
|
||||
} as const satisfies Record<PortalDomainAdminRateLimitAction, { readonly max: number; readonly windowSeconds: number }>;
|
||||
|
||||
const logger = createScopedLogger("customer-portal.domain-admin-rate-limit");
|
||||
let storeFactory: () => SharedStore = () => getSharedStore();
|
||||
|
||||
/**
|
||||
* Distributed, authenticated mutation throttle for the custom-domain admin.
|
||||
* Tenant and user ids are HMAC-pseudonymised before they enter the shared
|
||||
* store. A store/configuration failure denies the mutation.
|
||||
*/
|
||||
export async function checkPortalDomainAdminRateLimit(input: {
|
||||
readonly tenantId: string;
|
||||
readonly userId: string;
|
||||
readonly action: PortalDomainAdminRateLimitAction;
|
||||
readonly secret: string;
|
||||
}): Promise<PortalDomainAdminRateLimitResult> {
|
||||
const limit = limits[input.action];
|
||||
try {
|
||||
const key = portalDomainAdminRateLimitKey(input);
|
||||
const decision = await createFixedWindowRateLimiter({
|
||||
store: storeFactory(),
|
||||
prefix: `portal-domain-admin-v1:${input.action}`,
|
||||
max: limit.max,
|
||||
windowSeconds: limit.windowSeconds,
|
||||
}).consume(key);
|
||||
return decision.allowed ? { allowed: true } : { allowed: false, retryAfterSeconds: limit.windowSeconds };
|
||||
} catch (error) {
|
||||
logger.error(
|
||||
{
|
||||
event: "customer_portal.domain.admin_rate_limit_unavailable",
|
||||
action: input.action,
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
},
|
||||
"Portal-domain admin rate limit unavailable; mutation denied",
|
||||
);
|
||||
return { allowed: false, retryAfterSeconds: limit.windowSeconds };
|
||||
}
|
||||
}
|
||||
|
||||
export function portalDomainAdminRateLimitKey(input: {
|
||||
readonly tenantId: string;
|
||||
readonly userId: string;
|
||||
readonly action: PortalDomainAdminRateLimitAction;
|
||||
readonly secret: string;
|
||||
}): string {
|
||||
const tenantId = normalizePrincipal(input.tenantId);
|
||||
const userId = normalizePrincipal(input.userId);
|
||||
if (!portalDomainAdminRateLimitActions.includes(input.action)) throw new Error("Portal-domain rate-limit action is invalid.");
|
||||
if (input.secret.length < 32) throw new Error("Portal-domain rate-limit secret is invalid.");
|
||||
return createHmac("sha256", input.secret)
|
||||
.update(`portal-domain-admin-v1\0${tenantId}\0${userId}\0${input.action}`)
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
function normalizePrincipal(value: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!/^[A-Za-z0-9_-]{8,191}$/u.test(normalized)) throw new Error("Portal-domain rate-limit principal is invalid.");
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function __setPortalDomainAdminRateLimitStoreForTests(store: SharedStore): void {
|
||||
storeFactory = () => store;
|
||||
}
|
||||
|
||||
export function __resetPortalDomainAdminRateLimitStoreForTests(): void {
|
||||
storeFactory = () => getSharedStore();
|
||||
}
|
||||
+628
@@ -0,0 +1,628 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
getCustomerPortalCheckoutCatalog,
|
||||
getCustomerPortalCommercialEligibility,
|
||||
grantEnterpriseCustomerPortalContract,
|
||||
portalDomainBillingScopeKey,
|
||||
startCustomerPortalMonthlyCheckout,
|
||||
startPortalDomainSetupCheckout,
|
||||
} from "./portal-domain-commercial.server";
|
||||
|
||||
function client(input: {
|
||||
planCode?: string;
|
||||
subscriptionStatus?: string;
|
||||
subscriptionCancelledAt?: Date | null;
|
||||
subscriptionFrozenAt?: Date | null;
|
||||
acquisitions?: Array<{
|
||||
id: string;
|
||||
scopeKey: string;
|
||||
quantity: number;
|
||||
tenantSubscriptionProductId: string | null;
|
||||
cancelledAt?: Date | null;
|
||||
expiredAt?: Date | null;
|
||||
refundedAt?: Date | null;
|
||||
subscriptionProduct: { code: string; kind: "recurring_add_on" | "one_time_setup" | "contract_override" };
|
||||
}>;
|
||||
claim?: {
|
||||
id: string;
|
||||
portalId?: string;
|
||||
billingScopeKey: string | null;
|
||||
txtVerifiedAt?: Date | null;
|
||||
verificationTokenExpiresAt?: Date;
|
||||
claimedAt?: Date;
|
||||
} | null;
|
||||
product?: { id: string; code: string; lagoPlanCode?: string | null; kind: string; active: boolean; public: boolean };
|
||||
catalogProducts?: Array<{
|
||||
id: string;
|
||||
code: string;
|
||||
lagoPlanCode?: string | null;
|
||||
kind: string;
|
||||
active: boolean;
|
||||
public: boolean;
|
||||
prices: Array<{
|
||||
id: string;
|
||||
active: boolean;
|
||||
type: number;
|
||||
billingPeriod: number;
|
||||
price: string;
|
||||
currency: string;
|
||||
lagoPlanCode?: string | null;
|
||||
lagoFeeCode?: string | null;
|
||||
}>;
|
||||
}>;
|
||||
contractClaims?: number;
|
||||
}) {
|
||||
const claim = input.claim
|
||||
? {
|
||||
portalId: "portal_12345678",
|
||||
txtVerifiedAt: new Date("2026-07-17T09:00:00.000Z"),
|
||||
verificationTokenExpiresAt: new Date("2026-07-19T09:00:00.000Z"),
|
||||
claimedAt: new Date("2026-07-17T08:00:00.000Z"),
|
||||
...input.claim,
|
||||
}
|
||||
: null;
|
||||
return {
|
||||
$executeRaw: vi.fn(async () => 1),
|
||||
$queryRaw: vi.fn(async (query: TemplateStringsArray) =>
|
||||
query.join("").includes('"txtVerifiedAt"') && claim ? [claim] : []),
|
||||
tenantSubscription: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
status: input.subscriptionStatus ?? "active",
|
||||
planCode: input.planCode ?? "starter",
|
||||
cancelledAt: input.subscriptionCancelledAt ?? null,
|
||||
frozenAt: input.subscriptionFrozenAt ?? null,
|
||||
})),
|
||||
},
|
||||
tenantProductAcquisition: {
|
||||
findMany: vi.fn(async () => (input.acquisitions ?? []).map((acquisition) => ({
|
||||
cancelledAt: null,
|
||||
expiredAt: null,
|
||||
refundedAt: null,
|
||||
...acquisition,
|
||||
}))),
|
||||
},
|
||||
portalDomainHostnameClaim: {
|
||||
findFirst: vi.fn(async () => claim),
|
||||
findMany: vi.fn(async () => (claim ? [{ id: claim.id }] : [])),
|
||||
count: vi.fn(async () => input.contractClaims ?? 0),
|
||||
},
|
||||
subscriptionProduct: {
|
||||
findFirst: vi.fn(async () => input.product
|
||||
? {
|
||||
...input.product,
|
||||
lagoPlanCode: input.product.lagoPlanCode === undefined
|
||||
? input.product.kind === "recurring_add_on" ? input.product.code : null
|
||||
: input.product.lagoPlanCode,
|
||||
}
|
||||
: null),
|
||||
findMany: vi.fn(async () => (input.catalogProducts ?? []).map((product) => ({
|
||||
...product,
|
||||
lagoPlanCode: product.lagoPlanCode === undefined
|
||||
? product.kind === "recurring_add_on" ? product.code : null
|
||||
: product.lagoPlanCode,
|
||||
prices: product.prices.map((price) => ({
|
||||
...price,
|
||||
lagoPlanCode: price.lagoPlanCode === undefined
|
||||
? product.kind === "recurring_add_on" ? product.code : null
|
||||
: price.lagoPlanCode,
|
||||
lagoFeeCode: price.lagoFeeCode === undefined ? product.code : price.lagoFeeCode,
|
||||
})),
|
||||
}))),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const withClient = (database: ReturnType<typeof client>) => async <T>(_tenantId: string, operation: (value: ReturnType<typeof client>) => Promise<T>) => operation(database);
|
||||
|
||||
function canonicalPortalCatalogProducts(): NonNullable<Parameters<typeof client>[0]["catalogProducts"]> {
|
||||
return [
|
||||
{
|
||||
id: "product_monthly",
|
||||
code: "customer_portal_monthly",
|
||||
kind: "recurring_add_on",
|
||||
active: true,
|
||||
public: true,
|
||||
prices: [{ id: "price_monthly", active: true, type: 1, billingPeriod: 3, price: "19.99", currency: "eur" }],
|
||||
},
|
||||
{
|
||||
id: "product_setup",
|
||||
code: "customer_portal_domain_setup",
|
||||
kind: "one_time_setup",
|
||||
active: true,
|
||||
public: true,
|
||||
prices: [{ id: "price_setup", active: true, type: 0, billingPeriod: 0, price: "299.99", currency: "eur" }],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
describe("customer portal commercial domain contract", () => {
|
||||
it("resolves the one canonical public checkout price for each portal product", async () => {
|
||||
const database = client({
|
||||
catalogProducts: [
|
||||
{
|
||||
id: "product_monthly",
|
||||
code: "customer_portal_monthly",
|
||||
kind: "recurring_add_on",
|
||||
active: true,
|
||||
public: true,
|
||||
prices: [
|
||||
{ id: "price_monthly_old", active: false, type: 1, billingPeriod: 3, price: "18.99", currency: "eur" },
|
||||
{ id: "price_monthly", active: true, type: 1, billingPeriod: 3, price: "19.99", currency: "eur" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "product_domain_setup",
|
||||
code: "customer_portal_domain_setup",
|
||||
kind: "one_time_setup",
|
||||
active: true,
|
||||
public: true,
|
||||
prices: [{ id: "price_domain_setup", active: true, type: 0, billingPeriod: 0, price: "299.99", currency: "EUR" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
await expect(getCustomerPortalCheckoutCatalog(
|
||||
{ tenantId: "tenant_12345678" },
|
||||
{ withTenant: withClient(database) },
|
||||
)).resolves.toEqual({
|
||||
monthlyAddOn: {
|
||||
productId: "product_monthly",
|
||||
priceId: "price_monthly",
|
||||
code: "customer_portal_monthly",
|
||||
kind: "recurring_add_on",
|
||||
amountCents: 1999,
|
||||
currency: "EUR",
|
||||
},
|
||||
customDomainSetup: {
|
||||
productId: "product_domain_setup",
|
||||
priceId: "price_domain_setup",
|
||||
code: "customer_portal_domain_setup",
|
||||
kind: "one_time_setup",
|
||||
amountCents: 29999,
|
||||
currency: "EUR",
|
||||
},
|
||||
});
|
||||
expect(database.subscriptionProduct.findMany).toHaveBeenCalledWith(expect.objectContaining({
|
||||
where: { code: { in: ["customer_portal_monthly", "customer_portal_domain_setup"] } },
|
||||
}));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["duplicate products", [
|
||||
{ id: "product_monthly_a", code: "customer_portal_monthly", kind: "recurring_add_on", active: true, public: true, prices: [{ id: "price_a", active: true, type: 1, billingPeriod: 3, price: "19.99", currency: "eur" }] },
|
||||
{ id: "product_monthly_b", code: "customer_portal_monthly", kind: "recurring_add_on", active: true, public: true, prices: [{ id: "price_b", active: true, type: 1, billingPeriod: 3, price: "19.99", currency: "eur" }] },
|
||||
{ id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true, prices: [{ id: "price_setup", active: true, type: 0, billingPeriod: 0, price: "299.99", currency: "eur" }] },
|
||||
]],
|
||||
["repriced setup", [
|
||||
{ id: "product_monthly", code: "customer_portal_monthly", kind: "recurring_add_on", active: true, public: true, prices: [{ id: "price_monthly", active: true, type: 1, billingPeriod: 3, price: "19.99", currency: "eur" }] },
|
||||
{ id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true, prices: [{ id: "price_setup", active: true, type: 0, billingPeriod: 0, price: "300.00", currency: "eur" }] },
|
||||
]],
|
||||
["multiple active prices", [
|
||||
{ id: "product_monthly", code: "customer_portal_monthly", kind: "recurring_add_on", active: true, public: true, prices: [
|
||||
{ id: "price_monthly_a", active: true, type: 1, billingPeriod: 3, price: "19.99", currency: "eur" },
|
||||
{ id: "price_monthly_b", active: true, type: 1, billingPeriod: 3, price: "19.99", currency: "eur" },
|
||||
] },
|
||||
{ id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true, prices: [{ id: "price_setup", active: true, type: 0, billingPeriod: 0, price: "299.99", currency: "eur" }] },
|
||||
]],
|
||||
])("fails closed on checkout catalog drift: %s", async (_case, catalogProducts) => {
|
||||
const database = client({ catalogProducts });
|
||||
await expect(getCustomerPortalCheckoutCatalog(
|
||||
{ tenantId: "tenant_12345678" },
|
||||
{ withTenant: withClient(database) },
|
||||
)).rejects.toMatchObject({ code: "CHECKOUT_CATALOG_DRIFT" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["recurring product plan", (products: ReturnType<typeof canonicalPortalCatalogProducts>) => {
|
||||
products[0]!.lagoPlanCode = "customer_portal_legacy";
|
||||
}],
|
||||
["recurring price plan", (products: ReturnType<typeof canonicalPortalCatalogProducts>) => {
|
||||
products[0]!.prices[0]!.lagoPlanCode = "customer_portal_legacy";
|
||||
}],
|
||||
["one-time fee", (products: ReturnType<typeof canonicalPortalCatalogProducts>) => {
|
||||
products[1]!.prices[0]!.lagoFeeCode = "customer_portal_legacy";
|
||||
}],
|
||||
])("fails closed on provider-code drift: %s", async (_field, drift) => {
|
||||
const catalogProducts = canonicalPortalCatalogProducts();
|
||||
drift(catalogProducts);
|
||||
const database = client({ catalogProducts });
|
||||
|
||||
await expect(getCustomerPortalCheckoutCatalog(
|
||||
{ tenantId: "tenant_12345678" },
|
||||
{ withTenant: withClient(database) },
|
||||
)).rejects.toMatchObject({ code: "CHECKOUT_CATALOG_DRIFT" });
|
||||
});
|
||||
|
||||
it("requires the 19.99 EUR add-on on Starter and scopes it to the tenant", async () => {
|
||||
const database = client({
|
||||
product: { id: "product_monthly", code: "customer_portal_monthly", kind: "recurring_add_on", active: true, public: true },
|
||||
});
|
||||
let transactionOpen = false;
|
||||
const withTenant = async <T>(_tenantId: string, operation: (value: ReturnType<typeof client>) => Promise<T>): Promise<T> => {
|
||||
transactionOpen = true;
|
||||
try {
|
||||
return await operation(database);
|
||||
} finally {
|
||||
transactionOpen = false;
|
||||
}
|
||||
};
|
||||
const createAcquisition = vi.fn(async (input) => {
|
||||
expect(transactionOpen).toBe(false);
|
||||
return { id: "acq_monthly", status: "payment_pending", productKind: "recurring_add_on", scopeKey: input.scopeKey, checkoutUrl: "https://pay.example", providerPaymentId: "payment", replayed: false } as const;
|
||||
});
|
||||
const reserveAcquisition = vi.fn(async (input) => ({ id: "acq_monthly", status: "pending", productKind: "recurring_add_on", scopeKey: input.scopeKey, checkoutUrl: null, providerPaymentId: null, replayed: false } as const));
|
||||
const reservePolicy = vi.fn(async (_client, input) => ({
|
||||
reservation: await reserveAcquisition(input, { client: database }),
|
||||
paymentPolicyAmountCents: 100_974,
|
||||
}));
|
||||
const eligibility = await getCustomerPortalCommercialEligibility({ tenantId: "tenant_12345678" }, { withTenant: withClient(database) });
|
||||
expect(eligibility).toMatchObject({ portalAllowed: false, monthlyAddOnRequired: true, monthlyAddOnActive: false });
|
||||
await startCustomerPortalMonthlyCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_monthly",
|
||||
priceId: "price_12345678",
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, { withTenant, createAcquisition, reserveAcquisition, reservePolicy });
|
||||
expect(reserveAcquisition).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ scopeKey: "tenant" }),
|
||||
expect.objectContaining({ client: database }),
|
||||
);
|
||||
expect(reserveAcquisition.mock.invocationCallOrder[0]).toBeLessThan(createAcquisition.mock.invocationCallOrder[0] ?? 0);
|
||||
expect(createAcquisition).toHaveBeenCalledWith(expect.objectContaining({
|
||||
scopeKey: "tenant",
|
||||
paymentPolicyAmountCents: 100_974,
|
||||
}));
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "Business base plan",
|
||||
planCode: "business",
|
||||
acquisitions: [],
|
||||
},
|
||||
{
|
||||
name: "active monthly add-on",
|
||||
planCode: "starter",
|
||||
acquisitions: [{
|
||||
id: "acq_monthly",
|
||||
scopeKey: "tenant",
|
||||
quantity: 1,
|
||||
tenantSubscriptionProductId: "tenant_product_monthly",
|
||||
subscriptionProduct: { code: "customer_portal_monthly", kind: "recurring_add_on" as const },
|
||||
}],
|
||||
},
|
||||
{
|
||||
name: "Enterprise contract",
|
||||
planCode: "starter",
|
||||
acquisitions: [{
|
||||
id: "acq_contract",
|
||||
scopeKey: "tenant",
|
||||
quantity: 1,
|
||||
tenantSubscriptionProductId: null,
|
||||
subscriptionProduct: { code: "customer_portal_enterprise_contract", kind: "contract_override" as const },
|
||||
}],
|
||||
},
|
||||
])("does not create another monthly checkout when the portal is included by $name", async ({ planCode, acquisitions }) => {
|
||||
const database = client({
|
||||
planCode,
|
||||
acquisitions,
|
||||
product: { id: "product_monthly", code: "customer_portal_monthly", kind: "recurring_add_on", active: true, public: true },
|
||||
});
|
||||
const reserveAcquisition = vi.fn();
|
||||
const createAcquisition = vi.fn();
|
||||
|
||||
await expect(startCustomerPortalMonthlyCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_monthly",
|
||||
priceId: "price_12345678",
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, { withTenant: withClient(database), reserveAcquisition, createAcquisition }))
|
||||
.rejects.toMatchObject({ code: "PORTAL_ENTITLEMENT_REQUIRED" });
|
||||
expect(reserveAcquisition).not.toHaveBeenCalled();
|
||||
expect(createAcquisition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not start a monthly checkout without an active base subscription", async () => {
|
||||
const database = client({
|
||||
planCode: "starter",
|
||||
subscriptionStatus: "cancelled",
|
||||
product: { id: "product_monthly", code: "customer_portal_monthly", kind: "recurring_add_on", active: true, public: true },
|
||||
});
|
||||
const reserveAcquisition = vi.fn();
|
||||
const createAcquisition = vi.fn();
|
||||
|
||||
await expect(startCustomerPortalMonthlyCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_monthly",
|
||||
priceId: "price_12345678",
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, { withTenant: withClient(database), reserveAcquisition, createAcquisition }))
|
||||
.rejects.toMatchObject({ code: "PORTAL_ENTITLEMENT_REQUIRED" });
|
||||
expect(reserveAcquisition).not.toHaveBeenCalled();
|
||||
expect(createAcquisition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["cancelled", { subscriptionCancelledAt: new Date("2026-07-17T09:00:00.000Z") }],
|
||||
["frozen", { subscriptionFrozenAt: new Date("2026-07-17T09:00:00.000Z") }],
|
||||
])("fails closed when an active base subscription is %s by marker", async (_state, marker) => {
|
||||
const database = client({
|
||||
planCode: "business",
|
||||
subscriptionStatus: "active",
|
||||
...marker,
|
||||
});
|
||||
|
||||
await expect(getCustomerPortalCommercialEligibility(
|
||||
{ tenantId: "tenant_12345678" },
|
||||
{ withTenant: withClient(database) },
|
||||
)).resolves.toMatchObject({
|
||||
subscriptionActive: false,
|
||||
portalAllowed: false,
|
||||
portalSource: "missing",
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["cancelledAt", "expiredAt", "refundedAt"] as const)(
|
||||
"ignores an active add-on with the terminal %s marker",
|
||||
async (marker) => {
|
||||
const database = client({
|
||||
acquisitions: [{
|
||||
id: "acq_monthly",
|
||||
scopeKey: "tenant",
|
||||
quantity: 1,
|
||||
tenantSubscriptionProductId: "tenant_product_monthly",
|
||||
cancelledAt: null,
|
||||
expiredAt: null,
|
||||
refundedAt: null,
|
||||
[marker]: new Date("2026-07-17T09:00:00.000Z"),
|
||||
subscriptionProduct: { code: "customer_portal_monthly", kind: "recurring_add_on" },
|
||||
}],
|
||||
});
|
||||
|
||||
await expect(getCustomerPortalCommercialEligibility(
|
||||
{ tenantId: "tenant_12345678" },
|
||||
{ withTenant: withClient(database) },
|
||||
)).resolves.toMatchObject({
|
||||
portalAllowed: false,
|
||||
monthlyAddOnActive: false,
|
||||
monthlyAddOnSubscriptionProductId: null,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("returns only the active tenant-scoped add-on product id for provider-first cancellation", async () => {
|
||||
const database = client({
|
||||
acquisitions: [{
|
||||
id: "acq_monthly",
|
||||
scopeKey: "tenant",
|
||||
quantity: 1,
|
||||
tenantSubscriptionProductId: "tenant_product_monthly",
|
||||
subscriptionProduct: { code: "customer_portal_monthly", kind: "recurring_add_on" },
|
||||
}],
|
||||
});
|
||||
|
||||
await expect(getCustomerPortalCommercialEligibility({ tenantId: "tenant_12345678" }, { withTenant: withClient(database) }))
|
||||
.resolves.toMatchObject({
|
||||
portalSource: "recurring_add_on",
|
||||
monthlyAddOnSubscriptionProductId: "tenant_product_monthly",
|
||||
});
|
||||
});
|
||||
|
||||
it("includes the portal in Business but keeps the 299.99 EUR hostname setup claim-bound", async () => {
|
||||
const claim = { id: "claim_12345678", billingScopeKey: null };
|
||||
const database = client({
|
||||
planCode: "business",
|
||||
claim,
|
||||
product: { id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true },
|
||||
});
|
||||
const createAcquisition = vi.fn(async (input) => ({ id: "acq_setup", status: "payment_pending", productKind: "one_time_setup", scopeKey: input.scopeKey, checkoutUrl: "https://pay.example", providerPaymentId: "payment", replayed: false } as const));
|
||||
const reserveAcquisition = vi.fn(async (input) => ({ id: "acq_setup", status: "pending", productKind: "one_time_setup", scopeKey: input.scopeKey, checkoutUrl: null, providerPaymentId: null, replayed: false } as const));
|
||||
const eligibility = await getCustomerPortalCommercialEligibility({ tenantId: "tenant_12345678", claimId: claim.id }, { withTenant: withClient(database) });
|
||||
expect(eligibility).toMatchObject({ portalAllowed: true, portalSource: "base_plan", domainSetupActive: false });
|
||||
await startPortalDomainSetupCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_setup",
|
||||
priceId: "price_12345678",
|
||||
claimId: claim.id,
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, { withTenant: withClient(database), createAcquisition, reserveAcquisition, now: () => new Date("2026-07-17T10:00:00.000Z") });
|
||||
expect(database.$executeRaw).toHaveBeenCalledOnce();
|
||||
expect(database.$queryRaw).toHaveBeenCalledTimes(4);
|
||||
expect(reserveAcquisition).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ scopeKey: portalDomainBillingScopeKey(claim.id) }),
|
||||
expect.objectContaining({ client: database }),
|
||||
);
|
||||
expect(reserveAcquisition.mock.invocationCallOrder[0]).toBeLessThan(createAcquisition.mock.invocationCallOrder[0] ?? 0);
|
||||
expect(createAcquisition).toHaveBeenCalledWith(expect.objectContaining({ scopeKey: portalDomainBillingScopeKey(claim.id) }));
|
||||
});
|
||||
|
||||
it("fails closed before billing when the locked claim disappeared during expiry reclaim", async () => {
|
||||
const database = client({
|
||||
claim: { id: "claim_raced", billingScopeKey: null },
|
||||
product: { id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true },
|
||||
});
|
||||
database.$queryRaw.mockResolvedValue([]);
|
||||
const reserveAcquisition = vi.fn();
|
||||
const createAcquisition = vi.fn();
|
||||
|
||||
await expect(startPortalDomainSetupCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_setup",
|
||||
priceId: "price_12345678",
|
||||
claimId: "claim_raced",
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, { withTenant: withClient(database), reserveAcquisition, createAcquisition, now: () => new Date("2026-07-17T10:00:00.000Z") })).rejects.toMatchObject({ code: "CLAIM_NOT_FOUND" });
|
||||
expect(reserveAcquisition).not.toHaveBeenCalled();
|
||||
expect(createAcquisition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "paid hostname setup",
|
||||
planCode: "business",
|
||||
acquisitions: [{
|
||||
id: "acq_setup",
|
||||
scopeKey: portalDomainBillingScopeKey("claim_12345678"),
|
||||
quantity: 1,
|
||||
tenantSubscriptionProductId: "tenant_product_setup",
|
||||
subscriptionProduct: { code: "customer_portal_domain_setup", kind: "one_time_setup" as const },
|
||||
}],
|
||||
},
|
||||
{
|
||||
name: "Enterprise-included hostname setup",
|
||||
planCode: "starter",
|
||||
acquisitions: [{
|
||||
id: "acq_contract",
|
||||
scopeKey: "tenant",
|
||||
quantity: 1,
|
||||
tenantSubscriptionProductId: null,
|
||||
subscriptionProduct: { code: "customer_portal_enterprise_contract", kind: "contract_override" as const },
|
||||
}],
|
||||
},
|
||||
])("does not create another setup checkout for $name", async ({ planCode, acquisitions }) => {
|
||||
const database = client({
|
||||
planCode,
|
||||
acquisitions,
|
||||
claim: { id: "claim_12345678", billingScopeKey: null },
|
||||
product: { id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true },
|
||||
});
|
||||
const reserveAcquisition = vi.fn();
|
||||
const createAcquisition = vi.fn();
|
||||
|
||||
await expect(startPortalDomainSetupCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_setup",
|
||||
priceId: "price_12345678",
|
||||
claimId: "claim_12345678",
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, {
|
||||
withTenant: withClient(database),
|
||||
reserveAcquisition,
|
||||
createAcquisition,
|
||||
now: () => new Date("2026-07-17T10:00:00.000Z"),
|
||||
})).rejects.toMatchObject({ code: "CONTRACT_SETUP_ALREADY_CONSUMED" });
|
||||
expect(reserveAcquisition).not.toHaveBeenCalled();
|
||||
expect(createAcquisition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not start a setup checkout before portal entitlement is active", async () => {
|
||||
const database = client({
|
||||
planCode: "starter",
|
||||
claim: { id: "claim_12345678", billingScopeKey: null },
|
||||
product: { id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true },
|
||||
});
|
||||
const reserveAcquisition = vi.fn();
|
||||
const createAcquisition = vi.fn();
|
||||
|
||||
await expect(startPortalDomainSetupCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_setup",
|
||||
priceId: "price_12345678",
|
||||
claimId: "claim_12345678",
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, {
|
||||
withTenant: withClient(database),
|
||||
reserveAcquisition,
|
||||
createAcquisition,
|
||||
now: () => new Date("2026-07-17T10:00:00.000Z"),
|
||||
})).rejects.toMatchObject({ code: "PORTAL_ENTITLEMENT_REQUIRED" });
|
||||
expect(reserveAcquisition).not.toHaveBeenCalled();
|
||||
expect(createAcquisition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires a fresh TXT ownership proof before creating a paid setup checkout", async () => {
|
||||
const database = client({
|
||||
claim: { id: "claim_unproven", billingScopeKey: null, txtVerifiedAt: null },
|
||||
product: { id: "product_setup", code: "customer_portal_domain_setup", kind: "one_time_setup", active: true, public: true },
|
||||
});
|
||||
const reserveAcquisition = vi.fn();
|
||||
const createAcquisition = vi.fn();
|
||||
|
||||
await expect(startPortalDomainSetupCheckout({
|
||||
tenantId: "tenant_12345678",
|
||||
tenantName: "ACME",
|
||||
userId: "user_12345678",
|
||||
userEmail: "admin@example.com",
|
||||
userName: "Admin",
|
||||
productId: "product_setup",
|
||||
priceId: "price_12345678",
|
||||
claimId: "claim_unproven",
|
||||
redirectUrl: "https://app.example/return",
|
||||
webhookUrl: "https://api.example/webhook",
|
||||
}, {
|
||||
withTenant: withClient(database),
|
||||
reserveAcquisition,
|
||||
createAcquisition,
|
||||
now: () => new Date("2026-07-17T10:00:00.000Z"),
|
||||
})).rejects.toMatchObject({ code: "OWNERSHIP_PROOF_REQUIRED" });
|
||||
expect(reserveAcquisition).not.toHaveBeenCalled();
|
||||
expect(createAcquisition).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("grants one non-public Enterprise contract without a zero-value checkout", async () => {
|
||||
const database = client({
|
||||
product: { id: "product_contract", code: "customer_portal_enterprise_contract", kind: "contract_override", active: true, public: false },
|
||||
});
|
||||
const grantContract = vi.fn(async (input) => ({ id: "acq_contract", status: "active", productKind: "contract_override", scopeKey: input.scopeKey, checkoutUrl: null, providerPaymentId: null, replayed: false } as const));
|
||||
await grantEnterpriseCustomerPortalContract({
|
||||
tenantId: "tenant_12345678",
|
||||
actorUserId: "user_12345678",
|
||||
productId: "product_contract",
|
||||
contractReference: "contract-2026-1",
|
||||
quantity: 1,
|
||||
}, { withTenant: withClient(database), grantContract });
|
||||
expect(grantContract).toHaveBeenCalledWith(expect.objectContaining({ scopeKey: "tenant", quantity: 1 }));
|
||||
});
|
||||
|
||||
it("does not let an Enterprise setup grant leak to a second hostname claim", async () => {
|
||||
const contract = {
|
||||
id: "acq_contract",
|
||||
scopeKey: "tenant",
|
||||
quantity: 1,
|
||||
tenantSubscriptionProductId: null,
|
||||
subscriptionProduct: { code: "customer_portal_enterprise_contract", kind: "contract_override" as const },
|
||||
};
|
||||
const database = client({
|
||||
acquisitions: [contract],
|
||||
claim: { id: "claim_12345678", billingScopeKey: null },
|
||||
contractClaims: 1,
|
||||
});
|
||||
const eligibility = await getCustomerPortalCommercialEligibility({ tenantId: "tenant_12345678", claimId: "claim_12345678" }, { withTenant: withClient(database) });
|
||||
expect(eligibility).toMatchObject({ portalSource: "contract_override", domainSetupIncludedByContract: false, domainSetupActive: false });
|
||||
});
|
||||
});
|
||||
+580
@@ -0,0 +1,580 @@
|
||||
import {
|
||||
customerPortalPlanCommercialMapping,
|
||||
customerPortalCommercialProducts,
|
||||
customerPortalProductCodes,
|
||||
entitlementPlanIds,
|
||||
} from "@hivegrid/entitlements";
|
||||
|
||||
import {
|
||||
createProductAcquisition,
|
||||
grantContractProductAcquisition,
|
||||
reserveProductAcquisitionLedger,
|
||||
type CreateProductAcquisitionInput,
|
||||
type GrantContractProductInput,
|
||||
type ProductAcquisitionClient,
|
||||
type ProductAcquisitionResult,
|
||||
} from "~/services/billing/product-acquisition.server";
|
||||
import {
|
||||
reserveRecurringProductCheckoutLedgerWithClient,
|
||||
type RecurringCheckoutPolicyClient,
|
||||
} from "~/services/billing/recurring-checkout-policy.server";
|
||||
import { acquirePortalDomainBillingActivationLocks } from "@hivegrid/db/portal-domain-billing-fence.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
export const PORTAL_MONTHLY_SCOPE_KEY = "tenant" as const;
|
||||
export const PORTAL_DOMAIN_SCOPE_PREFIX = "portal-domain:" as const;
|
||||
export const PORTAL_ENTERPRISE_SCOPE_KEY = "tenant" as const;
|
||||
|
||||
type ActiveAcquisition = {
|
||||
readonly id: string;
|
||||
readonly scopeKey: string;
|
||||
readonly quantity: number;
|
||||
readonly tenantSubscriptionProductId: string | null;
|
||||
readonly cancelledAt: Date | null;
|
||||
readonly expiredAt: Date | null;
|
||||
readonly refundedAt: Date | null;
|
||||
readonly subscriptionProduct: {
|
||||
readonly code: string | null;
|
||||
readonly kind: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override";
|
||||
};
|
||||
};
|
||||
|
||||
type CommercialCatalogPrice = {
|
||||
readonly id: string;
|
||||
readonly active: boolean;
|
||||
readonly type: number;
|
||||
readonly billingPeriod: number;
|
||||
readonly price: number | string | { toString(): string };
|
||||
readonly currency: string;
|
||||
readonly lagoPlanCode: string | null;
|
||||
readonly lagoFeeCode: string | null;
|
||||
};
|
||||
|
||||
type CommercialCatalogProduct = {
|
||||
readonly id: string;
|
||||
readonly code: string | null;
|
||||
readonly lagoPlanCode: string | null;
|
||||
readonly kind: string;
|
||||
readonly active: boolean;
|
||||
readonly public: boolean;
|
||||
readonly prices: CommercialCatalogPrice[];
|
||||
};
|
||||
|
||||
export type CommercialReadClient = {
|
||||
$executeRaw(query: TemplateStringsArray, ...values: unknown[]): Promise<number>;
|
||||
$queryRaw<T = unknown>(query: TemplateStringsArray, ...values: unknown[]): Promise<T>;
|
||||
tenantSubscription: {
|
||||
findUnique(args: Record<string, unknown>): Promise<{
|
||||
status: string;
|
||||
planCode: string | null;
|
||||
cancelledAt: Date | null;
|
||||
frozenAt: Date | null;
|
||||
} | null>;
|
||||
};
|
||||
tenantProductAcquisition: {
|
||||
findMany(args: Record<string, unknown>): Promise<ActiveAcquisition[]>;
|
||||
};
|
||||
portalDomainHostnameClaim: {
|
||||
findFirst(args: Record<string, unknown>): Promise<{ id: string; portalId: string; billingScopeKey: string | null } | null>;
|
||||
findMany(args: Record<string, unknown>): Promise<Array<{ id: string }>>;
|
||||
count(args: Record<string, unknown>): Promise<number>;
|
||||
};
|
||||
subscriptionProduct: {
|
||||
findFirst(args: Record<string, unknown>): Promise<{
|
||||
id: string;
|
||||
code: string | null;
|
||||
lagoPlanCode: string | null;
|
||||
kind: string;
|
||||
active: boolean;
|
||||
public: boolean;
|
||||
} | null>;
|
||||
findMany(args: Record<string, unknown>): Promise<CommercialCatalogProduct[]>;
|
||||
};
|
||||
};
|
||||
|
||||
type WithTenantCommercialClient = <T>(
|
||||
tenantId: string,
|
||||
operation: (client: CommercialReadClient) => Promise<T>,
|
||||
) => Promise<T>;
|
||||
|
||||
const defaultWithTenant: WithTenantCommercialClient = (tenantId, operation) =>
|
||||
withTenantRLS(tenantId, (tx) => operation(tx as unknown as CommercialReadClient));
|
||||
|
||||
const PORTAL_DOMAIN_CLAIM_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export type CustomerPortalCommercialEligibility = {
|
||||
readonly subscriptionActive: boolean;
|
||||
readonly planCode: string | null;
|
||||
readonly portalAllowed: boolean;
|
||||
readonly portalSource: "base_plan" | "recurring_add_on" | "contract_override" | "missing";
|
||||
readonly monthlyAddOnRequired: boolean;
|
||||
readonly monthlyAddOnActive: boolean;
|
||||
readonly monthlyAddOnSubscriptionProductId: string | null;
|
||||
readonly domainSetupActive: boolean;
|
||||
readonly domainSetupIncludedByContract: boolean;
|
||||
readonly domainSetupAcquisitionId: string | null;
|
||||
readonly enterpriseContractAcquisitionId: string | null;
|
||||
readonly domainScopeKey: string | null;
|
||||
};
|
||||
|
||||
export type CustomerPortalCheckoutCatalogItem = {
|
||||
readonly productId: string;
|
||||
readonly priceId: string;
|
||||
readonly code: string;
|
||||
readonly kind: "recurring_add_on" | "one_time_setup";
|
||||
readonly amountCents: number;
|
||||
readonly currency: "EUR";
|
||||
};
|
||||
|
||||
export type CustomerPortalCheckoutCatalog = {
|
||||
readonly monthlyAddOn: CustomerPortalCheckoutCatalogItem & {
|
||||
readonly code: typeof customerPortalProductCodes.monthlyAddOn;
|
||||
readonly kind: "recurring_add_on";
|
||||
readonly amountCents: number;
|
||||
};
|
||||
readonly customDomainSetup: CustomerPortalCheckoutCatalogItem & {
|
||||
readonly code: typeof customerPortalProductCodes.customDomainSetup;
|
||||
readonly kind: "one_time_setup";
|
||||
readonly amountCents: number;
|
||||
};
|
||||
};
|
||||
|
||||
function requirePublicCheckoutPrice(
|
||||
product: { readonly amountCents: number | null; readonly currency: "EUR" | null },
|
||||
): { readonly amountCents: number; readonly currency: "EUR" } {
|
||||
if (!Number.isSafeInteger(product.amountCents) || (product.amountCents ?? 0) <= 0 || product.currency !== "EUR") {
|
||||
throw new Error("Customer-portal checkout products require a positive EUR catalog price");
|
||||
}
|
||||
return { amountCents: product.amountCents!, currency: product.currency };
|
||||
}
|
||||
|
||||
/** Single price contract shared by catalog validation, checkout and the admin VM. */
|
||||
export const customerPortalCheckoutPriceContract = Object.freeze({
|
||||
monthlyAddOn: Object.freeze(requirePublicCheckoutPrice(customerPortalCommercialProducts.monthlyAddOn)),
|
||||
customDomainSetup: Object.freeze(requirePublicCheckoutPrice(customerPortalCommercialProducts.customDomainSetup)),
|
||||
});
|
||||
|
||||
export class PortalDomainCommercialError extends Error {
|
||||
override readonly name = "PortalDomainCommercialError";
|
||||
|
||||
constructor(
|
||||
readonly code:
|
||||
| "PORTAL_ENTITLEMENT_REQUIRED"
|
||||
| "CLAIM_NOT_FOUND"
|
||||
| "OWNERSHIP_PROOF_REQUIRED"
|
||||
| "PRODUCT_NOT_FOUND"
|
||||
| "PRODUCT_CODE_MISMATCH"
|
||||
| "CONTRACT_SETUP_ALREADY_CONSUMED"
|
||||
| "CHECKOUT_CATALOG_DRIFT",
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves checkout identifiers from the catalog under tenant RLS. The route
|
||||
* never hard-codes database IDs, and any duplicate, stale or repriced public
|
||||
* row fails closed instead of charging an unintended product.
|
||||
*/
|
||||
export async function getCustomerPortalCheckoutCatalog(
|
||||
input: { readonly tenantId: string },
|
||||
dependencies: { readonly withTenant?: WithTenantCommercialClient } = {},
|
||||
): Promise<CustomerPortalCheckoutCatalog> {
|
||||
const withTenant = dependencies.withTenant ?? defaultWithTenant;
|
||||
return withTenant(input.tenantId, async (client) => {
|
||||
const products = await client.subscriptionProduct.findMany({
|
||||
where: {
|
||||
code: { in: [customerPortalProductCodes.monthlyAddOn, customerPortalProductCodes.customDomainSetup] },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
lagoPlanCode: true,
|
||||
kind: true,
|
||||
active: true,
|
||||
public: true,
|
||||
prices: {
|
||||
select: {
|
||||
id: true,
|
||||
active: true,
|
||||
type: true,
|
||||
billingPeriod: true,
|
||||
price: true,
|
||||
currency: true,
|
||||
lagoPlanCode: true,
|
||||
lagoFeeCode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
return {
|
||||
monthlyAddOn: requireCatalogItem(products, {
|
||||
code: customerPortalProductCodes.monthlyAddOn,
|
||||
kind: "recurring_add_on",
|
||||
priceType: 1,
|
||||
billingPeriod: 3,
|
||||
amountCents: customerPortalCheckoutPriceContract.monthlyAddOn.amountCents,
|
||||
}),
|
||||
customDomainSetup: requireCatalogItem(products, {
|
||||
code: customerPortalProductCodes.customDomainSetup,
|
||||
kind: "one_time_setup",
|
||||
priceType: 0,
|
||||
billingPeriod: 0,
|
||||
amountCents: customerPortalCheckoutPriceContract.customDomainSetup.amountCents,
|
||||
}),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function getCustomerPortalCommercialEligibility(
|
||||
input: { readonly tenantId: string; readonly claimId?: string },
|
||||
dependencies: { readonly withTenant?: WithTenantCommercialClient } = {},
|
||||
): Promise<CustomerPortalCommercialEligibility> {
|
||||
const withTenant = dependencies.withTenant ?? defaultWithTenant;
|
||||
return withTenant(input.tenantId, (client) => getCustomerPortalCommercialEligibilityWithClient(client, input));
|
||||
}
|
||||
|
||||
export function portalDomainBillingScopeKey(claimId: string): string {
|
||||
const normalized = normalizeIdentifier(claimId);
|
||||
return `${PORTAL_DOMAIN_SCOPE_PREFIX}${normalized}`;
|
||||
}
|
||||
|
||||
export function portalEnterpriseClaimScopeKey(acquisitionId: string): string {
|
||||
return `enterprise-contract:${normalizeIdentifier(acquisitionId)}`;
|
||||
}
|
||||
|
||||
export async function startCustomerPortalMonthlyCheckout(
|
||||
input: Omit<CreateProductAcquisitionInput, "scopeKey">,
|
||||
dependencies: {
|
||||
readonly withTenant?: WithTenantCommercialClient;
|
||||
readonly createAcquisition?: typeof createProductAcquisition;
|
||||
readonly reserveAcquisition?: typeof reserveProductAcquisitionLedger;
|
||||
readonly reservePolicy?: typeof reserveRecurringProductCheckoutLedgerWithClient;
|
||||
} = {},
|
||||
): Promise<ProductAcquisitionResult> {
|
||||
const withTenant = dependencies.withTenant ?? defaultWithTenant;
|
||||
const lockedPolicy = await withTenant(input.tenantId, async (client) => {
|
||||
// Contract grants, product activation/revocation and portal-domain
|
||||
// lifecycle transitions use the same lock order. The eligibility read and
|
||||
// the local checkout reservation therefore form one fail-closed decision.
|
||||
await acquirePortalDomainBillingActivationLocks(client, { tenantId: input.tenantId });
|
||||
await assertPortalProductWithClient(
|
||||
client,
|
||||
input.productId,
|
||||
customerPortalProductCodes.monthlyAddOn,
|
||||
"recurring_add_on",
|
||||
true,
|
||||
);
|
||||
const eligibility = await getCustomerPortalCommercialEligibilityWithClient(client, {
|
||||
tenantId: input.tenantId,
|
||||
});
|
||||
if (
|
||||
!eligibility.subscriptionActive
|
||||
|| !eligibility.monthlyAddOnRequired
|
||||
|| eligibility.portalAllowed
|
||||
|| eligibility.monthlyAddOnActive
|
||||
) {
|
||||
throw new PortalDomainCommercialError("PORTAL_ENTITLEMENT_REQUIRED");
|
||||
}
|
||||
return (dependencies.reservePolicy ?? reserveRecurringProductCheckoutLedgerWithClient)(
|
||||
client as unknown as RecurringCheckoutPolicyClient,
|
||||
{ ...input, scopeKey: PORTAL_MONTHLY_SCOPE_KEY },
|
||||
{},
|
||||
{ reserveLedger: dependencies.reserveAcquisition },
|
||||
);
|
||||
});
|
||||
return (dependencies.createAcquisition ?? createProductAcquisition)({
|
||||
...input,
|
||||
scopeKey: PORTAL_MONTHLY_SCOPE_KEY,
|
||||
paymentPolicyAmountCents: lockedPolicy.paymentPolicyAmountCents,
|
||||
});
|
||||
}
|
||||
|
||||
export async function startPortalDomainSetupCheckout(
|
||||
input: Omit<CreateProductAcquisitionInput, "scopeKey"> & { readonly claimId: string },
|
||||
dependencies: {
|
||||
readonly withTenant?: WithTenantCommercialClient;
|
||||
readonly createAcquisition?: typeof createProductAcquisition;
|
||||
readonly reserveAcquisition?: typeof reserveProductAcquisitionLedger;
|
||||
readonly now?: () => Date;
|
||||
} = {},
|
||||
): Promise<ProductAcquisitionResult> {
|
||||
const withTenant = dependencies.withTenant ?? defaultWithTenant;
|
||||
const { claimId: _claimId, ...acquisitionInput } = input;
|
||||
const scopeKey = await withTenant(input.tenantId, async (client) => {
|
||||
const observedClaim = await client.portalDomainHostnameClaim.findFirst({
|
||||
where: { id: input.claimId, tenantId: input.tenantId, releasedAt: null },
|
||||
select: { id: true, portalId: true, billingScopeKey: true },
|
||||
});
|
||||
if (!observedClaim) throw new PortalDomainCommercialError("CLAIM_NOT_FOUND");
|
||||
|
||||
// Serialize with the claim capability's per-portal lock, then lock the
|
||||
// concrete claim row. The initial ledger reservation below therefore
|
||||
// commits atomically with claim existence and cannot become orphaned by a
|
||||
// concurrent expiry reclaim.
|
||||
await client.$executeRaw`SELECT pg_advisory_xact_lock(
|
||||
hashtextextended('portal-domain-portal:' || ${input.tenantId} || ':' || ${observedClaim.portalId}, 26000)
|
||||
)`;
|
||||
await acquirePortalDomainBillingActivationLocks(client, {
|
||||
tenantId: input.tenantId,
|
||||
claimId: observedClaim.id,
|
||||
});
|
||||
const lockedClaims = await client.$queryRaw<Array<{
|
||||
id: string;
|
||||
portalId: string;
|
||||
billingScopeKey: string | null;
|
||||
txtVerifiedAt: Date | null;
|
||||
verificationTokenExpiresAt: Date;
|
||||
claimedAt: Date;
|
||||
}>>`
|
||||
SELECT "id", "portalId", "billingScopeKey", "txtVerifiedAt", "verificationTokenExpiresAt", "claimedAt"
|
||||
FROM "PortalDomainHostnameClaim"
|
||||
WHERE "id" = ${input.claimId}
|
||||
AND "tenantId" = ${input.tenantId}
|
||||
AND "releasedAt" IS NULL
|
||||
FOR UPDATE
|
||||
`;
|
||||
const claim = lockedClaims[0];
|
||||
if (!claim || claim.portalId !== observedClaim.portalId) throw new PortalDomainCommercialError("CLAIM_NOT_FOUND");
|
||||
const now = dependencies.now?.() ?? new Date();
|
||||
if (
|
||||
!claim.txtVerifiedAt
|
||||
|| claim.verificationTokenExpiresAt <= now
|
||||
|| claim.claimedAt <= new Date(now.getTime() - PORTAL_DOMAIN_CLAIM_MAX_AGE_MS)
|
||||
) {
|
||||
throw new PortalDomainCommercialError("OWNERSHIP_PROOF_REQUIRED");
|
||||
}
|
||||
|
||||
await assertPortalProductWithClient(
|
||||
client,
|
||||
input.productId,
|
||||
customerPortalProductCodes.customDomainSetup,
|
||||
"one_time_setup",
|
||||
true,
|
||||
);
|
||||
const eligibility = await getCustomerPortalCommercialEligibilityWithClient(client, {
|
||||
tenantId: input.tenantId,
|
||||
claimId: claim.id,
|
||||
});
|
||||
if (!eligibility.portalAllowed) {
|
||||
throw new PortalDomainCommercialError("PORTAL_ENTITLEMENT_REQUIRED");
|
||||
}
|
||||
if (eligibility.domainSetupActive) {
|
||||
throw new PortalDomainCommercialError("CONTRACT_SETUP_ALREADY_CONSUMED");
|
||||
}
|
||||
const reservedScopeKey = claim.billingScopeKey ?? portalDomainBillingScopeKey(claim.id);
|
||||
await (dependencies.reserveAcquisition ?? reserveProductAcquisitionLedger)(
|
||||
{ ...acquisitionInput, scopeKey: reservedScopeKey },
|
||||
{ client: client as unknown as ProductAcquisitionClient },
|
||||
);
|
||||
return reservedScopeKey;
|
||||
});
|
||||
return (dependencies.createAcquisition ?? createProductAcquisition)({ ...acquisitionInput, scopeKey });
|
||||
}
|
||||
|
||||
export async function getCustomerPortalCommercialEligibilityWithClient(
|
||||
client: CommercialReadClient,
|
||||
input: { readonly tenantId: string; readonly claimId?: string },
|
||||
): Promise<CustomerPortalCommercialEligibility> {
|
||||
const [subscription, acquisitions, claim] = await Promise.all([
|
||||
client.tenantSubscription.findUnique({
|
||||
where: { tenantId: input.tenantId },
|
||||
select: { status: true, planCode: true, cancelledAt: true, frozenAt: true },
|
||||
}),
|
||||
client.tenantProductAcquisition.findMany({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
status: "active",
|
||||
cancelledAt: null,
|
||||
expiredAt: null,
|
||||
refundedAt: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
scopeKey: true,
|
||||
quantity: true,
|
||||
tenantSubscriptionProductId: true,
|
||||
cancelledAt: true,
|
||||
expiredAt: true,
|
||||
refundedAt: true,
|
||||
subscriptionProduct: { select: { code: true, kind: true } },
|
||||
},
|
||||
}),
|
||||
input.claimId
|
||||
? client.portalDomainHostnameClaim.findFirst({
|
||||
where: { id: input.claimId, tenantId: input.tenantId },
|
||||
select: { id: true, billingScopeKey: true },
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
]);
|
||||
if (input.claimId && !claim) throw new PortalDomainCommercialError("CLAIM_NOT_FOUND");
|
||||
|
||||
const subscriptionActive = subscription?.status === "active"
|
||||
&& subscription.cancelledAt === null
|
||||
&& subscription.frozenAt === null;
|
||||
const liveAcquisitions = acquisitions.filter(
|
||||
(item) => item.cancelledAt === null && item.expiredAt === null && item.refundedAt === null,
|
||||
);
|
||||
const planCode = subscription?.planCode ?? null;
|
||||
const mapping = planCode ? customerPortalPlanCommercialMapping[planCode as keyof typeof customerPortalPlanCommercialMapping] : undefined;
|
||||
const monthly = liveAcquisitions.find(
|
||||
(item) => item.subscriptionProduct.code === customerPortalProductCodes.monthlyAddOn && item.scopeKey === PORTAL_MONTHLY_SCOPE_KEY,
|
||||
);
|
||||
const contract = liveAcquisitions.find(
|
||||
(item) => item.subscriptionProduct.code === customerPortalProductCodes.enterpriseContract && item.scopeKey === PORTAL_ENTERPRISE_SCOPE_KEY,
|
||||
);
|
||||
const portalSource: CustomerPortalCommercialEligibility["portalSource"] = !subscriptionActive
|
||||
? "missing"
|
||||
: contract
|
||||
? "contract_override"
|
||||
: mapping?.portal === "base_plan"
|
||||
? "base_plan"
|
||||
: monthly
|
||||
? "recurring_add_on"
|
||||
: "missing";
|
||||
const portalAllowed = portalSource !== "missing";
|
||||
|
||||
const domainScopeKey = claim ? claim.billingScopeKey ?? portalDomainBillingScopeKey(claim.id) : null;
|
||||
const paidSetup = domainScopeKey
|
||||
? liveAcquisitions.find(
|
||||
(item) => item.subscriptionProduct.code === customerPortalProductCodes.customDomainSetup && item.scopeKey === domainScopeKey,
|
||||
)
|
||||
: undefined;
|
||||
const contractScopeKey = contract ? portalEnterpriseClaimScopeKey(contract.id) : null;
|
||||
const claimAlreadyUsesContract = Boolean(claim && contractScopeKey && claim.billingScopeKey === contractScopeKey);
|
||||
const otherContractClaims = contractScopeKey
|
||||
? await client.portalDomainHostnameClaim.count({
|
||||
where: {
|
||||
tenantId: input.tenantId,
|
||||
billingScopeKey: contractScopeKey,
|
||||
...(claim ? { id: { not: claim.id } } : {}),
|
||||
},
|
||||
})
|
||||
: 0;
|
||||
const contractSetupAvailable = Boolean(contract && contract.quantity >= 1 && (claimAlreadyUsesContract || otherContractClaims === 0));
|
||||
|
||||
return {
|
||||
subscriptionActive,
|
||||
planCode,
|
||||
portalAllowed,
|
||||
portalSource,
|
||||
monthlyAddOnRequired: planCode === entitlementPlanIds.starter || planCode === entitlementPlanIds.pro,
|
||||
monthlyAddOnActive: Boolean(monthly) || portalSource === "base_plan" || portalSource === "contract_override",
|
||||
monthlyAddOnSubscriptionProductId: monthly?.tenantSubscriptionProductId ?? null,
|
||||
domainSetupActive: Boolean(paidSetup) || contractSetupAvailable,
|
||||
domainSetupIncludedByContract: contractSetupAvailable,
|
||||
domainSetupAcquisitionId: paidSetup?.id ?? null,
|
||||
enterpriseContractAcquisitionId: contract?.id ?? null,
|
||||
domainScopeKey,
|
||||
};
|
||||
}
|
||||
|
||||
export async function grantEnterpriseCustomerPortalContract(
|
||||
input: Omit<GrantContractProductInput, "scopeKey">,
|
||||
dependencies: {
|
||||
readonly withTenant?: WithTenantCommercialClient;
|
||||
readonly grantContract?: typeof grantContractProductAcquisition;
|
||||
} = {},
|
||||
): Promise<ProductAcquisitionResult> {
|
||||
await assertPortalProduct(input.tenantId, input.productId, customerPortalProductCodes.enterpriseContract, "contract_override", false, dependencies.withTenant);
|
||||
return (dependencies.grantContract ?? grantContractProductAcquisition)({ ...input, scopeKey: PORTAL_ENTERPRISE_SCOPE_KEY });
|
||||
}
|
||||
|
||||
async function assertPortalProduct(
|
||||
tenantId: string,
|
||||
productId: string,
|
||||
expectedCode: string,
|
||||
expectedKind: string,
|
||||
expectedPublic: boolean,
|
||||
withTenantDependency?: WithTenantCommercialClient,
|
||||
): Promise<void> {
|
||||
const withTenant = withTenantDependency ?? defaultWithTenant;
|
||||
await withTenant(tenantId, (client) => assertPortalProductWithClient(client, productId, expectedCode, expectedKind, expectedPublic));
|
||||
}
|
||||
|
||||
async function assertPortalProductWithClient(
|
||||
client: CommercialReadClient,
|
||||
productId: string,
|
||||
expectedCode: string,
|
||||
expectedKind: string,
|
||||
expectedPublic: boolean,
|
||||
): Promise<void> {
|
||||
const product = await client.subscriptionProduct.findFirst({
|
||||
where: { id: productId },
|
||||
select: { id: true, code: true, lagoPlanCode: true, kind: true, active: true, public: true },
|
||||
});
|
||||
if (!product?.active) throw new PortalDomainCommercialError("PRODUCT_NOT_FOUND");
|
||||
const expectedLagoPlanCode = expectedKind === "recurring_add_on" ? expectedCode : null;
|
||||
if (
|
||||
product.code !== expectedCode ||
|
||||
product.lagoPlanCode !== expectedLagoPlanCode ||
|
||||
product.kind !== expectedKind ||
|
||||
product.public !== expectedPublic
|
||||
) {
|
||||
throw new PortalDomainCommercialError("PRODUCT_CODE_MISMATCH");
|
||||
}
|
||||
}
|
||||
|
||||
function requireCatalogItem<
|
||||
const Expected extends {
|
||||
readonly code: string;
|
||||
readonly kind: "recurring_add_on" | "one_time_setup";
|
||||
readonly priceType: number;
|
||||
readonly billingPeriod: number;
|
||||
readonly amountCents: number;
|
||||
},
|
||||
>(
|
||||
products: readonly CommercialCatalogProduct[],
|
||||
expected: Expected,
|
||||
): CustomerPortalCheckoutCatalogItem & Pick<Expected, "code" | "kind" | "amountCents"> {
|
||||
const matchingProducts = products.filter((product) => product.code === expected.code);
|
||||
if (matchingProducts.length !== 1) throw new PortalDomainCommercialError("CHECKOUT_CATALOG_DRIFT");
|
||||
const product = matchingProducts[0];
|
||||
if (!product || !product.id || !product.active || !product.public || product.kind !== expected.kind) {
|
||||
throw new PortalDomainCommercialError("CHECKOUT_CATALOG_DRIFT");
|
||||
}
|
||||
const expectedLagoPlanCode = expected.kind === "recurring_add_on" ? expected.code : null;
|
||||
if (product.lagoPlanCode !== expectedLagoPlanCode) {
|
||||
throw new PortalDomainCommercialError("CHECKOUT_CATALOG_DRIFT");
|
||||
}
|
||||
const activePrices = product.prices.filter((price) => price.active);
|
||||
if (activePrices.length !== 1) throw new PortalDomainCommercialError("CHECKOUT_CATALOG_DRIFT");
|
||||
const price = activePrices[0];
|
||||
if (
|
||||
!price
|
||||
|| !price.id
|
||||
|| price.type !== expected.priceType
|
||||
|| price.billingPeriod !== expected.billingPeriod
|
||||
|| price.lagoPlanCode !== expectedLagoPlanCode
|
||||
|| price.lagoFeeCode !== expected.code
|
||||
|| price.currency.trim().toUpperCase() !== "EUR"
|
||||
|| commercialPriceToCents(price.price) !== expected.amountCents
|
||||
) {
|
||||
throw new PortalDomainCommercialError("CHECKOUT_CATALOG_DRIFT");
|
||||
}
|
||||
return {
|
||||
productId: product.id,
|
||||
priceId: price.id,
|
||||
code: expected.code,
|
||||
kind: expected.kind,
|
||||
amountCents: expected.amountCents,
|
||||
currency: "EUR",
|
||||
};
|
||||
}
|
||||
|
||||
function commercialPriceToCents(value: CommercialCatalogPrice["price"]): number {
|
||||
const amount = Number(typeof value === "object" ? value.toString() : value);
|
||||
const cents = Math.round(amount * 100);
|
||||
if (!Number.isFinite(amount) || amount <= 0 || !Number.isSafeInteger(cents) || Math.abs(amount * 100 - cents) > 0.000_001) {
|
||||
throw new PortalDomainCommercialError("CHECKOUT_CATALOG_DRIFT");
|
||||
}
|
||||
return cents;
|
||||
}
|
||||
|
||||
function normalizeIdentifier(value: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/u.test(normalized)) {
|
||||
throw new PortalDomainCommercialError("CLAIM_NOT_FOUND");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
PORTAL_CUSTOM_DOMAIN_CNAME_TARGET,
|
||||
PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET,
|
||||
PortalDomainPolicyError,
|
||||
assertPortalDomainTransition,
|
||||
createIdempotentPortalDomainVerificationSecret,
|
||||
createPortalDomainVerificationSecret,
|
||||
normalizePortalCustomHostname,
|
||||
portalCertificateAlertWindows,
|
||||
portalDomainCnameMatches,
|
||||
portalDomainCooldownUntil,
|
||||
portalDomainRetryAt,
|
||||
portalDomainTxtProofMatches,
|
||||
resolvePortalCustomDomainCnameTarget,
|
||||
shouldDisablePortalDomainAfterFailures,
|
||||
} from "./portal-domain-policy.server";
|
||||
|
||||
describe("portal custom-domain policy", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it.each([
|
||||
["Portal.Geerkens.DE.", "portal.geerkens.de"],
|
||||
["kunden.bücher.de", "kunden.xn--bcher-kva.de"],
|
||||
["portal.example.co.uk", "portal.example.co.uk"],
|
||||
])("normalizes a single registrable subdomain", (input, expected) => {
|
||||
expect(normalizePortalCustomHostname(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", "HOST_REQUIRED"],
|
||||
["*.geerkens.de", "HOST_WILDCARD_FORBIDDEN"],
|
||||
["https://portal.geerkens.de", "HOST_INVALID"],
|
||||
["127.0.0.1", "HOST_IP_FORBIDDEN"],
|
||||
["geerkens.de", "HOST_APEX_FORBIDDEN"],
|
||||
["example.co.uk", "HOST_APEX_FORBIDDEN"],
|
||||
["portal.localhost", "HOST_RESERVED"],
|
||||
["portal.hivegrid.de", "HOST_RESERVED"],
|
||||
[PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET, "HOST_RESERVED"],
|
||||
])("rejects unsafe hostname %s", (input, code) => {
|
||||
expect(() => normalizePortalCustomHostname(input)).toThrow(expect.objectContaining<Partial<PortalDomainPolicyError>>({ code }));
|
||||
});
|
||||
|
||||
it("stores only a hash-compatible TXT proof and verifies split TXT records", () => {
|
||||
const secret = createPortalDomainVerificationSecret("portal.geerkens.de");
|
||||
|
||||
expect(secret.token).toMatch(/^[A-Za-z0-9_-]{43}$/u);
|
||||
expect(secret.tokenHash).toMatch(/^[a-f0-9]{64}$/u);
|
||||
expect(secret.txtRecordName).toBe("_hivegrid-portal.portal.geerkens.de");
|
||||
expect(portalDomainTxtProofMatches(secret.tokenHash, [[secret.txtRecordValue.slice(0, 20), secret.txtRecordValue.slice(20)]])).toBe(true);
|
||||
expect(portalDomainTxtProofMatches(secret.tokenHash, ["hivegrid-portal-verification=wrong"])).toBe(false);
|
||||
});
|
||||
|
||||
it("reproduces one pseudorandom TXT proof only for the same idempotent claim context", () => {
|
||||
const input = {
|
||||
hostname: "portal.geerkens.de",
|
||||
tenantId: "tenant_12345678",
|
||||
portalId: "portal_12345678",
|
||||
idempotencyKey: "domain-claim-request-1",
|
||||
secretKey: "test-proof-key-that-is-longer-than-thirty-two-bytes",
|
||||
};
|
||||
const first = createIdempotentPortalDomainVerificationSecret(input);
|
||||
const replay = createIdempotentPortalDomainVerificationSecret(input);
|
||||
const anotherRequest = createIdempotentPortalDomainVerificationSecret({ ...input, idempotencyKey: "domain-claim-request-2" });
|
||||
expect(replay).toEqual(first);
|
||||
expect(anotherRequest.txtRecordValue).not.toBe(first.txtRecordValue);
|
||||
expect(first.token).toMatch(/^[A-Za-z0-9_-]{43}$/u);
|
||||
expect(first.txtRecordValue).not.toContain(input.secretKey);
|
||||
expect(() => createIdempotentPortalDomainVerificationSecret({ ...input, secretKey: "too-short" })).toThrow(
|
||||
expect.objectContaining<Partial<PortalDomainPolicyError>>({ code: "VERIFICATION_SECRET_INVALID" })
|
||||
);
|
||||
});
|
||||
|
||||
it("defaults to production, permits the dedicated staging target and rejects arbitrary runtime values", () => {
|
||||
vi.stubEnv("PORTAL_CUSTOM_DOMAIN_CNAME_TARGET", undefined);
|
||||
expect(resolvePortalCustomDomainCnameTarget()).toBe(PORTAL_CUSTOM_DOMAIN_CNAME_TARGET);
|
||||
expect(resolvePortalCustomDomainCnameTarget(PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET)).toBe(PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET);
|
||||
for (const invalid of [
|
||||
"",
|
||||
"DOMAINS.PORTAL.HIVEGRID.DE",
|
||||
"domains.portal.hivegrid.de.",
|
||||
"https://domains.portal.hivegrid.de",
|
||||
"evil.example.net",
|
||||
"domains.portal.hivegrid.de\nnext: value",
|
||||
]) {
|
||||
expect(() => resolvePortalCustomDomainCnameTarget(invalid)).toThrow(
|
||||
expect.objectContaining<Partial<PortalDomainPolicyError>>({ code: "CNAME_TARGET_INVALID" })
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("requires the exact environment-specific CNAME target", () => {
|
||||
expect(portalDomainCnameMatches([`${PORTAL_CUSTOM_DOMAIN_CNAME_TARGET}.`])).toBe(true);
|
||||
expect(portalDomainCnameMatches([`evil.${PORTAL_CUSTOM_DOMAIN_CNAME_TARGET}`])).toBe(false);
|
||||
expect(portalDomainCnameMatches([`${PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET}.`], PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET)).toBe(true);
|
||||
expect(portalDomainCnameMatches([PORTAL_CUSTOM_DOMAIN_CNAME_TARGET], PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET)).toBe(false);
|
||||
});
|
||||
|
||||
it("enforces generation state transitions", () => {
|
||||
expect(() => assertPortalDomainTransition("awaiting_dns", "dns_verified")).not.toThrow();
|
||||
expect(() => assertPortalDomainTransition("active", "awaiting_dns")).toThrow(
|
||||
expect.objectContaining<Partial<PortalDomainPolicyError>>({ code: "STATE_TRANSITION_INVALID" })
|
||||
);
|
||||
expect(() => assertPortalDomainTransition("released", "active")).toThrow();
|
||||
});
|
||||
|
||||
it("uses bounded retry delays and waits for three failures over 24 hours before disabling", () => {
|
||||
const now = new Date("2026-07-16T12:00:00.000Z");
|
||||
expect(portalDomainRetryAt(1, now).toISOString()).toBe("2026-07-16T12:15:00.000Z");
|
||||
expect(portalDomainRetryAt(2, now).toISOString()).toBe("2026-07-16T13:00:00.000Z");
|
||||
expect(portalDomainRetryAt(3, now).toISOString()).toBe("2026-07-16T18:00:00.000Z");
|
||||
expect(portalDomainRetryAt(8, now).toISOString()).toBe("2026-07-16T18:00:00.000Z");
|
||||
expect(shouldDisablePortalDomainAfterFailures({ failureCount: 3, firstFailureAt: new Date("2026-07-15T12:01:00.000Z"), now })).toBe(false);
|
||||
expect(shouldDisablePortalDomainAfterFailures({ failureCount: 3, firstFailureAt: new Date("2026-07-15T12:00:00.000Z"), now })).toBe(true);
|
||||
});
|
||||
|
||||
it("applies the 30-day reclaim cooldown and 21/7-day certificate windows", () => {
|
||||
const now = new Date("2026-07-16T12:00:00.000Z");
|
||||
expect(portalDomainCooldownUntil(now).toISOString()).toBe("2026-08-15T12:00:00.000Z");
|
||||
expect(portalCertificateAlertWindows(new Date("2026-07-22T12:00:00.000Z"), now)).toEqual([21, 7]);
|
||||
expect(portalCertificateAlertWindows(new Date("2026-08-06T12:00:01.000Z"), now)).toEqual([]);
|
||||
});
|
||||
});
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { domainToASCII } from "node:url";
|
||||
|
||||
import { parse } from "tldts";
|
||||
|
||||
export const PORTAL_CUSTOM_DOMAIN_CNAME_TARGET = "domains.portal.hivegrid.de" as const;
|
||||
export const PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET = "staging-domains.portal.hivegrid.de" as const;
|
||||
export type PortalCustomDomainCnameTarget = typeof PORTAL_CUSTOM_DOMAIN_CNAME_TARGET | typeof PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET;
|
||||
export const PORTAL_DOMAIN_RECLAIM_COOLDOWN_DAYS = 30 as const;
|
||||
export const PORTAL_DOMAIN_REVALIDATION_INTERVAL_MS = 6 * 60 * 60 * 1_000;
|
||||
export const PORTAL_DOMAIN_RETRY_DELAYS_MS = [15 * 60 * 1_000, 60 * 60 * 1_000, 6 * 60 * 60 * 1_000] as const;
|
||||
export const PORTAL_DOMAIN_CERTIFICATE_ALERT_DAYS = [21, 7] as const;
|
||||
|
||||
const DOMAIN_TOKEN_BYTES = 32;
|
||||
const HOSTNAME_MAX_LENGTH = 253;
|
||||
const LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
|
||||
const FORBIDDEN_EXACT_HOSTS = new Set([
|
||||
"app.hivegrid.de",
|
||||
"admin.hivegrid.de",
|
||||
"api.hivegrid.de",
|
||||
"portal.hivegrid.de",
|
||||
"staging-portal.hivegrid.de",
|
||||
PORTAL_CUSTOM_DOMAIN_CNAME_TARGET,
|
||||
PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET,
|
||||
]);
|
||||
const FORBIDDEN_SUFFIXES = [".localhost", ".local", ".internal", ".example", ".invalid", ".test"] as const;
|
||||
|
||||
export type PortalDomainState =
|
||||
| "awaiting_payment"
|
||||
| "awaiting_dns"
|
||||
| "dns_verified"
|
||||
| "provisioning"
|
||||
| "active"
|
||||
| "degraded"
|
||||
| "failed"
|
||||
| "disabled"
|
||||
| "deprovisioning"
|
||||
| "cooldown"
|
||||
| "released";
|
||||
|
||||
export type PortalDomainAction = "provision" | "deprovision" | "revalidate";
|
||||
|
||||
export class PortalDomainPolicyError extends Error {
|
||||
override readonly name = "PortalDomainPolicyError";
|
||||
|
||||
constructor(
|
||||
readonly code:
|
||||
| "HOST_REQUIRED"
|
||||
| "HOST_INVALID"
|
||||
| "HOST_IP_FORBIDDEN"
|
||||
| "HOST_APEX_FORBIDDEN"
|
||||
| "HOST_WILDCARD_FORBIDDEN"
|
||||
| "HOST_RESERVED"
|
||||
| "STATE_TRANSITION_INVALID"
|
||||
| "CNAME_TARGET_INVALID"
|
||||
| "VERIFICATION_TOKEN_INVALID"
|
||||
| "VERIFICATION_SECRET_INVALID"
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export function resolvePortalCustomDomainCnameTarget(configured = process.env.PORTAL_CUSTOM_DOMAIN_CNAME_TARGET): PortalCustomDomainCnameTarget {
|
||||
if (configured === undefined) return PORTAL_CUSTOM_DOMAIN_CNAME_TARGET;
|
||||
if (configured === PORTAL_CUSTOM_DOMAIN_CNAME_TARGET || configured === PORTAL_CUSTOM_DOMAIN_STAGING_CNAME_TARGET) {
|
||||
return configured;
|
||||
}
|
||||
throw new PortalDomainPolicyError("CNAME_TARGET_INVALID");
|
||||
}
|
||||
|
||||
export function normalizePortalCustomHostname(value: string): string {
|
||||
const raw = value.trim().replace(/\.+$/u, "");
|
||||
if (!raw) throw new PortalDomainPolicyError("HOST_REQUIRED");
|
||||
if (raw.includes("*")) throw new PortalDomainPolicyError("HOST_WILDCARD_FORBIDDEN");
|
||||
if (raw.includes("://") || /[/\\@?#:\s]/u.test(raw)) throw new PortalDomainPolicyError("HOST_INVALID");
|
||||
|
||||
const hostname = domainToASCII(raw).toLowerCase();
|
||||
if (!hostname || hostname.length > HOSTNAME_MAX_LENGTH || hostname.split(".").some((label) => !LABEL_PATTERN.test(label))) {
|
||||
throw new PortalDomainPolicyError("HOST_INVALID");
|
||||
}
|
||||
|
||||
const parsed = parse(hostname, { allowPrivateDomains: false });
|
||||
if (parsed.isIp) throw new PortalDomainPolicyError("HOST_IP_FORBIDDEN");
|
||||
if (FORBIDDEN_EXACT_HOSTS.has(hostname) || FORBIDDEN_SUFFIXES.some((suffix) => hostname === suffix.slice(1) || hostname.endsWith(suffix))) {
|
||||
throw new PortalDomainPolicyError("HOST_RESERVED");
|
||||
}
|
||||
if (!parsed.domain || !parsed.publicSuffix || !parsed.subdomain) {
|
||||
throw new PortalDomainPolicyError("HOST_APEX_FORBIDDEN");
|
||||
}
|
||||
if (!parsed.isIcann) {
|
||||
throw new PortalDomainPolicyError("HOST_RESERVED");
|
||||
}
|
||||
|
||||
return hostname;
|
||||
}
|
||||
|
||||
export type PortalDomainVerificationSecret = {
|
||||
readonly token: string;
|
||||
readonly tokenHash: string;
|
||||
readonly txtRecordName: string;
|
||||
readonly txtRecordValue: string;
|
||||
};
|
||||
|
||||
export function createPortalDomainVerificationSecret(hostname: string): PortalDomainVerificationSecret {
|
||||
const normalized = normalizePortalCustomHostname(hostname);
|
||||
const token = randomBytes(DOMAIN_TOKEN_BYTES).toString("base64url");
|
||||
return verificationSecretFromToken(normalized, token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Produces a pseudorandom but replay-stable proof for one idempotent claim.
|
||||
* The keyed derivation lets an HTTP retry reproduce the same TXT value while
|
||||
* the database continues to persist only its SHA-256 hash.
|
||||
*/
|
||||
export function createIdempotentPortalDomainVerificationSecret(input: {
|
||||
readonly hostname: string;
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
readonly idempotencyKey: string;
|
||||
readonly secretKey: string;
|
||||
}): PortalDomainVerificationSecret {
|
||||
const normalized = normalizePortalCustomHostname(input.hostname);
|
||||
if (
|
||||
Buffer.byteLength(input.secretKey, "utf8") < 32 ||
|
||||
Buffer.byteLength(input.secretKey, "utf8") > 512 ||
|
||||
!input.tenantId ||
|
||||
!input.portalId ||
|
||||
!input.idempotencyKey
|
||||
) {
|
||||
throw new PortalDomainPolicyError("VERIFICATION_SECRET_INVALID");
|
||||
}
|
||||
const context = JSON.stringify({
|
||||
version: 1,
|
||||
tenantId: input.tenantId,
|
||||
portalId: input.portalId,
|
||||
hostname: normalized,
|
||||
idempotencyKey: input.idempotencyKey,
|
||||
});
|
||||
const token = createHmac("sha256", input.secretKey)
|
||||
.update("hivegrid.portal-domain-verification.v1\u0000", "utf8")
|
||||
.update(context, "utf8")
|
||||
.digest("base64url");
|
||||
return verificationSecretFromToken(normalized, token);
|
||||
}
|
||||
|
||||
function verificationSecretFromToken(normalizedHostname: string, token: string): PortalDomainVerificationSecret {
|
||||
const txtRecordValue = `hivegrid-portal-verification=${token}`;
|
||||
return {
|
||||
token,
|
||||
tokenHash: hashPortalDomainVerificationValue(txtRecordValue),
|
||||
txtRecordName: `_hivegrid-portal.${normalizedHostname}`,
|
||||
txtRecordValue,
|
||||
};
|
||||
}
|
||||
|
||||
export function hashPortalDomainVerificationValue(value: string): string {
|
||||
return createHash("sha256").update(value.trim(), "utf8").digest("hex");
|
||||
}
|
||||
|
||||
export function portalDomainTxtProofMatches(expectedHash: string, txtRecords: readonly (string | readonly string[])[]): boolean {
|
||||
if (!/^[a-f0-9]{64}$/u.test(expectedHash)) return false;
|
||||
const expected = Buffer.from(expectedHash, "hex");
|
||||
return txtRecords.some((record) => {
|
||||
const value = (typeof record === "string" ? record : record.join("")).trim();
|
||||
const actual = Buffer.from(hashPortalDomainVerificationValue(value), "hex");
|
||||
return actual.byteLength === expected.byteLength && timingSafeEqual(actual, expected);
|
||||
});
|
||||
}
|
||||
|
||||
export function portalDomainCnameMatches(records: readonly string[], configuredTarget?: string): boolean {
|
||||
const expected = resolvePortalCustomDomainCnameTarget(configuredTarget);
|
||||
return records.some((record) => record.trim().toLowerCase().replace(/\.+$/u, "") === expected);
|
||||
}
|
||||
|
||||
const states = (...values: PortalDomainState[]): ReadonlySet<PortalDomainState> => new Set(values);
|
||||
|
||||
const ALLOWED_TRANSITIONS: Readonly<Record<PortalDomainState, ReadonlySet<PortalDomainState>>> = Object.freeze({
|
||||
awaiting_payment: states("awaiting_dns", "disabled", "released"),
|
||||
awaiting_dns: states("dns_verified", "disabled", "released"),
|
||||
dns_verified: states("provisioning", "awaiting_dns", "disabled"),
|
||||
provisioning: states("active", "failed", "deprovisioning"),
|
||||
active: states("degraded", "disabled", "deprovisioning"),
|
||||
degraded: states("active", "failed", "disabled", "deprovisioning"),
|
||||
failed: states("awaiting_dns", "provisioning", "disabled", "deprovisioning"),
|
||||
disabled: states("awaiting_dns", "deprovisioning", "cooldown"),
|
||||
deprovisioning: states("cooldown", "failed"),
|
||||
cooldown: states("released"),
|
||||
released: states(),
|
||||
});
|
||||
|
||||
export function assertPortalDomainTransition(from: PortalDomainState, to: PortalDomainState): void {
|
||||
if (from === to || ALLOWED_TRANSITIONS[from]?.has(to)) return;
|
||||
throw new PortalDomainPolicyError("STATE_TRANSITION_INVALID");
|
||||
}
|
||||
|
||||
export function portalDomainRetryAt(failureCount: number, now: Date): Date {
|
||||
const normalizedFailureCount = Math.max(1, Math.trunc(failureCount));
|
||||
const delay = PORTAL_DOMAIN_RETRY_DELAYS_MS[Math.min(normalizedFailureCount - 1, PORTAL_DOMAIN_RETRY_DELAYS_MS.length - 1)];
|
||||
return new Date(now.getTime() + delay);
|
||||
}
|
||||
|
||||
export function shouldDisablePortalDomainAfterFailures(input: {
|
||||
readonly failureCount: number;
|
||||
readonly firstFailureAt: Date | null;
|
||||
readonly now: Date;
|
||||
}): boolean {
|
||||
return Boolean(input.failureCount >= 3 && input.firstFailureAt && input.now.getTime() - input.firstFailureAt.getTime() >= 24 * 60 * 60 * 1_000);
|
||||
}
|
||||
|
||||
export function portalDomainCooldownUntil(now: Date): Date {
|
||||
return new Date(now.getTime() + PORTAL_DOMAIN_RECLAIM_COOLDOWN_DAYS * 24 * 60 * 60 * 1_000);
|
||||
}
|
||||
|
||||
export function portalDomainRevalidateAt(now: Date): Date {
|
||||
return new Date(now.getTime() + PORTAL_DOMAIN_REVALIDATION_INTERVAL_MS);
|
||||
}
|
||||
|
||||
export function portalCertificateAlertWindows(expiresAt: Date, now: Date): readonly number[] {
|
||||
const remainingMs = expiresAt.getTime() - now.getTime();
|
||||
return PORTAL_DOMAIN_CERTIFICATE_ALERT_DAYS.filter((days) => remainingMs <= days * 24 * 60 * 60 * 1_000 && remainingMs > 0);
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
type Dictionary = Record<string, unknown>;
|
||||
|
||||
const repositoryRoot = path.resolve(process.cwd());
|
||||
|
||||
function readDomainDictionary(locale: "de" | "en"): Dictionary {
|
||||
const translations = JSON.parse(
|
||||
readFileSync(path.join(repositoryRoot, `apps/web/public/locales/${locale}/translations.json`), "utf8"),
|
||||
) as { customerPortal?: { domain?: Dictionary } };
|
||||
if (!translations.customerPortal?.domain) throw new Error(`customerPortal.domain is missing for ${locale}`);
|
||||
return translations.customerPortal.domain;
|
||||
}
|
||||
|
||||
function leafPaths(value: Dictionary, prefix = ""): string[] {
|
||||
return Object.entries(value).flatMap(([key, nested]) => {
|
||||
const pathKey = prefix ? `${prefix}.${key}` : key;
|
||||
return nested && typeof nested === "object" && !Array.isArray(nested)
|
||||
? leafPaths(nested as Dictionary, pathKey)
|
||||
: [pathKey];
|
||||
});
|
||||
}
|
||||
|
||||
describe("portal custom-domain i18n contract", () => {
|
||||
it("keeps German and English domain copy in exact key parity", () => {
|
||||
expect(leafPaths(readDomainDictionary("de")).sort()).toEqual(leafPaths(readDomainDictionary("en")).sort());
|
||||
});
|
||||
|
||||
it("covers every server-generated timeline, failure, and notification key", () => {
|
||||
const keys = new Set(leafPaths(readDomainDictionary("de")));
|
||||
for (const key of [
|
||||
"timeline.claimed",
|
||||
"timeline.paymentConfirmed",
|
||||
"timeline.dnsVerified",
|
||||
"timeline.active",
|
||||
"timeline.failure",
|
||||
"timeline.disabled",
|
||||
"timeline.deprovisioned",
|
||||
"errors.dns_cname_mismatch",
|
||||
"errors.dns_lookup_failed",
|
||||
"errors.release_revision_mismatch",
|
||||
"errors.https_health_failed",
|
||||
"errors.unsafe_config_path",
|
||||
"errors.generation_conflict",
|
||||
"errors.config_permission_denied",
|
||||
"errors.controller_internal_error",
|
||||
"notifications.activated",
|
||||
"notifications.revalidated",
|
||||
"notifications.deprovisioned",
|
||||
"notifications.disabled_after_failures",
|
||||
"notifications.controller_failed",
|
||||
"notifications.proof_reissued",
|
||||
"notifications.proof_renewed",
|
||||
"notifications.kill_switch_enforced",
|
||||
"notifications.entitlement_lost",
|
||||
"notifications.certificateExpiring",
|
||||
]) {
|
||||
expect(keys, `missing customerPortal.domain.${key}`).toContain(key);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the current public plan names in commercial copy", () => {
|
||||
for (const locale of ["de", "en"] as const) {
|
||||
const copy = JSON.stringify(readDomainDictionary(locale));
|
||||
expect(copy).not.toMatch(/Starter|Team|Business/);
|
||||
expect(copy).toContain("Core");
|
||||
expect(copy).toContain("Swarm");
|
||||
expect(copy).toContain("Colony");
|
||||
}
|
||||
});
|
||||
});
|
||||
+1586
File diff suppressed because it is too large.
Load diff
+1532
File diff suppressed because it is too large.
Load diff
+167
@@ -0,0 +1,167 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
tx: { activity: { create: vi.fn() } },
|
||||
readSnapshot: vi.fn(),
|
||||
upsertTemplate: vi.fn(),
|
||||
billingState: vi.fn(),
|
||||
publishAudit: vi.fn(),
|
||||
logActivity: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/portals/db/portalEmailTemplates.db.server", () => ({
|
||||
readPortalEmailTemplateAdminSnapshot: (...args: unknown[]) => mocks.readSnapshot(...args),
|
||||
upsertVisiblePortalEmailTemplate: (...args: unknown[]) => mocks.upsertTemplate(...args),
|
||||
}));
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: (_tenantId: string, callback: (tx: unknown) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/billingStatusService", () => ({
|
||||
getTenantBillingReadOnlyState: (...args: unknown[]) => mocks.billingState(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAudit(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/activity", () => ({
|
||||
logActivity: (...args: unknown[]) => mocks.logActivity(...args),
|
||||
}));
|
||||
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import {
|
||||
loadPortalEmailTemplateAdmin,
|
||||
normalizePortalEmailTemplateLocale,
|
||||
PortalEmailTemplateAdminError,
|
||||
savePortalEmailTemplate,
|
||||
} from "./portal-email-template-admin.server";
|
||||
|
||||
const savedTemplate = {
|
||||
template: { id: "template_1", stageId: "stage_1", subject: "Status", body: "Hallo", active: true },
|
||||
portalId: "portal_1",
|
||||
stageLabel: "Angebot",
|
||||
created: true,
|
||||
changed: true,
|
||||
};
|
||||
|
||||
describe("portal email template admin domain service", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.billingState.mockResolvedValue({ readOnly: false, status: "active" });
|
||||
mocks.readSnapshot.mockResolvedValue({ portalId: "portal_1", stages: [], templates: [] });
|
||||
mocks.upsertTemplate.mockResolvedValue(savedTemplate);
|
||||
});
|
||||
|
||||
it("normalizes request locales to the supported template locale", () => {
|
||||
expect(normalizePortalEmailTemplateLocale("en-US")).toBe("en");
|
||||
expect(normalizePortalEmailTemplateLocale("de-formal")).toBe("de");
|
||||
expect(normalizePortalEmailTemplateLocale("pl-PL")).toBe("pl");
|
||||
expect(normalizePortalEmailTemplateLocale("ru-RU")).toBe("ru");
|
||||
expect(normalizePortalEmailTemplateLocale("uk-UA")).toBe("uk");
|
||||
expect(normalizePortalEmailTemplateLocale("hu-HU")).toBe("hu");
|
||||
});
|
||||
|
||||
it("loads the RLS-scoped snapshot and exposes a read-only tenant as frozen", async () => {
|
||||
mocks.billingState.mockResolvedValue({ readOnly: true, status: "frozen" });
|
||||
|
||||
await expect(loadPortalEmailTemplateAdmin({ tenantId: "tenant_1", locale: "en-US" })).resolves.toEqual({
|
||||
portalId: "portal_1",
|
||||
stages: [],
|
||||
templates: [],
|
||||
frozen: true,
|
||||
});
|
||||
expect(mocks.readSnapshot).toHaveBeenCalledWith(mocks.tx, { tenantId: "tenant_1", locale: "en" });
|
||||
});
|
||||
|
||||
it("refuses a server-side mutation while the tenant is frozen", async () => {
|
||||
mocks.billingState.mockResolvedValue({ readOnly: true, status: "frozen" });
|
||||
|
||||
await expect(
|
||||
savePortalEmailTemplate({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
stageId: "stage_1",
|
||||
locale: "de",
|
||||
subject: "Status",
|
||||
body: "Hallo",
|
||||
active: true,
|
||||
})
|
||||
).rejects.toMatchObject<Partial<PortalEmailTemplateAdminError>>({
|
||||
status: 423,
|
||||
messageKey: "customerPortal.states.frozen.body",
|
||||
});
|
||||
expect(mocks.upsertTemplate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("writes the template, audit outbox event, and tenant activity in one RLS transaction", async () => {
|
||||
const result = await savePortalEmailTemplate({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
stageId: " stage_1 ",
|
||||
locale: "de",
|
||||
subject: " Status ",
|
||||
body: " Hallo ",
|
||||
active: true,
|
||||
});
|
||||
|
||||
expect(result).toEqual(savedTemplate);
|
||||
expect(mocks.upsertTemplate).toHaveBeenCalledWith(mocks.tx, {
|
||||
tenantId: "tenant_1",
|
||||
stageId: "stage_1",
|
||||
locale: "de",
|
||||
subject: "Status",
|
||||
body: "Hallo",
|
||||
active: true,
|
||||
});
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
actorId: "user_1",
|
||||
action: "customer_portal.email_template.upserted",
|
||||
targetId: "template_1",
|
||||
})
|
||||
);
|
||||
expect(mocks.logActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
subjectType: "tenant",
|
||||
subjectId: "tenant_1",
|
||||
summaryText: "activity.runtime.customerPortal.emailTemplateUpdated",
|
||||
}),
|
||||
{ client: mocks.tx }
|
||||
);
|
||||
});
|
||||
|
||||
it("does not duplicate audit or activity records for an unchanged idempotent replay", async () => {
|
||||
mocks.upsertTemplate.mockResolvedValue({ ...savedTemplate, created: false, changed: false });
|
||||
|
||||
await savePortalEmailTemplate({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
stageId: "stage_1",
|
||||
locale: "de",
|
||||
subject: "Status",
|
||||
body: "Hallo",
|
||||
active: true,
|
||||
});
|
||||
|
||||
expect(mocks.publishAudit).not.toHaveBeenCalled();
|
||||
expect(mocks.logActivity).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns not-found when the requested stage is not visible in the portal", async () => {
|
||||
mocks.upsertTemplate.mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
savePortalEmailTemplate({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
stageId: "stage_hidden",
|
||||
locale: "de",
|
||||
subject: "Status",
|
||||
body: "Hallo",
|
||||
active: true,
|
||||
})
|
||||
).rejects.toBeInstanceOf(CatalogError);
|
||||
});
|
||||
});
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import { defaultLocale, normalizeLocaleCandidate, type SupportedLocale } from "@hivegrid/i18n";
|
||||
|
||||
import {
|
||||
readPortalEmailTemplateAdminSnapshot,
|
||||
upsertVisiblePortalEmailTemplate,
|
||||
type PortalEmailTemplateAdminSnapshot,
|
||||
type PortalEmailTemplateUpsertResult,
|
||||
} from "~/modules/portals/db/portalEmailTemplates.db.server";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
|
||||
|
||||
const SUBJECT_MAX_LENGTH = 200;
|
||||
const BODY_MAX_LENGTH = 10_000;
|
||||
|
||||
export class PortalEmailTemplateAdminError extends Error {
|
||||
readonly status: number;
|
||||
readonly messageKey: string;
|
||||
|
||||
constructor(messageKey: string, status: number) {
|
||||
super(messageKey);
|
||||
this.name = "PortalEmailTemplateAdminError";
|
||||
this.status = status;
|
||||
this.messageKey = messageKey;
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizePortalEmailTemplateLocale(locale: string): SupportedLocale {
|
||||
return normalizeLocaleCandidate(locale) ?? defaultLocale;
|
||||
}
|
||||
|
||||
export async function loadPortalEmailTemplateAdmin(input: {
|
||||
readonly tenantId: string;
|
||||
readonly locale: string;
|
||||
}): Promise<PortalEmailTemplateAdminSnapshot & { readonly frozen: boolean }> {
|
||||
const locale = normalizePortalEmailTemplateLocale(input.locale);
|
||||
const [snapshot, billingState] = await Promise.all([
|
||||
withTenantRLS(input.tenantId, (tx) => readPortalEmailTemplateAdminSnapshot(tx, { tenantId: input.tenantId, locale })),
|
||||
getTenantBillingReadOnlyState(input.tenantId),
|
||||
]);
|
||||
return { ...snapshot, frozen: billingState.readOnly };
|
||||
}
|
||||
|
||||
export async function savePortalEmailTemplate(input: {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
readonly stageId: string;
|
||||
readonly locale: string;
|
||||
readonly subject: string;
|
||||
readonly body: string;
|
||||
readonly active: boolean;
|
||||
}): Promise<PortalEmailTemplateUpsertResult> {
|
||||
const stageId = input.stageId.trim();
|
||||
const subject = input.subject.trim();
|
||||
const body = input.body.trim();
|
||||
if (!stageId || !subject || subject.length > SUBJECT_MAX_LENGTH || !body || body.length > BODY_MAX_LENGTH) {
|
||||
throw new PortalEmailTemplateAdminError("customerPortal.states.error.body", 400);
|
||||
}
|
||||
|
||||
const billingState = await getTenantBillingReadOnlyState(input.tenantId);
|
||||
if (billingState.readOnly) {
|
||||
throw new PortalEmailTemplateAdminError("customerPortal.states.frozen.body", 423);
|
||||
}
|
||||
|
||||
return withTenantRLS(input.tenantId, async (tx) => {
|
||||
const result = await upsertVisiblePortalEmailTemplate(tx, {
|
||||
tenantId: input.tenantId,
|
||||
stageId,
|
||||
locale: normalizePortalEmailTemplateLocale(input.locale),
|
||||
subject,
|
||||
body,
|
||||
active: input.active,
|
||||
});
|
||||
if (!result) {
|
||||
throw new CatalogError(foundationErrors.notFound, { stageId });
|
||||
}
|
||||
if (!result.changed) return result;
|
||||
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.actorUserId,
|
||||
actorType: "user",
|
||||
action: "customer_portal.email_template.upserted",
|
||||
targetType: "PortalEmailTemplate",
|
||||
targetId: result.template.id,
|
||||
sourceModule: "customer_portal",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
metadata: {
|
||||
portalId: result.portalId,
|
||||
stageId: result.template.stageId,
|
||||
locale: normalizePortalEmailTemplateLocale(input.locale),
|
||||
active: result.template.active,
|
||||
created: result.created,
|
||||
},
|
||||
});
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: input.tenantId,
|
||||
actorUserId: input.actorUserId,
|
||||
actorKind: "user",
|
||||
activityType: "audit_event",
|
||||
subjectType: "tenant",
|
||||
subjectId: input.tenantId,
|
||||
summaryText: "activity.runtime.customerPortal.emailTemplateUpdated",
|
||||
metadata: {
|
||||
portalId: result.portalId,
|
||||
templateId: result.template.id,
|
||||
stageId: result.template.stageId,
|
||||
active: result.template.active,
|
||||
},
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { loadPortalProjectInteractionsVM } from "./portal-interactions-data.server";
|
||||
|
||||
const identity = {
|
||||
tenantId: "tenant-1",
|
||||
portalId: "portal-1",
|
||||
portalUserId: "portal-user-1",
|
||||
portalSessionId: "portal-session-1",
|
||||
tenantSlug: "acme",
|
||||
tenantFrozen: false,
|
||||
portalTitle: "Acme Portal",
|
||||
viewerFirstName: "Karla",
|
||||
viewerLastName: "Kunde",
|
||||
viewerLocale: "de",
|
||||
origin: "https://portal.hivegrid.de",
|
||||
createdAt: new Date("2026-07-20T00:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-20T00:00:00.000Z"),
|
||||
expiresAt: new Date("2026-07-21T00:00:00.000Z"),
|
||||
} as const;
|
||||
|
||||
describe("portal project interactions data", () => {
|
||||
it("builds the complaint label from the definition returned by the portal resolver", async () => {
|
||||
const db = {
|
||||
portalConfiguration: {
|
||||
findFirst: vi.fn().mockResolvedValue({ uploadMaxFiles: 10, uploadMaxFileSizeBytes: 52_428_800 }),
|
||||
},
|
||||
portalUser: { findFirst: vi.fn().mockResolvedValue({ kind: "customer" }) },
|
||||
portalSubcontractorAccess: { findFirst: vi.fn().mockResolvedValue(null) },
|
||||
portalUpload: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
file: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
$queryRaw: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "complaint-form-1",
|
||||
definition: {
|
||||
title: "Reklamation melden",
|
||||
submitLabel: "Reklamation senden",
|
||||
successMessage: "Gespeichert",
|
||||
gdprConsentLabel: "Ich stimme der Verarbeitung zu.",
|
||||
captchaEnabled: false,
|
||||
fields: [{ key: "subject", type: "text", label: "Betreff", required: true }],
|
||||
},
|
||||
},
|
||||
]),
|
||||
};
|
||||
|
||||
const complaintAction = vi.fn((formId: string) => `/acme/projects/project-1/complaints/${formId}`);
|
||||
const vm = await loadPortalProjectInteractionsVM({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
projectLabel: "Wärmepumpe",
|
||||
pendingFilename: "Datei wird vorbereitet",
|
||||
uploadAction: "/acme/projects/project-1/upload",
|
||||
complaintAction,
|
||||
db: db as never,
|
||||
});
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
status: "ready",
|
||||
data: {
|
||||
complaintForm: {
|
||||
formId: "complaint-form-1",
|
||||
formSlug: "complaint-form-1",
|
||||
formName: "Reklamation melden",
|
||||
submitAction: "/acme/projects/project-1/complaints/complaint-form-1",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(complaintAction).toHaveBeenCalledOnce();
|
||||
expect(complaintAction).toHaveBeenCalledWith("complaint-form-1");
|
||||
});
|
||||
|
||||
it("uses localized copy instead of exposing an i18n key while a file is pending", async () => {
|
||||
const db = {
|
||||
portalConfiguration: { findFirst: vi.fn().mockResolvedValue(null) },
|
||||
portalUser: { findFirst: vi.fn().mockResolvedValue({ kind: "customer" }) },
|
||||
portalSubcontractorAccess: { findFirst: vi.fn().mockResolvedValue(null) },
|
||||
portalUpload: {
|
||||
findMany: vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: "upload-1",
|
||||
fileId: null,
|
||||
category: "attachment",
|
||||
status: "reserved",
|
||||
quotaBytes: 42,
|
||||
createdAt: new Date("2026-07-20T10:00:00.000Z"),
|
||||
failureCode: null,
|
||||
},
|
||||
]),
|
||||
},
|
||||
file: { findMany: vi.fn().mockResolvedValue([]) },
|
||||
$queryRaw: vi.fn().mockResolvedValue([]),
|
||||
};
|
||||
|
||||
const vm = await loadPortalProjectInteractionsVM({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
projectLabel: "Wärmepumpe",
|
||||
pendingFilename: "Datei wird vorbereitet",
|
||||
uploadAction: "/acme/projects/project-1/upload",
|
||||
complaintAction: (formId) => `/acme/projects/project-1/complaints/${formId}`,
|
||||
db: db as never,
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("Expected ready portal interactions VM");
|
||||
expect(vm.data.uploads[0]?.filename).toBe("Datei wird vorbereitet");
|
||||
expect(vm.data.uploads[0]?.filename).not.toContain("customerPortal.");
|
||||
});
|
||||
});
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
import { getWriteDbClient, type DbClient } from "@hivegrid/db/client.server";
|
||||
import { runWithPortalRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { buildPortalProjectInteractionsVM, type PortalProjectInteractionsVM, type PortalUploadRowVM } from "@hivegrid/view-models";
|
||||
import { FormDefinitionSchema } from "@hivegrid/form-widget";
|
||||
|
||||
import type { PortalSessionIdentity } from "./portal-data.server";
|
||||
import { PORTAL_UPLOAD_ALLOWED_MIME_TYPES } from "./portal-upload.server";
|
||||
|
||||
type ComplaintFormRow = {
|
||||
readonly id: string;
|
||||
readonly definition: unknown;
|
||||
};
|
||||
|
||||
export async function loadPortalProjectInteractionsVM(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly projectLabel: string;
|
||||
readonly pendingFilename: string;
|
||||
readonly uploadAction: string;
|
||||
readonly complaintAction: (formId: string) => string;
|
||||
readonly db?: DbClient;
|
||||
}): Promise<PortalProjectInteractionsVM> {
|
||||
const db = input.db ?? getWriteDbClient();
|
||||
return runWithPortalRlsContext(input.identity, async () => {
|
||||
const [configuration, viewer, subcontractorAccess, uploads, complaintForms] = await Promise.all([
|
||||
db.portalConfiguration.findFirst({
|
||||
where: { tenantId: input.identity.tenantId, portalId: input.identity.portalId },
|
||||
select: { uploadMaxFiles: true, uploadMaxFileSizeBytes: true },
|
||||
}),
|
||||
db.portalUser.findFirst({
|
||||
where: { id: input.identity.portalUserId, tenantId: input.identity.tenantId, archivedAt: null },
|
||||
select: { kind: true },
|
||||
}),
|
||||
db.portalSubcontractorAccess.findFirst({
|
||||
where: {
|
||||
tenantId: input.identity.tenantId,
|
||||
portalUserId: input.identity.portalUserId,
|
||||
projectId: input.projectId,
|
||||
active: true,
|
||||
revokedAt: null,
|
||||
OR: [{ validFrom: null }, { validFrom: { lte: new Date() } }],
|
||||
AND: [{ OR: [{ validUntil: null }, { validUntil: { gt: new Date() } }] }],
|
||||
},
|
||||
select: { canUpload: true },
|
||||
}),
|
||||
db.portalUpload.findMany({
|
||||
where: { tenantId: input.identity.tenantId, portalUserId: input.identity.portalUserId, projectId: input.projectId },
|
||||
select: { id: true, fileId: true, category: true, status: true, quotaBytes: true, createdAt: true, failureCode: true },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 100,
|
||||
}),
|
||||
db.$queryRaw<ComplaintFormRow[]>`
|
||||
SELECT * FROM public.hivegrid_portal_resolve_complaint_form(${input.projectId}, ${""})
|
||||
`,
|
||||
]);
|
||||
|
||||
if (!viewer) return { status: "empty" };
|
||||
const fileIds = uploads.flatMap((upload) => (upload.fileId ? [upload.fileId] : []));
|
||||
const files = fileIds.length
|
||||
? await db.file.findMany({
|
||||
where: { tenantId: input.identity.tenantId, id: { in: fileIds } },
|
||||
select: { id: true, displayName: true, sizeBytes: true },
|
||||
})
|
||||
: [];
|
||||
const fileById = new Map(files.map((file) => [file.id, file]));
|
||||
const uploadRows: PortalUploadRowVM[] = uploads.map((upload) => {
|
||||
const file = upload.fileId ? fileById.get(upload.fileId) : null;
|
||||
return {
|
||||
id: upload.id,
|
||||
filename: file?.displayName ?? input.pendingFilename,
|
||||
category: upload.category,
|
||||
status: upload.status,
|
||||
sizeBytes: file?.sizeBytes ?? upload.quotaBytes,
|
||||
createdAt: upload.createdAt.toISOString(),
|
||||
errorMessageKey: upload.failureCode ? `customerPortal.upload.errors.${upload.failureCode}` : null,
|
||||
};
|
||||
});
|
||||
const complaintForm = complaintForms[0] ?? null;
|
||||
const complaintDefinition = complaintForm ? FormDefinitionSchema.safeParse(complaintForm.definition) : null;
|
||||
const viewerKind = viewer.kind === "subcontractor" ? "subcontractor" : "customer";
|
||||
|
||||
return buildPortalProjectInteractionsVM({
|
||||
hasActiveProjectAccess: true,
|
||||
projectId: input.projectId,
|
||||
projectLabel: input.projectLabel,
|
||||
frozen: input.identity.tenantFrozen,
|
||||
viewerKind,
|
||||
uploadAllowed: viewerKind === "customer" || subcontractorAccess?.canUpload === true,
|
||||
uploadAction: input.uploadAction,
|
||||
maxFiles: configuration?.uploadMaxFiles,
|
||||
maxFileSizeBytes: configuration?.uploadMaxFileSizeBytes,
|
||||
acceptedMimeTypes: [...PORTAL_UPLOAD_ALLOWED_MIME_TYPES],
|
||||
uploads: uploadRows,
|
||||
complaintForm: complaintForm && complaintDefinition?.success
|
||||
? {
|
||||
formId: complaintForm.id,
|
||||
formSlug: complaintForm.id,
|
||||
formName: complaintDefinition.data.title,
|
||||
submitAction: input.complaintAction(complaintForm.id),
|
||||
submitLabel: complaintDefinition.data.submitLabel,
|
||||
gdprConsentLabel: complaintDefinition.data.gdprConsentLabel,
|
||||
fields: complaintDefinition.data.fields
|
||||
.filter((field) => !["honeypot", "file", "photo"].includes(field.type))
|
||||
.map((field) => ({
|
||||
key: field.key,
|
||||
type: field.type as "text" | "textarea" | "number" | "date" | "time" | "select" | "multiselect" | "boolean" | "email" | "phone",
|
||||
label: field.label,
|
||||
required: field.required,
|
||||
options: field.options ?? [],
|
||||
})),
|
||||
}
|
||||
: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
validateCsrf: vi.fn(),
|
||||
inviteContact: vi.fn(),
|
||||
inviteProjectContact: vi.fn(),
|
||||
recordFailure: vi.fn(),
|
||||
recordForeignTargetDenial: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: (...args: unknown[]) => mocks.validateCsrf(...args),
|
||||
}));
|
||||
vi.mock("./portal-invitation.server", async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import("./portal-invitation.server")>();
|
||||
return {
|
||||
...original,
|
||||
invitePortalContact: (...args: unknown[]) => mocks.inviteContact(...args),
|
||||
invitePortalProjectContact: (...args: unknown[]) => mocks.inviteProjectContact(...args),
|
||||
recordPortalInvitationFailure: (...args: unknown[]) => mocks.recordFailure(...args),
|
||||
recordPortalInvitationForeignTargetDenial: (...args: unknown[]) => mocks.recordForeignTargetDenial(...args),
|
||||
};
|
||||
});
|
||||
|
||||
import {
|
||||
canUsePortalInvitationEntrypoint,
|
||||
invitePortalContactFromEntrypoint,
|
||||
invitePortalProjectContactFromEntrypoint,
|
||||
portalInvitationActionErrorResponse,
|
||||
} from "./portal-invitation-entrypoint.server";
|
||||
import { PortalInvitationError } from "./portal-invitation.server";
|
||||
|
||||
const context = {
|
||||
tenantId: "tenant_1",
|
||||
userId: "user_1",
|
||||
permissions: ["portal.manage_users"],
|
||||
};
|
||||
|
||||
function post(body: Record<string, string> = {}): { request: Request; formData: FormData } {
|
||||
const formData = new FormData();
|
||||
for (const [key, value] of Object.entries(body)) formData.set(key, value);
|
||||
return {
|
||||
request: new Request("https://app.example.test/acme/projects/project_1", { method: "POST", body: formData }),
|
||||
formData,
|
||||
};
|
||||
}
|
||||
|
||||
describe("customer portal invitation workspace entrypoints", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.validateCsrf.mockResolvedValue(undefined);
|
||||
mocks.inviteContact.mockResolvedValue("portal_user_1");
|
||||
mocks.inviteProjectContact.mockResolvedValue("portal_user_1");
|
||||
mocks.recordFailure.mockResolvedValue(undefined);
|
||||
mocks.recordForeignTargetDenial.mockResolvedValue(undefined);
|
||||
});
|
||||
|
||||
it("hides the loader affordance without the narrow permission", async () => {
|
||||
await expect(canUsePortalInvitationEntrypoint({ ...context, permissions: ["crm.write"] })).resolves.toBe(false);
|
||||
await expect(canUsePortalInvitationEntrypoint(context)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("uses the tenant, actor and contact id supplied by the contact route", async () => {
|
||||
const { request, formData } = post({ csrf: "token" });
|
||||
|
||||
await expect(
|
||||
invitePortalContactFromEntrypoint({
|
||||
request,
|
||||
formData,
|
||||
context,
|
||||
contactId: "contact_from_route",
|
||||
assertTargetVisible: async () => undefined,
|
||||
}),
|
||||
).resolves.toBe("portal_user_1");
|
||||
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, { formData });
|
||||
expect(mocks.inviteContact).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
contactId: "contact_from_route",
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards the route project id and lets the invitation service revalidate the submitted project contact", async () => {
|
||||
const { request, formData } = post({ csrf: "token", contactId: "contact_from_link" });
|
||||
|
||||
await invitePortalProjectContactFromEntrypoint({
|
||||
request,
|
||||
formData,
|
||||
context,
|
||||
projectId: "project_from_route",
|
||||
contactId: "contact_from_link",
|
||||
assertTargetVisible: async () => undefined,
|
||||
});
|
||||
|
||||
expect(mocks.inviteProjectContact).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
projectId: "project_from_route",
|
||||
contactId: "contact_from_link",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires valid CSRF before auditing a missing portal.manage_users permission", async () => {
|
||||
const { request, formData } = post();
|
||||
|
||||
await expect(
|
||||
invitePortalContactFromEntrypoint({
|
||||
request,
|
||||
formData,
|
||||
context: { ...context, permissions: ["crm.write"] },
|
||||
contactId: "contact_1",
|
||||
assertTargetVisible: async () => undefined,
|
||||
}),
|
||||
).rejects.toBeTruthy();
|
||||
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledWith(request, { formData });
|
||||
expect(mocks.inviteContact).not.toHaveBeenCalled();
|
||||
expect(mocks.recordFailure).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
operation: "contact_invite",
|
||||
reason: "permission_denied",
|
||||
outcome: "blocked",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps permission denial indistinguishable and audit-free when CSRF is invalid", async () => {
|
||||
const { request, formData } = post();
|
||||
mocks.validateCsrf.mockRejectedValueOnce(new Error("invalid csrf"));
|
||||
|
||||
await expect(
|
||||
invitePortalContactFromEntrypoint({
|
||||
request,
|
||||
formData,
|
||||
context: { ...context, permissions: ["crm.write"] },
|
||||
contactId: "contact_1",
|
||||
assertTargetVisible: async () => undefined,
|
||||
}),
|
||||
).rejects.toBeTruthy();
|
||||
|
||||
expect(mocks.recordFailure).not.toHaveBeenCalled();
|
||||
expect(mocks.inviteContact).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("fails closed before mutation on invalid CSRF", async () => {
|
||||
const first = post();
|
||||
mocks.validateCsrf.mockRejectedValueOnce(new Error("invalid csrf"));
|
||||
await expect(
|
||||
invitePortalContactFromEntrypoint({
|
||||
...first,
|
||||
context,
|
||||
contactId: "contact_1",
|
||||
assertTargetVisible: async () => undefined,
|
||||
}),
|
||||
).rejects.toThrow("invalid csrf");
|
||||
expect(mocks.inviteContact).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps missing identity context as 404 without fabricating an audit actor", async () => {
|
||||
const { request, formData } = post();
|
||||
|
||||
await expect(
|
||||
invitePortalContactFromEntrypoint({
|
||||
request,
|
||||
formData,
|
||||
context: { ...context, userId: "" },
|
||||
contactId: "contact_1",
|
||||
assertTargetVisible: async () => undefined,
|
||||
}),
|
||||
).rejects.toBeTruthy();
|
||||
|
||||
expect(mocks.recordFailure).not.toHaveBeenCalled();
|
||||
expect(mocks.inviteContact).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("authorizes the request before auditing a hidden canonical object", async () => {
|
||||
const { request, formData } = post({ csrf: "token" });
|
||||
const hidden = new CatalogError(foundationErrors.notFound);
|
||||
const assertTargetVisible = vi.fn().mockRejectedValue(hidden);
|
||||
|
||||
await expect(
|
||||
invitePortalContactFromEntrypoint({
|
||||
request,
|
||||
formData,
|
||||
context,
|
||||
contactId: "contact_hidden",
|
||||
assertTargetVisible,
|
||||
}),
|
||||
).rejects.toBe(hidden);
|
||||
|
||||
expect(mocks.validateCsrf).toHaveBeenCalledBefore(assertTargetVisible);
|
||||
expect(mocks.recordForeignTargetDenial).toHaveBeenCalledWith({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "user_1",
|
||||
operation: "contact_invite",
|
||||
});
|
||||
expect(JSON.stringify(mocks.recordForeignTargetDenial.mock.calls)).not.toContain("contact_hidden");
|
||||
expect(mocks.inviteContact).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves the invitation service's cleartext error key and status for route action data", async () => {
|
||||
const response = portalInvitationActionErrorResponse(
|
||||
new PortalInvitationError("customerPortal.admin.errors.emailExists", 409),
|
||||
);
|
||||
|
||||
expect(response?.status).toBe(409);
|
||||
await expect(response?.json()).resolves.toEqual({ error: "customerPortal.admin.errors.emailExists" });
|
||||
});
|
||||
|
||||
it("keeps both narrow portal intents ahead of their domain-wide write gates", () => {
|
||||
const crmSource = readFileSync(
|
||||
path.resolve(process.cwd(), "apps/web/app/utils/integrations/crm/crmDetailRoute.server.ts"),
|
||||
"utf8",
|
||||
);
|
||||
const crmAction = crmSource.split("export async function handleKontaktDetailAction")[1] ?? "";
|
||||
expect(crmAction.indexOf('intent === "invitePortalContact"')).toBeGreaterThanOrEqual(0);
|
||||
expect(crmAction.indexOf('intent === "invitePortalContact"')).toBeLessThan(
|
||||
crmAction.indexOf('requireCrmPermission(ctx, "crm.write")'),
|
||||
);
|
||||
|
||||
const projectSource = readFileSync(
|
||||
path.resolve(process.cwd(), "apps/web/app/routes/app.$tenant/projects.$id.tsx"),
|
||||
"utf8",
|
||||
);
|
||||
const projectAction = projectSource.split("export async function action")[1]?.split("export default function")[0] ?? "";
|
||||
expect(projectAction.indexOf('intent === "invitePortalProjectContact"')).toBeGreaterThanOrEqual(0);
|
||||
expect(projectAction.indexOf('intent === "invitePortalProjectContact"')).toBeLessThan(
|
||||
projectAction.indexOf('intent === "updateStammdaten"'),
|
||||
);
|
||||
});
|
||||
});
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
|
||||
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
import {
|
||||
invitePortalContact,
|
||||
invitePortalProjectContact,
|
||||
PortalInvitationError,
|
||||
recordPortalInvitationFailure,
|
||||
recordPortalInvitationForeignTargetDenial,
|
||||
type PortalInvitationOperation,
|
||||
} from "./portal-invitation.server";
|
||||
|
||||
export const PORTAL_INVITATION_PERMISSION = "portal.manage_users";
|
||||
|
||||
export type PortalInvitationEntrypointContext = {
|
||||
readonly tenantId: string;
|
||||
readonly userId: string;
|
||||
readonly permissions: readonly string[];
|
||||
};
|
||||
|
||||
export async function canUsePortalInvitationEntrypoint(context: PortalInvitationEntrypointContext): Promise<boolean> {
|
||||
return Boolean(context.tenantId && context.userId && context.permissions.includes(PORTAL_INVITATION_PERMISSION));
|
||||
}
|
||||
|
||||
async function requirePortalInvitationEntrypoint(input: {
|
||||
readonly request: Request;
|
||||
readonly formData: FormData;
|
||||
readonly context: PortalInvitationEntrypointContext;
|
||||
readonly operation: Extract<PortalInvitationOperation, "contact_invite" | "project_invite">;
|
||||
}): Promise<void> {
|
||||
const { context } = input;
|
||||
if (!context.tenantId || !context.userId) {
|
||||
// There is no verified tenant/user tuple from which a safe tenant audit
|
||||
// context can be built. Keep the denial indistinguishable as 404.
|
||||
throw new CatalogError(foundationErrors.notFound);
|
||||
}
|
||||
try {
|
||||
requirePermission(
|
||||
{
|
||||
tenantId: context.tenantId,
|
||||
userId: context.userId,
|
||||
permissions: context.permissions,
|
||||
},
|
||||
PORTAL_INVITATION_PERMISSION,
|
||||
);
|
||||
} catch (error) {
|
||||
// Preserve the indistinguishable permission response, but never let an
|
||||
// untrusted cross-site request append a denial audit row.
|
||||
try {
|
||||
await validateCSRFToken(input.request, { formData: input.formData });
|
||||
} catch {
|
||||
throw error;
|
||||
}
|
||||
await recordPortalInvitationFailure({
|
||||
tenantId: context.tenantId,
|
||||
actorUserId: context.userId,
|
||||
operation: input.operation,
|
||||
reason: "permission_denied",
|
||||
outcome: "blocked",
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
await validateCSRFToken(input.request, { formData: input.formData });
|
||||
}
|
||||
|
||||
export async function invitePortalContactFromEntrypoint(input: {
|
||||
readonly request: Request;
|
||||
readonly formData: FormData;
|
||||
readonly context: PortalInvitationEntrypointContext;
|
||||
/** Always sourced from the contact detail route parameter. */
|
||||
readonly contactId: string;
|
||||
/** Canonical CRM object-visibility guard, evaluated after request authorization. */
|
||||
readonly assertTargetVisible: () => Promise<void>;
|
||||
}): Promise<string> {
|
||||
await requirePortalInvitationEntrypoint({ ...input, operation: "contact_invite" });
|
||||
await assertInvitationTargetVisible(input, "contact_invite");
|
||||
return invitePortalContact({
|
||||
tenantId: input.context.tenantId,
|
||||
actorUserId: input.context.userId,
|
||||
contactId: input.contactId,
|
||||
});
|
||||
}
|
||||
|
||||
export async function invitePortalProjectContactFromEntrypoint(input: {
|
||||
readonly request: Request;
|
||||
readonly formData: FormData;
|
||||
readonly context: PortalInvitationEntrypointContext;
|
||||
/** Always sourced from the project detail route parameter. */
|
||||
readonly projectId: string;
|
||||
/** Revalidated by invitePortalProjectContact against ProjektKontakt. */
|
||||
readonly contactId: string;
|
||||
/** Canonical project object-visibility guard, evaluated after request authorization. */
|
||||
readonly assertTargetVisible: () => Promise<void>;
|
||||
}): Promise<string> {
|
||||
await requirePortalInvitationEntrypoint({ ...input, operation: "project_invite" });
|
||||
await assertInvitationTargetVisible(input, "project_invite");
|
||||
return invitePortalProjectContact({
|
||||
tenantId: input.context.tenantId,
|
||||
actorUserId: input.context.userId,
|
||||
projectId: input.projectId,
|
||||
contactId: input.contactId,
|
||||
});
|
||||
}
|
||||
|
||||
async function assertInvitationTargetVisible(
|
||||
input: {
|
||||
readonly context: PortalInvitationEntrypointContext;
|
||||
readonly assertTargetVisible: () => Promise<void>;
|
||||
},
|
||||
operation: Extract<PortalInvitationOperation, "contact_invite" | "project_invite">,
|
||||
): Promise<void> {
|
||||
try {
|
||||
await input.assertTargetVisible();
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) {
|
||||
await recordPortalInvitationForeignTargetDenial({
|
||||
tenantId: input.context.tenantId,
|
||||
actorUserId: input.context.userId,
|
||||
operation,
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function portalInvitationActionErrorResponse(error: unknown): Response | null {
|
||||
if (!(error instanceof PortalInvitationError)) return null;
|
||||
return Response.json({ error: error.messageKey }, { status: error.status });
|
||||
}
|
||||
+539
@@ -0,0 +1,539 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
billingState: vi.fn(),
|
||||
commercialEligibility: vi.fn(),
|
||||
publishAudit: vi.fn(),
|
||||
publishOutbox: vi.fn(),
|
||||
encryptTenantField: vi.fn(),
|
||||
logActivity: vi.fn(),
|
||||
loggerError: vi.fn(),
|
||||
lockedContactTarget: vi.fn(),
|
||||
lockedProjectTarget: vi.fn(),
|
||||
lockedPortalUser: vi.fn(),
|
||||
renderMail: vi.fn(),
|
||||
tx: {
|
||||
$queryRaw: vi.fn(),
|
||||
portal: { findFirst: vi.fn() },
|
||||
portalUser: { findFirst: vi.fn(), findUnique: vi.fn(), create: vi.fn(), update: vi.fn() },
|
||||
portalSession: { updateMany: vi.fn() },
|
||||
portalToken: { create: vi.fn(), updateMany: vi.fn() },
|
||||
portalProjectAccess: { upsert: vi.fn(), updateMany: vi.fn() },
|
||||
portalSubcontractorAccess: { updateMany: vi.fn() },
|
||||
kontakt: { findFirst: vi.fn() },
|
||||
projekt: { findFirst: vi.fn() },
|
||||
projektKontakt: { findFirst: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
|
||||
withTenantRLS: async (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/billing-domain.server", () => ({
|
||||
resolveTenantBillingState: (...args: unknown[]) => mocks.billingState(...args),
|
||||
}));
|
||||
vi.mock("./portal-domain-commercial.server", () => ({
|
||||
getCustomerPortalCommercialEligibilityWithClient: (...args: unknown[]) => mocks.commercialEligibility(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/audit-events.server", () => ({
|
||||
publishAuditEventViaOutbox: (...args: unknown[]) => mocks.publishAudit(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/outbox", () => ({
|
||||
publishOutboxEvent: (...args: unknown[]) => mocks.publishOutbox(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/db/crypto/tenant-envelope.server", () => ({
|
||||
encryptTenantField: (...args: unknown[]) => mocks.encryptTenantField(...args),
|
||||
}));
|
||||
vi.mock("@hivegrid/activity", () => ({
|
||||
logActivity: (...args: unknown[]) => mocks.logActivity(...args),
|
||||
}));
|
||||
vi.mock("~/utils/logger.server", () => ({
|
||||
createScopedLogger: () => ({ error: (...args: unknown[]) => mocks.loggerError(...args) }),
|
||||
}));
|
||||
vi.mock("@hivegrid/config", () => ({
|
||||
loadRequiredWebConfig: () => ({ routing: { protocol: "https", portalAppHost: "portal.example.test" } }),
|
||||
}));
|
||||
vi.mock("~/locale/mail-translator.server", () => ({
|
||||
getMailTranslator: async () => ({ t: (key: string) => key, locale: "de" }),
|
||||
}));
|
||||
vi.mock("@hivegrid/mail", () => ({
|
||||
buildBrand: (input: unknown) => input,
|
||||
renderTransactionalEmail: (template: string, input: { actionUrl: string }) => {
|
||||
mocks.renderMail(template, input);
|
||||
return {
|
||||
html: `<a href="${input.actionUrl}">setup</a>`,
|
||||
text: input.actionUrl,
|
||||
};
|
||||
},
|
||||
}));
|
||||
vi.mock("./portal-auth-token.server", () => ({
|
||||
PORTAL_AUTH_TOKEN_TTL_MS: { setup: 7 * 24 * 60 * 60 * 1000 },
|
||||
createPortalAuthToken: () => ({
|
||||
rawToken: "r".repeat(43),
|
||||
tokenHash: "d9ef4334ec1e720d52182936117c00ed352c044d0f8d46cd845298cbc1869b72",
|
||||
expiresAt: new Date("2026-07-25T12:00:00.000Z"),
|
||||
purpose: "setup",
|
||||
}),
|
||||
}));
|
||||
|
||||
import {
|
||||
invitePortalContact,
|
||||
invitePortalProjectContact,
|
||||
invitePortalUserFromAdmin,
|
||||
PortalInvitationError,
|
||||
resendPortalUserInvitation,
|
||||
} from "./portal-invitation.server";
|
||||
|
||||
const portal = {
|
||||
id: "portal_1",
|
||||
title: "Kundenportal",
|
||||
isPublished: true,
|
||||
tenant: { slug: "acme" },
|
||||
configuration: { imprintUrl: "https://acme.test/impressum", privacyUrl: "https://acme.test/datenschutz" },
|
||||
customDomain: null,
|
||||
};
|
||||
|
||||
function normalizeRawSql(call: unknown[] | undefined): string {
|
||||
const strings = call?.[0] as TemplateStringsArray | undefined;
|
||||
return strings ? strings.join(" ").replace(/\s+/gu, " ").trim() : "";
|
||||
}
|
||||
|
||||
function rawCallContaining(fragment: string): unknown[] {
|
||||
const call = mocks.tx.$queryRaw.mock.calls.find((candidate) => normalizeRawSql(candidate).includes(fragment));
|
||||
expect(call, `expected a raw query containing ${fragment}`).toBeDefined();
|
||||
return call!;
|
||||
}
|
||||
|
||||
function rawCallOrder(fragment: string): number {
|
||||
const index = mocks.tx.$queryRaw.mock.calls.findIndex((candidate) => normalizeRawSql(candidate).includes(fragment));
|
||||
expect(index, `expected a raw query containing ${fragment}`).toBeGreaterThanOrEqual(0);
|
||||
return mocks.tx.$queryRaw.mock.invocationCallOrder[index]!;
|
||||
}
|
||||
|
||||
describe("customer portal invitation lifecycle", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.billingState.mockResolvedValue({ readOnly: false, status: "active" });
|
||||
mocks.commercialEligibility.mockResolvedValue({ portalAllowed: true });
|
||||
mocks.encryptTenantField.mockResolvedValue("encrypted-setup-capability");
|
||||
mocks.tx.$queryRaw.mockImplementation((strings: TemplateStringsArray, ...values: unknown[]) => {
|
||||
const sql = strings.join(" ");
|
||||
if (sql.includes('FROM "TenantSubscription"')) return Promise.resolve([{ tenantId: "tenant_1" }]);
|
||||
if (sql.includes('FROM "Projekt" AS project')) return mocks.lockedProjectTarget(...values);
|
||||
if (sql.includes('FROM "Kontakt" AS contact')) return mocks.lockedContactTarget(...values);
|
||||
if (sql.includes('FROM "PortalUser" AS portal_user')) return mocks.lockedPortalUser(...values);
|
||||
throw new Error(`Unexpected raw query in portal invitation test: ${sql}`);
|
||||
});
|
||||
mocks.tx.portal.findFirst.mockResolvedValue(portal);
|
||||
mocks.tx.portalUser.findUnique.mockResolvedValue(null);
|
||||
mocks.tx.portalUser.create.mockResolvedValue({ id: "portal_user_1", email: "ada@example.test", firstName: "Ada", lastName: "Lovelace", locale: "de" });
|
||||
mocks.tx.portalUser.findFirst.mockResolvedValue({ id: "portal_user_1", email: "ada@example.test", firstName: "Ada", lastName: "Lovelace", locale: "de" });
|
||||
mocks.tx.portalUser.update.mockResolvedValue({ id: "portal_user_1", email: "ada@example.test", firstName: "Ada", lastName: "Lovelace", locale: "de" });
|
||||
mocks.tx.portalToken.create.mockResolvedValue({ id: "token_1" });
|
||||
mocks.tx.portalToken.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.portalSession.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.portalProjectAccess.upsert.mockResolvedValue({ id: "access_1" });
|
||||
mocks.tx.portalProjectAccess.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.tx.portalSubcontractorAccess.updateMany.mockResolvedValue({ count: 1 });
|
||||
mocks.lockedContactTarget.mockResolvedValue([
|
||||
{
|
||||
id: "contact_1",
|
||||
vorname: "Ada",
|
||||
nachname: "Lovelace",
|
||||
primaerEmail: "ada@example.test",
|
||||
language: "de",
|
||||
},
|
||||
]);
|
||||
mocks.lockedProjectTarget.mockResolvedValue([
|
||||
{
|
||||
projectId: "project_1",
|
||||
id: "contact_1",
|
||||
vorname: "Ada",
|
||||
nachname: "Lovelace",
|
||||
primaerEmail: "ada@example.test",
|
||||
language: "de",
|
||||
pipelineTypHint: "sales",
|
||||
},
|
||||
]);
|
||||
mocks.lockedPortalUser.mockResolvedValue([
|
||||
{
|
||||
id: "portal_user_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("creates exactly one unbound seven-day setup capability and queues the setup mail atomically", async () => {
|
||||
await expect(
|
||||
invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: " ADA@Example.TEST ",
|
||||
firstName: " Ada ",
|
||||
lastName: " Lovelace ",
|
||||
locale: null,
|
||||
kind: "customer",
|
||||
})
|
||||
).resolves.toBe("portal_user_1");
|
||||
|
||||
expect(mocks.tx.portalToken.create).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalToken.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
tenantId: "tenant_1",
|
||||
portalUserId: "portal_user_1",
|
||||
purpose: "setup",
|
||||
tokenHash: "d9ef4334ec1e720d52182936117c00ed352c044d0f8d46cd845298cbc1869b72",
|
||||
requestedIpHash: null,
|
||||
expiresAt: new Date("2026-07-25T12:00:00.000Z"),
|
||||
}),
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.renderMail).toHaveBeenCalledWith(
|
||||
"magic-link",
|
||||
expect.objectContaining({
|
||||
language: "de",
|
||||
footerCopy: expect.objectContaining({
|
||||
privacyLabel: "common.legal.privacyLabel",
|
||||
imprintLabel: "common.legal.imprintLabel",
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(mocks.publishOutbox).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({
|
||||
type: "mail.transactional.send",
|
||||
payload: expect.objectContaining({
|
||||
to: ["ada@example.test"],
|
||||
text: "https://portal.example.test/acme/setup/__HIVEGRID_PORTAL_SETUP_CAPABILITY__",
|
||||
metadata: expect.objectContaining({
|
||||
source: "portal_setup_invite",
|
||||
invitationSource: "portal_admin_invite",
|
||||
portalUserId: "portal_user_1",
|
||||
encryptedCapability: "encrypted-setup-capability",
|
||||
}),
|
||||
}),
|
||||
})
|
||||
);
|
||||
const mail = mocks.publishOutbox.mock.calls.find((call) => call[1]?.type === "mail.transactional.send")?.[1];
|
||||
expect(JSON.stringify(mail)).not.toContain("r".repeat(43));
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(mocks.tx, expect.objectContaining({ action: "customer_portal.user.invited", targetId: "portal_user_1" }));
|
||||
expect((mocks.tx.$queryRaw.mock.calls[0]?.[0] as TemplateStringsArray).join(" ")).toContain('FROM "TenantSubscription"');
|
||||
expect((mocks.tx.$queryRaw.mock.calls[0]?.[0] as TemplateStringsArray).join(" ")).toContain("FOR UPDATE");
|
||||
expect(mocks.billingState).toHaveBeenCalledWith("tenant_1", { client: mocks.tx });
|
||||
expect(mocks.tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan(mocks.billingState.mock.invocationCallOrder[0] ?? Number.MIN_SAFE_INTEGER);
|
||||
expect(mocks.billingState.mock.invocationCallOrder[0]).toBeLessThan(mocks.tx.portal.findFirst.mock.invocationCallOrder[0] ?? Number.MIN_SAFE_INTEGER);
|
||||
});
|
||||
|
||||
it("locks and revalidates a tenant-scoped private-person contact before issuing its invitation", async () => {
|
||||
await expect(invitePortalContact({ tenantId: "tenant_1", actorUserId: "actor_1", contactId: "contact_1" })).resolves.toBe("portal_user_1");
|
||||
|
||||
const call = rawCallContaining('FROM "Kontakt" AS contact');
|
||||
const sql = normalizeRawSql(call);
|
||||
expect(call.slice(1)).toEqual(["contact_1", "tenant_1"]);
|
||||
expect(sql).toContain('contact."tenantId" =');
|
||||
expect(sql).toContain("contact.\"kontaktTyp\" = 'privatperson'");
|
||||
expect(sql).toContain('contact."archivedAt" IS NULL');
|
||||
expect(sql).toContain("FOR UPDATE OF contact");
|
||||
expect(rawCallOrder('FROM "Kontakt" AS contact')).toBeLessThan(mocks.tx.portalUser.findUnique.mock.invocationCallOrder[0] ?? Number.MIN_SAFE_INTEGER);
|
||||
expect(mocks.tx.kontakt.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("derives a sales-project origin and grants project access in the invitation transaction", async () => {
|
||||
await invitePortalProjectContact({ tenantId: "tenant_1", actorUserId: "actor_1", projectId: "project_1", contactId: "contact_1" });
|
||||
|
||||
const call = rawCallContaining('FROM "Projekt" AS project');
|
||||
const sql = normalizeRawSql(call);
|
||||
expect(call.slice(1)).toEqual(["tenant_1", "tenant_1", "tenant_1", "project_1", "tenant_1", "contact_1", "contact_1"]);
|
||||
expect(sql).toContain('project_contact."tenantId" =');
|
||||
expect(sql).toContain('contact."tenantId" =');
|
||||
expect(sql).toContain('pipeline."tenantId" =');
|
||||
expect(sql).toContain('project."tenantId" =');
|
||||
expect(sql).toContain('ORDER BY project_contact."id" LIMIT 1');
|
||||
expect(sql).toContain("FOR UPDATE OF project, contact, project_contact, pipeline");
|
||||
expect(rawCallOrder('FROM "Projekt" AS project')).toBeLessThan(mocks.tx.portalProjectAccess.upsert.mock.invocationCallOrder[0] ?? Number.MIN_SAFE_INTEGER);
|
||||
expect(mocks.tx.portalProjectAccess.upsert).toHaveBeenCalledWith({
|
||||
where: {
|
||||
portalId_portalUserId_projectId: {
|
||||
portalId: "portal_1",
|
||||
portalUserId: "portal_user_1",
|
||||
projectId: "project_1",
|
||||
},
|
||||
},
|
||||
create: expect.objectContaining({ portalId: "portal_1", portalUserId: "portal_user_1", projectId: "project_1", active: true }),
|
||||
update: { active: true, revokedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({ metadata: expect.objectContaining({ origin: "sales_project", projectId: "project_1", contactId: "contact_1" }) })
|
||||
);
|
||||
expect(mocks.tx.projekt.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.kontakt.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.projektKontakt.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a contact without a tenant-scoped private-person target", async () => {
|
||||
mocks.lockedContactTarget.mockResolvedValue([]);
|
||||
await expect(invitePortalContact({ tenantId: "tenant_1", actorUserId: "actor_1", contactId: "foreign_contact" })).rejects.toMatchObject<
|
||||
Partial<PortalInvitationError>
|
||||
>({ status: 404 });
|
||||
expect(mocks.tx.portalUser.create).not.toHaveBeenCalled();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({
|
||||
action: "customer_portal.user.invitation_blocked",
|
||||
outcome: "blocked",
|
||||
metadata: { operation: "contact_invite", reason: "foreign_target" },
|
||||
})
|
||||
);
|
||||
expect(JSON.stringify(mocks.publishAudit.mock.calls)).not.toContain("foreign_contact");
|
||||
});
|
||||
|
||||
it("rejects foreign project links before creating an identity, access, token or mail", async () => {
|
||||
mocks.lockedProjectTarget.mockResolvedValue([]);
|
||||
|
||||
await expect(
|
||||
invitePortalProjectContact({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
projectId: "project_1",
|
||||
contactId: "foreign_contact",
|
||||
})
|
||||
).rejects.toMatchObject<Partial<PortalInvitationError>>({ status: 404 });
|
||||
|
||||
expect(mocks.tx.portalUser.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.portalProjectAccess.upsert).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.portalToken.create).not.toHaveBeenCalled();
|
||||
expect(mocks.publishOutbox).not.toHaveBeenCalled();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(mocks.tx, expect.objectContaining({ metadata: { operation: "project_invite", reason: "foreign_target" } }));
|
||||
expect(JSON.stringify(mocks.publishAudit.mock.calls)).not.toContain("foreign_contact");
|
||||
});
|
||||
|
||||
it("rejects an active duplicate email without replacing credentials or sending another setup mail", async () => {
|
||||
mocks.tx.portalUser.findUnique.mockResolvedValue({ id: "portal_user_1", archivedAt: null });
|
||||
|
||||
await expect(
|
||||
invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
kind: "customer",
|
||||
})
|
||||
).rejects.toMatchObject<Partial<PortalInvitationError>>({ status: 409 });
|
||||
|
||||
expect(mocks.tx.portalUser.create).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.portalUser.update).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.portalToken.create).not.toHaveBeenCalled();
|
||||
expect(mocks.publishOutbox).not.toHaveBeenCalled();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(mocks.tx, expect.objectContaining({ metadata: { operation: "admin_invite", reason: "duplicate_email" } }));
|
||||
expect(JSON.stringify(mocks.publishAudit.mock.calls)).not.toContain("ada@example.test");
|
||||
});
|
||||
|
||||
it("maps a concurrent unique collision to the same audited duplicate denial", async () => {
|
||||
mocks.tx.portalUser.create.mockRejectedValueOnce(Object.assign(new Error("unique"), { code: "P2002" }));
|
||||
|
||||
await expect(
|
||||
invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
kind: "customer",
|
||||
})
|
||||
).rejects.toMatchObject<Partial<PortalInvitationError>>({ status: 409, auditReason: "duplicate_email" });
|
||||
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({
|
||||
action: "customer_portal.user.invitation_blocked",
|
||||
outcome: "blocked",
|
||||
metadata: { operation: "admin_invite", reason: "duplicate_email" },
|
||||
})
|
||||
);
|
||||
expect(mocks.tx.portalToken.create).not.toHaveBeenCalled();
|
||||
expect(mocks.publishOutbox).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("revokes an archived identity's credentials and access before reinviting it", async () => {
|
||||
mocks.tx.portalUser.findUnique.mockResolvedValue({ id: "portal_user_1", archivedAt: new Date("2026-07-01T00:00:00.000Z") });
|
||||
|
||||
await invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
kind: "customer",
|
||||
});
|
||||
|
||||
expect(mocks.tx.portalSession.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalToken.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalProjectAccess.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalSubcontractorAccess.updateMany).toHaveBeenCalledOnce();
|
||||
expect(mocks.tx.portalUser.update).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
status: "invited",
|
||||
passwordHash: null,
|
||||
emailVerifiedAt: null,
|
||||
privacyNoticeAcknowledgedAt: null,
|
||||
privacyNoticeAcknowledgedUrl: null,
|
||||
archivedAt: null,
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it("resends explicitly by revoking every prior live setup token and issuing one replacement", async () => {
|
||||
await resendPortalUserInvitation({ tenantId: "tenant_1", actorUserId: "actor_1", portalUserId: "portal_user_1" });
|
||||
|
||||
const call = rawCallContaining('FROM "PortalUser" AS portal_user');
|
||||
const sql = normalizeRawSql(call);
|
||||
expect(call.slice(1)).toEqual(["portal_user_1", "tenant_1"]);
|
||||
expect(sql).toContain('portal_user."tenantId" =');
|
||||
expect(sql).toContain("portal_user.\"status\" = 'invited'");
|
||||
expect(sql).toContain('portal_user."archivedAt" IS NULL');
|
||||
expect(sql).toContain("FOR UPDATE OF portal_user");
|
||||
expect(rawCallOrder('FROM "PortalUser" AS portal_user')).toBeLessThan(
|
||||
mocks.tx.portalToken.updateMany.mock.invocationCallOrder[0] ?? Number.MIN_SAFE_INTEGER
|
||||
);
|
||||
expect(mocks.tx.portalToken.updateMany).toHaveBeenCalledWith({
|
||||
where: {
|
||||
tenantId: "tenant_1",
|
||||
portalUserId: "portal_user_1",
|
||||
purpose: "setup",
|
||||
consumedAt: null,
|
||||
revokedAt: null,
|
||||
},
|
||||
data: { revokedAt: expect.any(Date) },
|
||||
});
|
||||
expect(mocks.tx.portalToken.create).toHaveBeenCalledOnce();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(mocks.tx, expect.objectContaining({ action: "customer_portal.user.invitation_resent" }));
|
||||
expect(mocks.tx.portalUser.findFirst).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not issue a replacement setup token when activation wins while resend waits for the user lock", async () => {
|
||||
let releasePortalUserLock!: (rows: unknown[]) => void;
|
||||
mocks.lockedPortalUser.mockReturnValueOnce(
|
||||
new Promise<unknown[]>((resolve) => {
|
||||
releasePortalUserLock = resolve;
|
||||
})
|
||||
);
|
||||
|
||||
const resend = resendPortalUserInvitation({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
portalUserId: "portal_user_1",
|
||||
});
|
||||
await vi.waitFor(() => expect(mocks.lockedPortalUser).toHaveBeenCalledOnce());
|
||||
expect(mocks.tx.portalToken.updateMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.portalToken.create).not.toHaveBeenCalled();
|
||||
|
||||
// The blocking setup transaction committed status=active before this
|
||||
// SELECT ... FOR UPDATE could revalidate the invitation state.
|
||||
releasePortalUserLock([]);
|
||||
await expect(resend).rejects.toMatchObject<Partial<PortalInvitationError>>({ status: 404 });
|
||||
|
||||
expect(mocks.tx.portalToken.updateMany).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.portalToken.create).not.toHaveBeenCalled();
|
||||
expect(mocks.publishOutbox).not.toHaveBeenCalled();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({ metadata: { operation: "resend_invite", reason: "target_not_found" } })
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed when the tenant is frozen or the portal is not published with legal links", async () => {
|
||||
mocks.billingState.mockResolvedValueOnce({ readOnly: true, status: "frozen" });
|
||||
await expect(
|
||||
invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
kind: "customer",
|
||||
})
|
||||
).rejects.toMatchObject<Partial<PortalInvitationError>>({ status: 423 });
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(mocks.tx, expect.objectContaining({ metadata: { operation: "admin_invite", reason: "tenant_read_only" } }));
|
||||
|
||||
mocks.publishAudit.mockClear();
|
||||
mocks.tx.portal.findFirst.mockResolvedValueOnce({ ...portal, isPublished: false });
|
||||
await expect(
|
||||
invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
kind: "customer",
|
||||
})
|
||||
).rejects.toMatchObject<Partial<PortalInvitationError>>({ status: 409 });
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(mocks.tx, expect.objectContaining({ metadata: { operation: "admin_invite", reason: "activation_gate" } }));
|
||||
});
|
||||
|
||||
it("fails closed and audits before issuing an invitation without a live portal entitlement", async () => {
|
||||
mocks.commercialEligibility.mockResolvedValueOnce({ portalAllowed: false });
|
||||
|
||||
await expect(
|
||||
invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
kind: "customer",
|
||||
}),
|
||||
).rejects.toMatchObject<Partial<PortalInvitationError>>({
|
||||
status: 409,
|
||||
messageKey: "customerPortal.domain.errors.entitlementRequired",
|
||||
auditReason: "feature_unavailable",
|
||||
});
|
||||
expect(mocks.tx.portal.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.publishOutbox).not.toHaveBeenCalled();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({ metadata: { operation: "admin_invite", reason: "feature_unavailable" } }),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed and audits when no billing row can be locked", async () => {
|
||||
mocks.tx.$queryRaw.mockResolvedValueOnce([]);
|
||||
|
||||
await expect(
|
||||
invitePortalUserFromAdmin({
|
||||
tenantId: "tenant_1",
|
||||
actorUserId: "actor_1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
locale: "de",
|
||||
kind: "customer",
|
||||
})
|
||||
).rejects.toMatchObject<Partial<PortalInvitationError>>({
|
||||
status: 423,
|
||||
auditReason: "tenant_state_unprovable",
|
||||
});
|
||||
|
||||
expect(mocks.billingState).not.toHaveBeenCalled();
|
||||
expect(mocks.tx.portal.findFirst).not.toHaveBeenCalled();
|
||||
expect(mocks.publishAudit).toHaveBeenCalledWith(
|
||||
mocks.tx,
|
||||
expect.objectContaining({ metadata: { operation: "admin_invite", reason: "tenant_state_unprovable" } })
|
||||
);
|
||||
});
|
||||
});
|
||||
+710
@@ -0,0 +1,710 @@
|
||||
import { logActivity } from "@hivegrid/activity";
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { publishAuditEventViaOutbox } from "@hivegrid/db/audit-events.server";
|
||||
import { resolveTenantBillingState, type TenantBillingStateClient } from "@hivegrid/db/billing-domain.server";
|
||||
import { encryptTenantField, type TenantEnvelopeOptions } from "@hivegrid/db/crypto/tenant-envelope.server";
|
||||
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
|
||||
import {
|
||||
buildPortalSetupCapabilityPlaintext,
|
||||
hashPortalSetupMailContent,
|
||||
PORTAL_SETUP_MAIL_SOURCE,
|
||||
PORTAL_SETUP_TOKEN_PLACEHOLDER,
|
||||
} from "@hivegrid/db/portal-setup-mail-contract.server";
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
import { buildBrand, renderTransactionalEmail } from "@hivegrid/mail";
|
||||
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
|
||||
|
||||
import { getMailTranslator } from "~/locale/mail-translator.server";
|
||||
import { localizedMailChrome } from "~/modules/emails/utils/LocalizedMailChrome";
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
|
||||
import { createPortalAuthToken, PORTAL_AUTH_TOKEN_TTL_MS } from "./portal-auth-token.server";
|
||||
import {
|
||||
getCustomerPortalCommercialEligibilityWithClient,
|
||||
type CommercialReadClient,
|
||||
} from "./portal-domain-commercial.server";
|
||||
|
||||
export type PortalInvitationOrigin = "admin" | "contact" | "project" | "sales_project";
|
||||
export type PortalInvitationOperation = "admin_invite" | "contact_invite" | "project_invite" | "resend_invite";
|
||||
export type PortalInvitationFailureReason =
|
||||
| "permission_denied"
|
||||
| "feature_disabled"
|
||||
| "feature_unavailable"
|
||||
| "tenant_read_only"
|
||||
| "tenant_state_unprovable"
|
||||
| "activation_gate"
|
||||
| "duplicate_email"
|
||||
| "foreign_target"
|
||||
| "target_not_found"
|
||||
| "invalid_input"
|
||||
| "internal_failure";
|
||||
|
||||
const portalInvitationLogger = createScopedLogger("customer-portal.invitation");
|
||||
|
||||
export class PortalInvitationError extends Error {
|
||||
override readonly name = "PortalInvitationError";
|
||||
|
||||
constructor(
|
||||
readonly messageKey: string,
|
||||
readonly status: 400 | 404 | 409 | 423 = 400,
|
||||
readonly auditReason?: PortalInvitationFailureReason
|
||||
) {
|
||||
super(messageKey);
|
||||
}
|
||||
}
|
||||
|
||||
type PortalInvitationActor = {
|
||||
readonly tenantId: string;
|
||||
readonly actorUserId: string;
|
||||
};
|
||||
|
||||
type PortalInviteIdentity = {
|
||||
readonly email: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly locale: string | null;
|
||||
};
|
||||
|
||||
type PortalInviteTarget = PortalInviteIdentity & {
|
||||
readonly kind: "customer" | "subcontractor";
|
||||
readonly origin: PortalInvitationOrigin;
|
||||
readonly contactId?: string;
|
||||
readonly projectId?: string;
|
||||
};
|
||||
|
||||
type PortalTransaction = Prisma.TransactionClient;
|
||||
|
||||
type InvitationPortal = {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly isPublished: boolean;
|
||||
readonly tenant: { readonly slug: string };
|
||||
readonly configuration: { readonly imprintUrl: string | null; readonly privacyUrl: string | null } | null;
|
||||
readonly customDomain: { readonly status: string; readonly activeOrigin: string | null } | null;
|
||||
};
|
||||
|
||||
type PortalInvitationUser = {
|
||||
readonly id: string;
|
||||
readonly email: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly locale: string;
|
||||
};
|
||||
|
||||
type LockedContactInvitationTarget = {
|
||||
readonly id: string;
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly language: string | null;
|
||||
};
|
||||
|
||||
type LockedProjectInvitationTarget = LockedContactInvitationTarget & {
|
||||
readonly projectId: string;
|
||||
readonly pipelineTypHint: string;
|
||||
};
|
||||
|
||||
export async function invitePortalUserFromAdmin(
|
||||
input: PortalInvitationActor & PortalInviteIdentity & { readonly kind: "customer" | "subcontractor" }
|
||||
): Promise<string> {
|
||||
return runPortalInvitationCommand(input, "admin_invite", async (tx) => {
|
||||
const portal = await requireInvitationPortal(tx, input.tenantId);
|
||||
return issuePortalInvitationWithTx(tx, portal, input, {
|
||||
email: normalizeEmail(input.email),
|
||||
firstName: normalizeName(input.firstName),
|
||||
lastName: normalizeName(input.lastName),
|
||||
locale: input.locale,
|
||||
kind: input.kind,
|
||||
origin: "admin",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function invitePortalContact(input: PortalInvitationActor & { readonly contactId: string }): Promise<string> {
|
||||
return runPortalInvitationCommand(input, "contact_invite", async (tx) => {
|
||||
const contactId = requireId(input.contactId);
|
||||
const [portal, contact] = await Promise.all([requireInvitationPortal(tx, input.tenantId), lockContactInvitationTarget(tx, input.tenantId, contactId)]);
|
||||
if (!contact) throw notFound("foreign_target");
|
||||
return issuePortalInvitationWithTx(tx, portal, input, {
|
||||
...contactIdentity(contact),
|
||||
kind: "customer",
|
||||
origin: "contact",
|
||||
contactId: contact.id,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function invitePortalProjectContact(input: PortalInvitationActor & { readonly projectId: string; readonly contactId: string }): Promise<string> {
|
||||
return runPortalInvitationCommand(input, "project_invite", async (tx) => {
|
||||
const projectId = requireId(input.projectId);
|
||||
const contactId = requireId(input.contactId);
|
||||
const [portal, target] = await Promise.all([
|
||||
requireInvitationPortal(tx, input.tenantId),
|
||||
lockProjectInvitationTarget(tx, input.tenantId, projectId, contactId),
|
||||
]);
|
||||
if (!target) throw notFound("foreign_target");
|
||||
return issuePortalInvitationWithTx(tx, portal, input, {
|
||||
...contactIdentity(target),
|
||||
kind: "customer",
|
||||
origin: target.pipelineTypHint === "sales" ? "sales_project" : "project",
|
||||
contactId: target.id,
|
||||
projectId: target.projectId,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function resendPortalUserInvitation(input: PortalInvitationActor & { readonly portalUserId: string }): Promise<void> {
|
||||
await runPortalInvitationCommand(input, "resend_invite", async (tx) => {
|
||||
const portalUserId = requireId(input.portalUserId);
|
||||
const [portal, user] = await Promise.all([requireInvitationPortal(tx, input.tenantId), lockInvitedPortalUser(tx, input.tenantId, portalUserId)]);
|
||||
if (!user) throw notFound();
|
||||
await tx.portalToken.updateMany({
|
||||
where: { tenantId: input.tenantId, portalUserId: user.id, purpose: "setup", consumedAt: null, revokedAt: null },
|
||||
data: { revokedAt: new Date() },
|
||||
});
|
||||
await issueSetupTokenAndMail(tx, portal, user, input.tenantId, "portal_admin_resend");
|
||||
await auditInvitation(tx, input, "customer_portal.user.invitation_resent", user.id, {
|
||||
origin: "admin",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function lockContactInvitationTarget(tx: PortalTransaction, tenantId: string, contactId: string): Promise<LockedContactInvitationTarget | null> {
|
||||
const rows = await tx.$queryRaw<LockedContactInvitationTarget[]>`
|
||||
SELECT
|
||||
contact."id",
|
||||
contact."vorname",
|
||||
contact."nachname",
|
||||
contact."primaerEmail",
|
||||
contact."language"
|
||||
FROM "Kontakt" AS contact
|
||||
WHERE contact."id" = ${contactId}
|
||||
AND contact."tenantId" = ${tenantId}
|
||||
AND contact."kontaktTyp" = 'privatperson'
|
||||
AND contact."archivedAt" IS NULL
|
||||
FOR UPDATE OF contact
|
||||
`;
|
||||
return rows.length === 1 ? rows[0]! : null;
|
||||
}
|
||||
|
||||
async function lockProjectInvitationTarget(
|
||||
tx: PortalTransaction,
|
||||
tenantId: string,
|
||||
projectId: string,
|
||||
contactId: string
|
||||
): Promise<LockedProjectInvitationTarget | null> {
|
||||
const rows = await tx.$queryRaw<LockedProjectInvitationTarget[]>`
|
||||
SELECT
|
||||
project."id" AS "projectId",
|
||||
contact."id",
|
||||
contact."vorname",
|
||||
contact."nachname",
|
||||
contact."primaerEmail",
|
||||
contact."language",
|
||||
pipeline."typHint"::text AS "pipelineTypHint"
|
||||
FROM "Projekt" AS project
|
||||
INNER JOIN "ProjektKontakt" AS project_contact
|
||||
ON project_contact."projektId" = project."id"
|
||||
AND project_contact."tenantId" = ${tenantId}
|
||||
INNER JOIN "Kontakt" AS contact
|
||||
ON contact."id" = project_contact."kontaktId"
|
||||
AND contact."tenantId" = ${tenantId}
|
||||
INNER JOIN "Pipeline" AS pipeline
|
||||
ON pipeline."id" = project."pipelineId"
|
||||
AND pipeline."tenantId" = ${tenantId}
|
||||
WHERE project."id" = ${projectId}
|
||||
AND project."tenantId" = ${tenantId}
|
||||
AND project."archivedAt" IS NULL
|
||||
AND project_contact."kontaktId" = ${contactId}
|
||||
AND contact."id" = ${contactId}
|
||||
AND contact."kontaktTyp" = 'privatperson'
|
||||
AND contact."archivedAt" IS NULL
|
||||
AND pipeline."archivedAt" IS NULL
|
||||
ORDER BY project_contact."id"
|
||||
LIMIT 1
|
||||
FOR UPDATE OF project, contact, project_contact, pipeline
|
||||
`;
|
||||
return rows.length === 1 ? rows[0]! : null;
|
||||
}
|
||||
|
||||
async function lockInvitedPortalUser(tx: PortalTransaction, tenantId: string, portalUserId: string): Promise<PortalInvitationUser | null> {
|
||||
const rows = await tx.$queryRaw<PortalInvitationUser[]>`
|
||||
SELECT
|
||||
portal_user."id",
|
||||
portal_user."email",
|
||||
portal_user."firstName",
|
||||
portal_user."lastName",
|
||||
portal_user."locale"
|
||||
FROM "PortalUser" AS portal_user
|
||||
WHERE portal_user."id" = ${portalUserId}
|
||||
AND portal_user."tenantId" = ${tenantId}
|
||||
AND portal_user."status" = 'invited'
|
||||
AND portal_user."archivedAt" IS NULL
|
||||
FOR UPDATE OF portal_user
|
||||
`;
|
||||
return rows.length === 1 ? rows[0]! : null;
|
||||
}
|
||||
|
||||
async function issuePortalInvitationWithTx(
|
||||
tx: PortalTransaction,
|
||||
portal: InvitationPortal,
|
||||
actor: PortalInvitationActor,
|
||||
target: PortalInviteTarget
|
||||
): Promise<string> {
|
||||
const existing = await tx.portalUser.findUnique({
|
||||
where: { portalId_emailNormalized: { portalId: portal.id, emailNormalized: target.email } },
|
||||
select: { id: true, archivedAt: true },
|
||||
});
|
||||
if (existing && !existing.archivedAt) throw duplicateEmail();
|
||||
|
||||
if (existing) {
|
||||
const revokedAt = new Date();
|
||||
await Promise.all([
|
||||
tx.portalSession.updateMany({ where: { tenantId: actor.tenantId, portalUserId: existing.id, revokedAt: null }, data: { revokedAt } }),
|
||||
tx.portalToken.updateMany({ where: { tenantId: actor.tenantId, portalUserId: existing.id, revokedAt: null }, data: { revokedAt } }),
|
||||
tx.portalProjectAccess.updateMany({
|
||||
where: { tenantId: actor.tenantId, portalUserId: existing.id, revokedAt: null },
|
||||
data: { active: false, revokedAt },
|
||||
}),
|
||||
tx.portalSubcontractorAccess.updateMany({
|
||||
where: { tenantId: actor.tenantId, portalUserId: existing.id, revokedAt: null },
|
||||
data: { active: false, revokedAt },
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
let user: PortalInvitationUser;
|
||||
if (existing) {
|
||||
user = await tx.portalUser.update({
|
||||
where: { id: existing.id },
|
||||
data: {
|
||||
email: target.email,
|
||||
emailNormalized: target.email,
|
||||
firstName: target.firstName,
|
||||
lastName: target.lastName,
|
||||
locale: target.locale ?? "de",
|
||||
kind: target.kind,
|
||||
status: "invited",
|
||||
passwordHash: null,
|
||||
emailVerifiedAt: null,
|
||||
privacyNoticeAcknowledgedAt: null,
|
||||
privacyNoticeAcknowledgedUrl: null,
|
||||
lastLoginAt: null,
|
||||
lastActivityAt: null,
|
||||
archivedAt: null,
|
||||
},
|
||||
select: { id: true, email: true, firstName: true, lastName: true, locale: true },
|
||||
});
|
||||
} else {
|
||||
try {
|
||||
user = await tx.portalUser.create({
|
||||
data: {
|
||||
tenantId: actor.tenantId,
|
||||
portalId: portal.id,
|
||||
email: target.email,
|
||||
emailNormalized: target.email,
|
||||
firstName: target.firstName,
|
||||
lastName: target.lastName,
|
||||
locale: target.locale ?? "de",
|
||||
kind: target.kind,
|
||||
status: "invited",
|
||||
},
|
||||
select: { id: true, email: true, firstName: true, lastName: true, locale: true },
|
||||
});
|
||||
} catch (error) {
|
||||
if (isUniqueConstraintError(error)) throw duplicateEmail();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (target.projectId) {
|
||||
await tx.portalProjectAccess.upsert({
|
||||
where: {
|
||||
portalId_portalUserId_projectId: {
|
||||
portalId: portal.id,
|
||||
portalUserId: user.id,
|
||||
projectId: target.projectId,
|
||||
},
|
||||
},
|
||||
create: {
|
||||
tenantId: actor.tenantId,
|
||||
portalId: portal.id,
|
||||
portalUserId: user.id,
|
||||
projectId: target.projectId,
|
||||
active: true,
|
||||
revokedAt: null,
|
||||
},
|
||||
update: { active: true, revokedAt: null },
|
||||
select: { id: true },
|
||||
});
|
||||
}
|
||||
|
||||
await issueSetupTokenAndMail(tx, portal, user, actor.tenantId, sourceForOrigin(target.origin));
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: actor.tenantId,
|
||||
event: "portal.user_created",
|
||||
data: { portalId: portal.id, portalUserId: user.id, kind: target.kind },
|
||||
userId: actor.actorUserId,
|
||||
sourceId: `portal-user:${user.id}:created`,
|
||||
})
|
||||
);
|
||||
if (target.projectId) {
|
||||
await publishOutboxEvent(
|
||||
tx as unknown as OutboxPublisherTransaction,
|
||||
buildWorkflowTriggerOutboxEvent({
|
||||
tenantId: actor.tenantId,
|
||||
event: "portal.access_granted",
|
||||
data: { portalId: portal.id, portalUserId: user.id, projectId: target.projectId },
|
||||
userId: actor.actorUserId,
|
||||
sourceId: `portal-access:${user.id}:${target.projectId}:granted`,
|
||||
})
|
||||
);
|
||||
}
|
||||
await auditInvitation(tx, actor, "customer_portal.user.invited", user.id, {
|
||||
origin: target.origin,
|
||||
kind: target.kind,
|
||||
...(target.contactId ? { contactId: target.contactId } : {}),
|
||||
...(target.projectId ? { projectId: target.projectId } : {}),
|
||||
});
|
||||
return user.id;
|
||||
}
|
||||
|
||||
async function issueSetupTokenAndMail(
|
||||
tx: PortalTransaction,
|
||||
portal: InvitationPortal,
|
||||
user: { readonly id: string; readonly email: string; readonly firstName: string; readonly locale: string },
|
||||
tenantId: string,
|
||||
source: string
|
||||
): Promise<void> {
|
||||
const setupToken = createPortalAuthToken("setup");
|
||||
const persistedToken = await tx.portalToken.create({
|
||||
data: {
|
||||
tenantId,
|
||||
portalUserId: user.id,
|
||||
purpose: "setup",
|
||||
tokenHash: setupToken.tokenHash,
|
||||
expiresAt: setupToken.expiresAt,
|
||||
requestedIpHash: null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
const actionUrl = buildSetupUrl(portal, PORTAL_SETUP_TOKEN_PLACEHOLDER);
|
||||
const { t, locale } = await getMailTranslator(user.locale);
|
||||
const expiresInDays = PORTAL_AUTH_TOKEN_TTL_MS.setup / (24 * 60 * 60 * 1000);
|
||||
const vars = { productName: portal.title, name: user.firstName, expiresInDays };
|
||||
const subject = t("customerPortalAuth.setup.subject", vars);
|
||||
const rendered = renderTransactionalEmail("magic-link", {
|
||||
brand: buildBrand({ productName: portal.title }),
|
||||
...localizedMailChrome(t, locale),
|
||||
recipientName: user.firstName,
|
||||
actionUrl,
|
||||
expiresInMinutes: PORTAL_AUTH_TOKEN_TTL_MS.setup / 60_000,
|
||||
subject,
|
||||
previewText: t("customerPortalAuth.setup.previewText", vars),
|
||||
eyebrow: t("customerPortalAuth.setup.eyebrow", vars),
|
||||
title: t("customerPortalAuth.setup.title_named", vars),
|
||||
intro: t("customerPortalAuth.setup.intro", vars),
|
||||
actionLabel: t("customerPortalAuth.setup.actionLabel", vars),
|
||||
outro: t("customerPortalAuth.setup.outro", vars),
|
||||
expiresText: t("customerPortalAuth.setup.expiresText", vars),
|
||||
signoffThanks: t("common.signoff.thanks"),
|
||||
});
|
||||
const mailContentHash = hashPortalSetupMailContent({
|
||||
recipient: user.email,
|
||||
subject,
|
||||
text: rendered.text,
|
||||
html: rendered.html,
|
||||
});
|
||||
const capabilityMetadata = {
|
||||
invitationSource: source,
|
||||
portalId: portal.id,
|
||||
portalUserId: user.id,
|
||||
portalTokenId: persistedToken.id,
|
||||
setupTokenHash: setupToken.tokenHash,
|
||||
expiresAt: setupToken.expiresAt.toISOString(),
|
||||
mailContentHash,
|
||||
};
|
||||
const encryptedCapability = await encryptTenantField(
|
||||
tenantId,
|
||||
buildPortalSetupCapabilityPlaintext({
|
||||
tenantId,
|
||||
rawToken: setupToken.rawToken,
|
||||
metadata: capabilityMetadata,
|
||||
}),
|
||||
{ client: tx as unknown as NonNullable<TenantEnvelopeOptions["client"]> }
|
||||
);
|
||||
await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, {
|
||||
tenantId,
|
||||
type: "mail.transactional.send",
|
||||
dispatchKey: `portal-setup:${persistedToken.id}`,
|
||||
payload: {
|
||||
tenantId,
|
||||
to: [user.email],
|
||||
subject,
|
||||
text: rendered.text,
|
||||
html: rendered.html,
|
||||
metadata: {
|
||||
source: PORTAL_SETUP_MAIL_SOURCE,
|
||||
...capabilityMetadata,
|
||||
encryptedCapability,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function buildSetupUrl(portal: InvitationPortal, rawToken: string): string {
|
||||
const customOrigin = portal.customDomain?.status === "active" ? normalizeRootOrigin(portal.customDomain.activeOrigin, true) : null;
|
||||
const routing = loadRequiredWebConfig().routing;
|
||||
const standardOrigin = normalizeRootOrigin(`${routing.protocol}://${routing.portalAppHost}`, routing.protocol === "https");
|
||||
if (!standardOrigin) throw new PortalInvitationError("customerPortal.admin.errors.activationGate", 409);
|
||||
const origin = customOrigin ?? standardOrigin;
|
||||
const tenantPrefix = customOrigin ? "" : `/${encodeURIComponent(portal.tenant.slug)}`;
|
||||
return `${origin}${tenantPrefix}/setup/${encodeURIComponent(rawToken)}`;
|
||||
}
|
||||
|
||||
async function requireInvitationPortal(tx: PortalTransaction, tenantId: string): Promise<InvitationPortal> {
|
||||
const portal = await tx.portal.findFirst({
|
||||
where: { tenantId },
|
||||
select: {
|
||||
id: true,
|
||||
title: true,
|
||||
isPublished: true,
|
||||
tenant: { select: { slug: true } },
|
||||
configuration: { select: { imprintUrl: true, privacyUrl: true } },
|
||||
customDomain: { select: { status: true, activeOrigin: true } },
|
||||
},
|
||||
});
|
||||
if (!portal) throw notFound();
|
||||
if (!portal.isPublished || !normalizeLegalUrl(portal.configuration?.imprintUrl) || !normalizeLegalUrl(portal.configuration?.privacyUrl)) {
|
||||
throw new PortalInvitationError("customerPortal.admin.errors.activationGate", 409);
|
||||
}
|
||||
return portal;
|
||||
}
|
||||
|
||||
async function auditInvitation(
|
||||
tx: PortalTransaction,
|
||||
actor: PortalInvitationActor,
|
||||
action: string,
|
||||
portalUserId: string,
|
||||
metadata: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
tenantId: actor.tenantId,
|
||||
actorId: actor.actorUserId,
|
||||
actorType: "user",
|
||||
action,
|
||||
targetType: "PortalUser",
|
||||
targetId: portalUserId,
|
||||
sourceModule: "customer_portal",
|
||||
outcome: "success",
|
||||
dataSensitivity: "internal",
|
||||
metadata: metadata as Prisma.InputJsonValue,
|
||||
});
|
||||
const contactId = typeof metadata.contactId === "string" ? metadata.contactId : null;
|
||||
const projectId = typeof metadata.projectId === "string" ? metadata.projectId : null;
|
||||
await logActivity(
|
||||
{
|
||||
tenantId: actor.tenantId,
|
||||
actorUserId: actor.actorUserId,
|
||||
actorKind: "user",
|
||||
activityType: "audit_event",
|
||||
subjectType: projectId ? "project" : contactId ? "contact" : "tenant",
|
||||
subjectId: projectId ?? contactId ?? actor.tenantId,
|
||||
summaryText: action,
|
||||
metadata: { targetType: "PortalUser", targetId: portalUserId, ...metadata },
|
||||
},
|
||||
{ client: tx }
|
||||
);
|
||||
}
|
||||
|
||||
async function runPortalInvitationCommand<T>(
|
||||
actor: PortalInvitationActor,
|
||||
operation: PortalInvitationOperation,
|
||||
mutation: (tx: PortalTransaction) => Promise<T>
|
||||
): Promise<T> {
|
||||
try {
|
||||
return await withTenantRLS(actor.tenantId, async (tx) => {
|
||||
await assertPortalInvitationWritableWithTx(tx, actor.tenantId);
|
||||
return mutation(tx);
|
||||
});
|
||||
} catch (error) {
|
||||
await recordPortalInvitationFailure({
|
||||
...actor,
|
||||
operation,
|
||||
reason: error instanceof PortalInvitationError ? (error.auditReason ?? failureReasonFor(error)) : "internal_failure",
|
||||
outcome: error instanceof PortalInvitationError ? "blocked" : "failure",
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async function assertPortalInvitationWritableWithTx(tx: PortalTransaction, tenantId: string): Promise<void> {
|
||||
const lockedSubscriptions = await tx.$queryRaw<Array<{ tenantId: string }>>`
|
||||
SELECT "tenantId"
|
||||
FROM "TenantSubscription"
|
||||
WHERE "tenantId" = ${tenantId}
|
||||
FOR UPDATE
|
||||
`;
|
||||
if (lockedSubscriptions.length !== 1) {
|
||||
throw frozen("tenant_state_unprovable");
|
||||
}
|
||||
const billingState = await resolveTenantBillingState(tenantId, {
|
||||
client: tx as unknown as TenantBillingStateClient,
|
||||
});
|
||||
if (billingState.readOnly) {
|
||||
throw frozen("tenant_read_only");
|
||||
}
|
||||
const commercial = await getCustomerPortalCommercialEligibilityWithClient(
|
||||
tx as unknown as CommercialReadClient,
|
||||
{ tenantId },
|
||||
);
|
||||
if (!commercial.portalAllowed) {
|
||||
throw new PortalInvitationError("customerPortal.domain.errors.entitlementRequired", 409, "feature_unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
export async function recordPortalInvitationFailure(
|
||||
input: PortalInvitationActor & {
|
||||
readonly operation: PortalInvitationOperation;
|
||||
readonly reason: PortalInvitationFailureReason;
|
||||
readonly outcome: "blocked" | "failure";
|
||||
}
|
||||
): Promise<void> {
|
||||
// Without both verified identifiers there is no safe tenant-scoped audit
|
||||
// context. Callers must preserve their indistinguishable denial response.
|
||||
if (!input.tenantId || !input.actorUserId) return;
|
||||
try {
|
||||
await withTenantRLS(input.tenantId, async (tx) => {
|
||||
await publishAuditEventViaOutbox(tx, {
|
||||
tenantId: input.tenantId,
|
||||
actorId: input.actorUserId,
|
||||
actorType: "user",
|
||||
action: input.outcome === "blocked" ? "customer_portal.user.invitation_blocked" : "customer_portal.user.invitation_failed",
|
||||
targetType: "PortalInvitation",
|
||||
sourceModule: "customer_portal",
|
||||
outcome: input.outcome,
|
||||
dataSensitivity: "internal",
|
||||
regulatoryScope: ["gdpr", "soc2"],
|
||||
metadata: {
|
||||
operation: input.operation,
|
||||
reason: input.reason,
|
||||
},
|
||||
});
|
||||
});
|
||||
} catch (error) {
|
||||
portalInvitationLogger.error(
|
||||
{
|
||||
event: "customer_portal.invitation.audit_failed",
|
||||
operation: input.operation,
|
||||
reason: input.reason,
|
||||
outcome: input.outcome,
|
||||
errorName: error instanceof Error ? error.name : "UnknownError",
|
||||
},
|
||||
"Portal invitation failure audit could not be appended"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function recordPortalInvitationForeignTargetDenial(
|
||||
input: PortalInvitationActor & {
|
||||
readonly operation: Extract<PortalInvitationOperation, "contact_invite" | "project_invite">;
|
||||
}
|
||||
): Promise<void> {
|
||||
await recordPortalInvitationFailure({
|
||||
...input,
|
||||
reason: "foreign_target",
|
||||
outcome: "blocked",
|
||||
});
|
||||
}
|
||||
|
||||
function failureReasonFor(error: PortalInvitationError): PortalInvitationFailureReason {
|
||||
if (error.messageKey === "customerPortal.states.frozen.body") return "tenant_read_only";
|
||||
if (error.messageKey === "customerPortal.admin.errors.activationGate") return "activation_gate";
|
||||
if (error.messageKey === "customerPortal.admin.errors.emailExists") return "duplicate_email";
|
||||
if (error.messageKey === "customerPortal.admin.errors.notFound") return "target_not_found";
|
||||
if (error.messageKey === "customerPortal.admin.errors.invalidInput") return "invalid_input";
|
||||
return "internal_failure";
|
||||
}
|
||||
|
||||
function isUniqueConstraintError(error: unknown): boolean {
|
||||
return Boolean(error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "P2002");
|
||||
}
|
||||
|
||||
function contactIdentity(contact: {
|
||||
readonly vorname: string | null;
|
||||
readonly nachname: string | null;
|
||||
readonly primaerEmail: string | null;
|
||||
readonly language: string | null;
|
||||
}): PortalInviteIdentity {
|
||||
return {
|
||||
email: normalizeEmail(contact.primaerEmail ?? ""),
|
||||
firstName: normalizeName(contact.vorname ?? ""),
|
||||
lastName: normalizeName(contact.nachname ?? ""),
|
||||
locale: contact.language,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeEmail(value: string): string {
|
||||
const email = value.trim().toLowerCase();
|
||||
if (email.length > 320 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email)) throw invalid();
|
||||
return email;
|
||||
}
|
||||
|
||||
function normalizeName(value: string): string {
|
||||
const name = value.trim().slice(0, 120);
|
||||
if (!name) throw invalid();
|
||||
return name;
|
||||
}
|
||||
|
||||
function requireId(value: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 191 || /[\u0000-\u001f\u007f]/u.test(normalized)) throw invalid();
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizeLegalUrl(value: string | null | undefined): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "https:" || url.username || url.password || url.hash) return null;
|
||||
return url.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRootOrigin(value: string | null, requireHttps: boolean): string | null {
|
||||
if (!value) return null;
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if ((requireHttps && url.protocol !== "https:") || (!requireHttps && url.protocol !== "http:" && url.protocol !== "https:")) return null;
|
||||
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;
|
||||
return url.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function sourceForOrigin(origin: PortalInvitationOrigin): string {
|
||||
return origin === "admin" ? "portal_admin_invite" : origin === "contact" ? "portal_contact_invite" : "portal_project_invite";
|
||||
}
|
||||
|
||||
function invalid(): PortalInvitationError {
|
||||
return new PortalInvitationError("customerPortal.admin.errors.invalidInput", 400, "invalid_input");
|
||||
}
|
||||
|
||||
function notFound(reason: "target_not_found" | "foreign_target" = "target_not_found"): PortalInvitationError {
|
||||
return new PortalInvitationError("customerPortal.admin.errors.notFound", 404, reason);
|
||||
}
|
||||
|
||||
function duplicateEmail(): PortalInvitationError {
|
||||
return new PortalInvitationError("customerPortal.admin.errors.emailExists", 409, "duplicate_email");
|
||||
}
|
||||
|
||||
function frozen(reason: "tenant_read_only" | "tenant_state_unprovable"): PortalInvitationError {
|
||||
return new PortalInvitationError("customerPortal.states.frozen.body", 423, reason);
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type { PortalSessionContext } from "./portal-data.server";
|
||||
import {
|
||||
cancelPortalAccountDeletion,
|
||||
loadPortalLifecycle,
|
||||
PortalLifecycleError,
|
||||
recordPortalGdprExportDownload,
|
||||
redactPortalLifecycleDiagnostic,
|
||||
resolvePortalGdprExportArtifact,
|
||||
requestPortalAccountDeletion,
|
||||
requestPortalGdprExport,
|
||||
type PortalLifecycleSnapshot,
|
||||
type PortalLifecycleStore,
|
||||
} from "./portal-lifecycle.server";
|
||||
|
||||
const now = new Date("2026-07-16T10:00:00.000Z");
|
||||
const context: PortalSessionContext = {
|
||||
identity: {
|
||||
tenantId: "tenant_1",
|
||||
portalId: "portal_1",
|
||||
portalUserId: "portal_user_1",
|
||||
portalSessionId: "portal_session_1",
|
||||
tenantSlug: "acme",
|
||||
tenantFrozen: false,
|
||||
portalTitle: "ACME Portal",
|
||||
viewerFirstName: "Ada",
|
||||
viewerLastName: "Lovelace",
|
||||
viewerLocale: "de",
|
||||
createdAt: now,
|
||||
lastSeenAt: now,
|
||||
expiresAt: new Date("2026-07-17T10:00:00.000Z"),
|
||||
origin: "https://portal.hivegrid.de",
|
||||
},
|
||||
origin: {
|
||||
origin: "https://portal.hivegrid.de",
|
||||
hostname: "portal.hivegrid.de",
|
||||
tenantSlug: "acme",
|
||||
customHost: false,
|
||||
},
|
||||
responseHeaders: new Headers(),
|
||||
};
|
||||
|
||||
const snapshot: PortalLifecycleSnapshot = {
|
||||
profile: {
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
phone: null,
|
||||
locale: "de",
|
||||
createdAt: now,
|
||||
lastLoginAt: now,
|
||||
lastActivityAt: now,
|
||||
privacyNoticeAcknowledgedAt: now,
|
||||
privacyNoticeAcknowledgedUrl: "https://acme.example.test/datenschutz",
|
||||
},
|
||||
notificationPreferences: [],
|
||||
exportJobs: [],
|
||||
deletionRequest: null,
|
||||
};
|
||||
|
||||
function store(overrides: Partial<PortalLifecycleStore> = {}): PortalLifecycleStore {
|
||||
return {
|
||||
loadSnapshot: vi.fn(async () => snapshot),
|
||||
upsertNotificationPreference: vi.fn(async () => "preference_1"),
|
||||
requestExport: vi.fn(async () => "export_1"),
|
||||
resolveExportDownload: vi.fn(async () => ({
|
||||
resultBucket: "private-exports",
|
||||
resultKey: "tenants/tenant_1/portal-gdpr/export_1.json",
|
||||
resultSizeBytes: 42,
|
||||
resultExpiresAt: new Date("2026-07-17T10:00:00.000Z"),
|
||||
})),
|
||||
recordExportDownload: vi.fn(async () => ({
|
||||
resultBucket: "private-exports",
|
||||
resultKey: "tenants/tenant_1/portal-gdpr/export_1.json",
|
||||
resultSizeBytes: 42,
|
||||
resultExpiresAt: new Date("2026-07-17T10:00:00.000Z"),
|
||||
})),
|
||||
resolveDeletionPasswordHash: vi.fn(async () => "$argon2id$hash"),
|
||||
requestDeletion: vi.fn(async () => ({
|
||||
id: "deletion_1",
|
||||
requestedAt: now,
|
||||
cancellableUntil: new Date("2026-07-17T10:00:00.000Z"),
|
||||
})),
|
||||
cancelDeletion: vi.fn(async () => true),
|
||||
appendAudit: vi.fn(async () => undefined),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("portal lifecycle self service", () => {
|
||||
it("loads only the portal-scoped snapshot through the injected store", async () => {
|
||||
const lifecycleStore = store();
|
||||
|
||||
await expect(loadPortalLifecycle(context, { store: lifecycleStore })).resolves.toBe(snapshot);
|
||||
expect(lifecycleStore.loadSnapshot).toHaveBeenCalledWith(context.identity);
|
||||
});
|
||||
|
||||
it("requests an idempotent JSON export and appends a GDPR audit event", async () => {
|
||||
const lifecycleStore = store();
|
||||
const request = new Request("https://portal.hivegrid.de/acme/settings", {
|
||||
headers: { "x-request-id": "request-export-1" },
|
||||
});
|
||||
|
||||
await expect(requestPortalGdprExport(context, { idempotencyKey: "portal-export:1", request }, { store: lifecycleStore })).resolves.toEqual({
|
||||
exportId: "export_1",
|
||||
});
|
||||
expect(lifecycleStore.requestExport).toHaveBeenCalledWith(context.identity, "portal-export:1");
|
||||
expect(lifecycleStore.appendAudit).toHaveBeenCalledWith({
|
||||
identity: context.identity,
|
||||
action: "customer_portal.gdpr_export.requested",
|
||||
targetId: "portal_user_1",
|
||||
requestId: "request-export-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("authorizes and counts only one ready, unexpired export artifact", async () => {
|
||||
const lifecycleStore = store();
|
||||
|
||||
await expect(recordPortalGdprExportDownload(context, { exportId: "export_1" }, { store: lifecycleStore })).resolves.toMatchObject({
|
||||
resultBucket: "private-exports",
|
||||
resultSizeBytes: 42,
|
||||
});
|
||||
expect(lifecycleStore.appendAudit).toHaveBeenCalledWith(expect.objectContaining({ action: "customer_portal.gdpr_export.downloaded" }));
|
||||
});
|
||||
|
||||
it("resolves a ready artifact without counting or auditing a download", async () => {
|
||||
const lifecycleStore = store();
|
||||
|
||||
await expect(resolvePortalGdprExportArtifact(context, { exportId: "export_1" }, { store: lifecycleStore })).resolves.toMatchObject({
|
||||
resultBucket: "private-exports",
|
||||
resultSizeBytes: 42,
|
||||
});
|
||||
expect(lifecycleStore.resolveExportDownload).toHaveBeenCalledWith(context.identity, "export_1");
|
||||
expect(lifecycleStore.recordExportDownload).not.toHaveBeenCalled();
|
||||
expect(lifecycleStore.appendAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("requires the current password before creating the 24-hour deletion request", async () => {
|
||||
const lifecycleStore = store();
|
||||
const verify = vi.fn(async () => ({ valid: true as const }));
|
||||
|
||||
await expect(
|
||||
requestPortalAccountDeletion(
|
||||
context,
|
||||
{ password: "correct horse battery staple", idempotencyKey: "portal-delete:1" },
|
||||
{ store: lifecycleStore, verifyPassword: verify }
|
||||
)
|
||||
).resolves.toEqual({
|
||||
deletionRequestId: "deletion_1",
|
||||
requestedAt: now,
|
||||
cancellableUntil: new Date("2026-07-17T10:00:00.000Z"),
|
||||
});
|
||||
expect(verify).toHaveBeenCalledWith("correct horse battery staple", "$argon2id$hash");
|
||||
expect(lifecycleStore.requestDeletion).toHaveBeenCalledWith({
|
||||
identity: context.identity,
|
||||
idempotencyKey: "portal-delete:1",
|
||||
settingsUrl: "https://portal.hivegrid.de/acme/settings",
|
||||
});
|
||||
expect(lifecycleStore.appendAudit).toHaveBeenCalledWith(expect.objectContaining({ action: "customer_portal.deletion.requested" }));
|
||||
});
|
||||
|
||||
it("uses the host-bound custom-domain settings URL in the confirmation mail contract", async () => {
|
||||
const lifecycleStore = store();
|
||||
const customHostContext: PortalSessionContext = {
|
||||
...context,
|
||||
identity: { ...context.identity, origin: "https://kunden.acme.de" },
|
||||
origin: {
|
||||
origin: "https://kunden.acme.de",
|
||||
hostname: "kunden.acme.de",
|
||||
tenantSlug: "acme",
|
||||
customHost: true,
|
||||
},
|
||||
};
|
||||
|
||||
await requestPortalAccountDeletion(
|
||||
customHostContext,
|
||||
{ password: "correct horse battery staple", idempotencyKey: "portal-delete:custom" },
|
||||
{ store: lifecycleStore, verifyPassword: vi.fn(async () => ({ valid: true as const })) }
|
||||
);
|
||||
|
||||
expect(lifecycleStore.requestDeletion).toHaveBeenCalledWith(expect.objectContaining({ settingsUrl: "https://kunden.acme.de/settings" }));
|
||||
});
|
||||
|
||||
it("fails closed on a wrong password without creating a request or audit event", async () => {
|
||||
const lifecycleStore = store();
|
||||
|
||||
await expect(
|
||||
requestPortalAccountDeletion(
|
||||
context,
|
||||
{ password: "wrong", idempotencyKey: "portal-delete:2" },
|
||||
{ store: lifecycleStore, verifyPassword: vi.fn(async () => ({ valid: false as const })) }
|
||||
)
|
||||
).rejects.toMatchObject({ code: "PASSWORD_INVALID" });
|
||||
expect(lifecycleStore.requestDeletion).not.toHaveBeenCalled();
|
||||
expect(lifecycleStore.appendAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels only inside the reverse window and audits the cancellation", async () => {
|
||||
const lifecycleStore = store();
|
||||
|
||||
await expect(cancelPortalAccountDeletion(context, { deletionRequestId: "deletion_1" }, { store: lifecycleStore })).resolves.toBeUndefined();
|
||||
expect(lifecycleStore.cancelDeletion).toHaveBeenCalledWith(context.identity, "deletion_1");
|
||||
expect(lifecycleStore.appendAudit).toHaveBeenCalledWith(expect.objectContaining({ action: "customer_portal.deletion.cancelled" }));
|
||||
});
|
||||
|
||||
it("does not expose secrets in lifecycle diagnostics", () => {
|
||||
const diagnostic = redactPortalLifecycleDiagnostic(new Error("authorization: Bearer abc password=hunter2 token=opaque cookie=session secret=top"));
|
||||
|
||||
expect(diagnostic).not.toMatch(/abc|hunter2|opaque|session|top/u);
|
||||
expect(diagnostic).toContain("[REDACTED]");
|
||||
});
|
||||
|
||||
it("rejects malformed idempotency keys before store access", async () => {
|
||||
const lifecycleStore = store();
|
||||
|
||||
await expect(requestPortalGdprExport(context, { idempotencyKey: "contains spaces" }, { store: lifecycleStore })).rejects.toBeInstanceOf(
|
||||
PortalLifecycleError
|
||||
);
|
||||
expect(lifecycleStore.requestExport).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+403
@@ -0,0 +1,403 @@
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import { getWriteDbClient } from "@hivegrid/db/client.server";
|
||||
import { runWithPortalRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
|
||||
import { verifyPassword } from "~/utils/auth/passwordHasher.server";
|
||||
|
||||
import { appendPortalAuditEvent, PORTAL_AUDIT_ACTIONS, portalAuditRequestId } from "./portal-audit.server";
|
||||
import type { PortalSessionContext, PortalSessionIdentity } from "./portal-data.server";
|
||||
import { portalPublicPath } from "./portal-origin.server";
|
||||
|
||||
const PORTAL_DUMMY_PASSWORD_HASH = "$argon2id$v=19$m=19456,t=2,p=1$CGZ841jS/Rerhh41+cREiw$piaCzFMbzHjq946K2t0iN7iMI/389iUpLNm2HROGO4Y";
|
||||
const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9._:-]{1,128}$/u;
|
||||
const PORTAL_LIFECYCLE_PREFERENCE_EVENT_TYPES = ["status_mail", "lifecycle"] as const;
|
||||
|
||||
export const PORTAL_GDPR_EXPORT_TYPE = "gdpr_portal_user_self" as const;
|
||||
export const PORTAL_GDPR_ARTIFACT_TTL_HOURS = 24;
|
||||
export const PORTAL_DELETION_REVERSE_WINDOW_HOURS = 24;
|
||||
|
||||
export type PortalLifecycleErrorCode =
|
||||
| "INVALID_REQUEST"
|
||||
| "PASSWORD_REQUIRED"
|
||||
| "PASSWORD_INVALID"
|
||||
| "DELETE_ALREADY_PENDING"
|
||||
| "DELETE_NOT_CANCELLABLE"
|
||||
| "EXPORT_NOT_AVAILABLE";
|
||||
|
||||
export class PortalLifecycleError extends Error {
|
||||
override readonly name = "PortalLifecycleError";
|
||||
|
||||
constructor(readonly code: PortalLifecycleErrorCode) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export type PortalLifecycleProfile = {
|
||||
readonly email: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly phone: string | null;
|
||||
readonly locale: string;
|
||||
readonly createdAt: Date;
|
||||
readonly lastLoginAt: Date | null;
|
||||
readonly lastActivityAt: Date | null;
|
||||
readonly privacyNoticeAcknowledgedAt: Date | null;
|
||||
readonly privacyNoticeAcknowledgedUrl: string | null;
|
||||
};
|
||||
|
||||
export type PortalLifecyclePreference = {
|
||||
readonly eventType: "status_mail" | "lifecycle";
|
||||
readonly emailEnabled: boolean;
|
||||
readonly mutedUntil: Date | null;
|
||||
};
|
||||
|
||||
export type PortalLifecycleExportJob = {
|
||||
readonly id: string;
|
||||
readonly status: "queued" | "processing" | "ready" | "expired" | "failed";
|
||||
readonly progressPercent: number;
|
||||
readonly createdAt: Date;
|
||||
readonly resultExpiresAt: Date | null;
|
||||
readonly failureCode: string | null;
|
||||
};
|
||||
|
||||
export type PortalLifecycleDeletionRequest = {
|
||||
readonly id: string;
|
||||
readonly status: "pending" | "cancelled" | "processing" | "completed" | "failed";
|
||||
readonly requestedAt: Date;
|
||||
readonly cancellableUntil: Date;
|
||||
readonly cancelledAt: Date | null;
|
||||
readonly completedAt: Date | null;
|
||||
readonly failureCode: string | null;
|
||||
};
|
||||
|
||||
export type PortalLifecycleSnapshot = {
|
||||
readonly profile: PortalLifecycleProfile;
|
||||
readonly notificationPreferences: readonly PortalLifecyclePreference[];
|
||||
readonly exportJobs: readonly PortalLifecycleExportJob[];
|
||||
readonly deletionRequest: PortalLifecycleDeletionRequest | null;
|
||||
};
|
||||
|
||||
export type PortalGdprArtifact = {
|
||||
readonly resultBucket: string;
|
||||
readonly resultKey: string;
|
||||
readonly resultSizeBytes: number | null;
|
||||
readonly resultExpiresAt: Date;
|
||||
};
|
||||
|
||||
export interface PortalLifecycleStore {
|
||||
loadSnapshot(identity: PortalSessionIdentity): Promise<PortalLifecycleSnapshot>;
|
||||
upsertNotificationPreference(input: {
|
||||
identity: PortalSessionIdentity;
|
||||
eventType: PortalLifecyclePreference["eventType"];
|
||||
emailEnabled: boolean;
|
||||
mutedUntil: Date | null;
|
||||
}): Promise<string>;
|
||||
requestExport(identity: PortalSessionIdentity, idempotencyKey: string): Promise<string>;
|
||||
resolveExportDownload(identity: PortalSessionIdentity, exportId: string): Promise<PortalGdprArtifact | null>;
|
||||
recordExportDownload(identity: PortalSessionIdentity, exportId: string): Promise<PortalGdprArtifact | null>;
|
||||
resolveDeletionPasswordHash(identity: PortalSessionIdentity): Promise<string | null>;
|
||||
requestDeletion(input: {
|
||||
identity: PortalSessionIdentity;
|
||||
idempotencyKey: string;
|
||||
settingsUrl: string;
|
||||
}): Promise<{ id: string; requestedAt: Date; cancellableUntil: Date } | null>;
|
||||
cancelDeletion(identity: PortalSessionIdentity, requestId: string): Promise<boolean>;
|
||||
appendAudit(input: {
|
||||
identity: PortalSessionIdentity;
|
||||
action: (typeof PORTAL_AUDIT_ACTIONS)[keyof typeof PORTAL_AUDIT_ACTIONS];
|
||||
targetId: string;
|
||||
requestId?: string | null;
|
||||
}): Promise<void>;
|
||||
}
|
||||
|
||||
export type PortalLifecycleDependencies = {
|
||||
readonly store?: PortalLifecycleStore;
|
||||
readonly verifyPassword?: typeof verifyPassword;
|
||||
};
|
||||
|
||||
export async function loadPortalLifecycle(context: PortalSessionContext, dependencies: PortalLifecycleDependencies = {}): Promise<PortalLifecycleSnapshot> {
|
||||
return withPortalStore(context.identity, dependencies, (store) => store.loadSnapshot(context.identity));
|
||||
}
|
||||
|
||||
export async function updatePortalNotificationPreference(
|
||||
context: PortalSessionContext,
|
||||
input: {
|
||||
readonly eventType: PortalLifecyclePreference["eventType"];
|
||||
readonly emailEnabled: boolean;
|
||||
readonly mutedUntil?: Date | null;
|
||||
},
|
||||
dependencies: PortalLifecycleDependencies = {}
|
||||
): Promise<string> {
|
||||
return withPortalStore(context.identity, dependencies, (store) =>
|
||||
store.upsertNotificationPreference({
|
||||
identity: context.identity,
|
||||
eventType: input.eventType,
|
||||
emailEnabled: input.emailEnabled,
|
||||
mutedUntil: input.mutedUntil ?? null,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function requestPortalGdprExport(
|
||||
context: PortalSessionContext,
|
||||
input: { readonly idempotencyKey: string; readonly request?: Request },
|
||||
dependencies: PortalLifecycleDependencies = {}
|
||||
): Promise<{ readonly exportId: string }> {
|
||||
const idempotencyKey = normalizeIdempotencyKey(input.idempotencyKey);
|
||||
return withPortalStore(context.identity, dependencies, async (store) => {
|
||||
const exportId = await store.requestExport(context.identity, idempotencyKey);
|
||||
await store.appendAudit({
|
||||
identity: context.identity,
|
||||
action: PORTAL_AUDIT_ACTIONS.gdprExportRequested,
|
||||
targetId: context.identity.portalUserId,
|
||||
requestId: input.request ? portalAuditRequestId(input.request) : null,
|
||||
});
|
||||
return { exportId };
|
||||
});
|
||||
}
|
||||
|
||||
export async function recordPortalGdprExportDownload(
|
||||
context: PortalSessionContext,
|
||||
input: { readonly exportId: string; readonly request?: Request },
|
||||
dependencies: PortalLifecycleDependencies = {}
|
||||
): Promise<PortalGdprArtifact> {
|
||||
const exportId = requireIdentifier(input.exportId);
|
||||
return withPortalStore(context.identity, dependencies, async (store) => {
|
||||
const artifact = await store.recordExportDownload(context.identity, exportId);
|
||||
if (!artifact) throw new PortalLifecycleError("EXPORT_NOT_AVAILABLE");
|
||||
await store.appendAudit({
|
||||
identity: context.identity,
|
||||
action: PORTAL_AUDIT_ACTIONS.gdprExportDownloaded,
|
||||
targetId: context.identity.portalUserId,
|
||||
requestId: input.request ? portalAuditRequestId(input.request) : null,
|
||||
});
|
||||
return artifact;
|
||||
});
|
||||
}
|
||||
|
||||
export async function resolvePortalGdprExportArtifact(
|
||||
context: PortalSessionContext,
|
||||
input: { readonly exportId: string },
|
||||
dependencies: PortalLifecycleDependencies = {}
|
||||
): Promise<PortalGdprArtifact> {
|
||||
const exportId = requireIdentifier(input.exportId);
|
||||
return withPortalStore(context.identity, dependencies, async (store) => {
|
||||
const artifact = await store.resolveExportDownload(context.identity, exportId);
|
||||
if (!artifact) throw new PortalLifecycleError("EXPORT_NOT_AVAILABLE");
|
||||
return artifact;
|
||||
});
|
||||
}
|
||||
|
||||
export async function requestPortalAccountDeletion(
|
||||
context: PortalSessionContext,
|
||||
input: {
|
||||
readonly password: string;
|
||||
readonly idempotencyKey: string;
|
||||
readonly request?: Request;
|
||||
},
|
||||
dependencies: PortalLifecycleDependencies = {}
|
||||
): Promise<{ readonly deletionRequestId: string; readonly requestedAt: Date; readonly cancellableUntil: Date }> {
|
||||
const idempotencyKey = normalizeIdempotencyKey(input.idempotencyKey);
|
||||
if (!input.password) throw new PortalLifecycleError("PASSWORD_REQUIRED");
|
||||
if (input.password.length > 1_024) throw new PortalLifecycleError("PASSWORD_INVALID");
|
||||
|
||||
return withPortalStore(context.identity, dependencies, async (store) => {
|
||||
const passwordHash = await store.resolveDeletionPasswordHash(context.identity);
|
||||
const verification = await (dependencies.verifyPassword ?? verifyPassword)(input.password, passwordHash ?? PORTAL_DUMMY_PASSWORD_HASH);
|
||||
if (!passwordHash || !verification.valid) throw new PortalLifecycleError("PASSWORD_INVALID");
|
||||
|
||||
const deletionRequest = await store.requestDeletion({
|
||||
identity: context.identity,
|
||||
idempotencyKey,
|
||||
settingsUrl: new URL(portalPublicPath(context.origin, "settings"), context.origin.origin).href,
|
||||
});
|
||||
if (!deletionRequest) throw new PortalLifecycleError("DELETE_ALREADY_PENDING");
|
||||
await store.appendAudit({
|
||||
identity: context.identity,
|
||||
action: PORTAL_AUDIT_ACTIONS.deletionRequested,
|
||||
targetId: context.identity.portalUserId,
|
||||
requestId: input.request ? portalAuditRequestId(input.request) : null,
|
||||
});
|
||||
return {
|
||||
deletionRequestId: deletionRequest.id,
|
||||
requestedAt: deletionRequest.requestedAt,
|
||||
cancellableUntil: deletionRequest.cancellableUntil,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export async function cancelPortalAccountDeletion(
|
||||
context: PortalSessionContext,
|
||||
input: { readonly deletionRequestId: string; readonly request?: Request },
|
||||
dependencies: PortalLifecycleDependencies = {}
|
||||
): Promise<void> {
|
||||
const deletionRequestId = requireIdentifier(input.deletionRequestId);
|
||||
await withPortalStore(context.identity, dependencies, async (store) => {
|
||||
const cancelled = await store.cancelDeletion(context.identity, deletionRequestId);
|
||||
if (!cancelled) throw new PortalLifecycleError("DELETE_NOT_CANCELLABLE");
|
||||
await store.appendAudit({
|
||||
identity: context.identity,
|
||||
action: PORTAL_AUDIT_ACTIONS.deletionCancelled,
|
||||
targetId: context.identity.portalUserId,
|
||||
requestId: input.request ? portalAuditRequestId(input.request) : null,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function createPortalLifecycleStore(db: DbClient = getWriteDbClient()): PortalLifecycleStore {
|
||||
return {
|
||||
async loadSnapshot(identity) {
|
||||
const profileRows = await db.$queryRaw<PortalLifecycleProfile[]>`
|
||||
SELECT * FROM public.hivegrid_portal_resolve_lifecycle_profile()
|
||||
`;
|
||||
const profile = profileRows[0];
|
||||
if (!profile) throw new PortalLifecycleError("INVALID_REQUEST");
|
||||
const [notificationPreferences, exportJobs, deletionRequest] = await Promise.all([
|
||||
db.portalNotificationPreference.findMany({
|
||||
where: {
|
||||
tenantId: identity.tenantId,
|
||||
portalUserId: identity.portalUserId,
|
||||
eventType: { in: [...PORTAL_LIFECYCLE_PREFERENCE_EVENT_TYPES] },
|
||||
},
|
||||
orderBy: { eventType: "asc" },
|
||||
select: { eventType: true, emailEnabled: true, mutedUntil: true },
|
||||
}),
|
||||
db.portalGdprExportJob.findMany({
|
||||
where: { tenantId: identity.tenantId, portalUserId: identity.portalUserId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 20,
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
progressPercent: true,
|
||||
createdAt: true,
|
||||
resultExpiresAt: true,
|
||||
failureCode: true,
|
||||
},
|
||||
}),
|
||||
db.portalDeletionRequest.findFirst({
|
||||
where: {
|
||||
tenantId: identity.tenantId,
|
||||
portalUserId: identity.portalUserId,
|
||||
status: { in: ["pending", "processing", "failed"] },
|
||||
},
|
||||
orderBy: { requestedAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
requestedAt: true,
|
||||
cancellableUntil: true,
|
||||
cancelledAt: true,
|
||||
completedAt: true,
|
||||
failureCode: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const supportedNotificationPreferences = notificationPreferences.filter((preference): preference is PortalLifecyclePreference =>
|
||||
isPortalLifecyclePreferenceEventType(preference.eventType)
|
||||
);
|
||||
return {
|
||||
profile,
|
||||
notificationPreferences: supportedNotificationPreferences,
|
||||
exportJobs,
|
||||
deletionRequest,
|
||||
};
|
||||
},
|
||||
|
||||
async upsertNotificationPreference(input) {
|
||||
const rows = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT public.hivegrid_portal_upsert_notification_preference(
|
||||
${input.eventType}, ${input.emailEnabled}, ${input.mutedUntil}
|
||||
) AS id
|
||||
`;
|
||||
const id = rows[0]?.id;
|
||||
if (!id) throw new PortalLifecycleError("INVALID_REQUEST");
|
||||
return id;
|
||||
},
|
||||
|
||||
async requestExport(_identity, idempotencyKey) {
|
||||
const rows = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT public.hivegrid_portal_request_gdpr_export(${idempotencyKey}) AS id
|
||||
`;
|
||||
const id = rows[0]?.id;
|
||||
if (!id) throw new PortalLifecycleError("INVALID_REQUEST");
|
||||
return id;
|
||||
},
|
||||
|
||||
async resolveExportDownload(_identity, exportId) {
|
||||
const rows = await db.$queryRaw<PortalGdprArtifact[]>`
|
||||
SELECT * FROM public.hivegrid_portal_resolve_gdpr_export(${exportId})
|
||||
`;
|
||||
return rows[0] ?? null;
|
||||
},
|
||||
|
||||
async recordExportDownload(_identity, exportId) {
|
||||
const rows = await db.$queryRaw<PortalGdprArtifact[]>`
|
||||
SELECT * FROM public.hivegrid_portal_record_gdpr_export_download(${exportId})
|
||||
`;
|
||||
return rows[0] ?? null;
|
||||
},
|
||||
|
||||
async resolveDeletionPasswordHash() {
|
||||
const rows = await db.$queryRaw<Array<{ passwordHash: string | null }>>`
|
||||
SELECT * FROM public.hivegrid_portal_resolve_deletion_password_hash()
|
||||
`;
|
||||
return rows[0]?.passwordHash ?? null;
|
||||
},
|
||||
|
||||
async requestDeletion(input) {
|
||||
const rows = await db.$queryRaw<Array<{ id: string; requestedAt: Date; cancellableUntil: Date }>>`
|
||||
SELECT * FROM public.hivegrid_portal_request_deletion(${input.idempotencyKey}, ${input.settingsUrl})
|
||||
`;
|
||||
return rows[0] ?? null;
|
||||
},
|
||||
|
||||
async cancelDeletion(_identity, requestId) {
|
||||
const rows = await db.$queryRaw<Array<{ cancelled: boolean }>>`
|
||||
SELECT public.hivegrid_portal_cancel_deletion(${requestId}) AS cancelled
|
||||
`;
|
||||
return rows[0]?.cancelled === true;
|
||||
},
|
||||
|
||||
async appendAudit(input) {
|
||||
await appendPortalAuditEvent(db, {
|
||||
action: input.action,
|
||||
targetId: input.targetId,
|
||||
requestId: input.requestId,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function redactPortalLifecycleDiagnostic(value: unknown): string {
|
||||
const message = value instanceof Error ? value.message : String(value);
|
||||
return message
|
||||
.replace(/(authorization\s*[:=]\s*Bearer\s+)\S+/giu, "$1[REDACTED]")
|
||||
.replace(/(password|secret|token|cookie|api[-_]?key)(\s*[:=]\s*)\S+/giu, "$1$2[REDACTED]")
|
||||
.slice(0, 500);
|
||||
}
|
||||
|
||||
async function withPortalStore<T>(
|
||||
identity: PortalSessionIdentity,
|
||||
dependencies: PortalLifecycleDependencies,
|
||||
operation: (store: PortalLifecycleStore) => Promise<T>
|
||||
): Promise<T> {
|
||||
const store = dependencies.store ?? createPortalLifecycleStore();
|
||||
return runWithPortalRlsContext(identity, () => operation(store));
|
||||
}
|
||||
|
||||
function normalizeIdempotencyKey(value: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!IDEMPOTENCY_KEY_PATTERN.test(normalized)) throw new PortalLifecycleError("INVALID_REQUEST");
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function isPortalLifecyclePreferenceEventType(eventType: string): eventType is PortalLifecyclePreference["eventType"] {
|
||||
return PORTAL_LIFECYCLE_PREFERENCE_EVENT_TYPES.some((candidate) => candidate === eventType);
|
||||
}
|
||||
|
||||
function requireIdentifier(value: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 191) throw new PortalLifecycleError("INVALID_REQUEST");
|
||||
return normalized;
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { portalPublicPath, requirePortalRouteTenantSlug, requireTrustedPortalOrigin } from "./portal-origin.server";
|
||||
|
||||
function trustedRequest(url: string, tenant = "acme", customHost?: string) {
|
||||
const origin = new URL(url).origin;
|
||||
const headers: Record<string, string> = {
|
||||
"x-hivegrid-portal-tenant": tenant,
|
||||
"x-hivegrid-portal-origin": origin,
|
||||
};
|
||||
if (customHost) headers["x-hivegrid-portal-custom-host"] = customHost;
|
||||
return new Request(url, { headers });
|
||||
}
|
||||
|
||||
describe("trusted portal origin", () => {
|
||||
it("keeps standard-host paths tenant-prefixed", () => {
|
||||
const context = requireTrustedPortalOrigin(trustedRequest("http://portal.localhost/acme/projects"), "acme");
|
||||
expect(context).toEqual({ origin: "http://portal.localhost", hostname: "portal.localhost", tenantSlug: "acme", customHost: false });
|
||||
expect(portalPublicPath(context)).toBe("/acme");
|
||||
expect(portalPublicPath(context, "/login/magic/token/")).toBe("/acme/login/magic/token");
|
||||
});
|
||||
|
||||
it("keeps custom-host paths free of the tenant slug", () => {
|
||||
const context = requireTrustedPortalOrigin(trustedRequest("https://kunden.geerkens.de/projects", "acme", "kunden.geerkens.de"), "acme");
|
||||
expect(context.customHost).toBe(true);
|
||||
expect(portalPublicPath(context)).toBe("/");
|
||||
expect(portalPublicPath(context, "projects/project-1")).toBe("/projects/project-1");
|
||||
});
|
||||
|
||||
it("binds standard-host routes to the exact trusted tenant segment", () => {
|
||||
const request = trustedRequest("https://portal.example.test/acme/login");
|
||||
expect(requirePortalRouteTenantSlug(request, "acme")).toBe("acme");
|
||||
expect(() => requirePortalRouteTenantSlug(request, undefined)).toThrow(expect.objectContaining({ status: 404 }));
|
||||
expect(() => requirePortalRouteTenantSlug(request, "other")).toThrow(expect.objectContaining({ status: 404 }));
|
||||
});
|
||||
|
||||
it("accepts only the slugless route tree on a trusted custom host", () => {
|
||||
const request = trustedRequest("https://kunden.geerkens.de/login", "acme", "kunden.geerkens.de");
|
||||
const unknownPath = trustedRequest("https://kunden.geerkens.de/unknown", "acme", "kunden.geerkens.de");
|
||||
const tenantPrefixedPath = trustedRequest("https://kunden.geerkens.de/acme/login", "acme", "kunden.geerkens.de");
|
||||
expect(requirePortalRouteTenantSlug(request, undefined)).toBe("acme");
|
||||
expect(() => requirePortalRouteTenantSlug(request, "acme")).toThrow(expect.objectContaining({ status: 404 }));
|
||||
expect(() => requirePortalRouteTenantSlug(request, "other")).toThrow(expect.objectContaining({ status: 404 }));
|
||||
expect(() => requirePortalRouteTenantSlug(unknownPath, "unknown")).toThrow(expect.objectContaining({ status: 404 }));
|
||||
expect(() => requirePortalRouteTenantSlug(tenantPrefixedPath, "acme")).toThrow(expect.objectContaining({ status: 404 }));
|
||||
});
|
||||
|
||||
it.each([
|
||||
new Request("https://kunden.geerkens.de", { headers: { "x-hivegrid-portal-tenant": "acme" } }),
|
||||
new Request("https://kunden.geerkens.de", {
|
||||
headers: { "x-hivegrid-portal-tenant": "other", "x-hivegrid-portal-origin": "https://kunden.geerkens.de" },
|
||||
}),
|
||||
new Request("https://kunden.geerkens.de", {
|
||||
headers: { "x-hivegrid-portal-tenant": "acme", "x-hivegrid-portal-origin": "https://evil.example.org" },
|
||||
}),
|
||||
new Request("https://kunden.geerkens.de", {
|
||||
headers: {
|
||||
"x-hivegrid-portal-tenant": "acme",
|
||||
"x-hivegrid-portal-origin": "https://kunden.geerkens.de",
|
||||
"x-hivegrid-portal-custom-host": "evil.example.org",
|
||||
},
|
||||
}),
|
||||
new Request("http://kunden.geerkens.de", {
|
||||
headers: {
|
||||
"x-hivegrid-portal-tenant": "acme",
|
||||
"x-hivegrid-portal-origin": "http://kunden.geerkens.de",
|
||||
"x-hivegrid-portal-custom-host": "kunden.geerkens.de",
|
||||
},
|
||||
}),
|
||||
])("fails closed for missing or inconsistent trust context", (request) => {
|
||||
expect(() => requireTrustedPortalOrigin(request, "acme")).toThrow(expect.objectContaining({ status: 404 }));
|
||||
});
|
||||
});
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
const PORTAL_TENANT_HEADER = "x-hivegrid-portal-tenant";
|
||||
const PORTAL_ORIGIN_HEADER = "x-hivegrid-portal-origin";
|
||||
const PORTAL_CUSTOM_HOST_HEADER = "x-hivegrid-portal-custom-host";
|
||||
const TENANT_SLUG_PATTERN = /^[a-z0-9][a-z0-9-]{1,62}$/u;
|
||||
|
||||
export type TrustedPortalOrigin = {
|
||||
readonly origin: string;
|
||||
readonly hostname: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly customHost: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolves the tenant segment selected by the public route manifest against
|
||||
* the context injected by the outer Host -> Portal boundary.
|
||||
*
|
||||
* Standard-host routes must carry the exact tenant slug in the URL. Custom
|
||||
* hosts must use the slugless alias tree, so any route-level tenant segment is
|
||||
* rejected even when it happens to equal the trusted tenant. This prevents a
|
||||
* second, tenant-prefixed URL contract from being exposed on a custom host.
|
||||
*/
|
||||
export function requirePortalRouteTenantSlug(request: Request, routeTenantSlug: string | undefined): string {
|
||||
const trustedTenant = request.headers.get(PORTAL_TENANT_HEADER)?.trim().toLowerCase();
|
||||
if (!trustedTenant || !TENANT_SLUG_PATTERN.test(trustedTenant)) throw portalOriginNotFound();
|
||||
|
||||
const customHostname = request.headers.get(PORTAL_CUSTOM_HOST_HEADER)?.trim().toLowerCase() ?? null;
|
||||
if (customHostname) {
|
||||
if (routeTenantSlug !== undefined) throw portalOriginNotFound();
|
||||
return trustedTenant;
|
||||
}
|
||||
|
||||
const tenantSlug = routeTenantSlug?.trim().toLowerCase();
|
||||
if (!tenantSlug || !TENANT_SLUG_PATTERN.test(tenantSlug) || tenantSlug !== trustedTenant) throw portalOriginNotFound();
|
||||
return tenantSlug;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads only context injected by the outer host-routing boundary. The direct
|
||||
* request URL must agree byte-for-byte with the trusted origin, preventing a
|
||||
* capability URL or session issued on one portal hostname from being replayed
|
||||
* on another hostname that happens to resolve to the same tenant.
|
||||
*/
|
||||
export function requireTrustedPortalOrigin(request: Request, routeTenantSlug: string): TrustedPortalOrigin {
|
||||
const tenantSlug = routeTenantSlug.trim().toLowerCase();
|
||||
const trustedTenant = request.headers.get(PORTAL_TENANT_HEADER)?.trim().toLowerCase();
|
||||
if (!TENANT_SLUG_PATTERN.test(tenantSlug) || trustedTenant !== tenantSlug) throw portalOriginNotFound();
|
||||
|
||||
const requestUrl = new URL(request.url);
|
||||
const trustedOriginValue = request.headers.get(PORTAL_ORIGIN_HEADER);
|
||||
if (!trustedOriginValue) throw portalOriginNotFound();
|
||||
let trustedOrigin: URL;
|
||||
try {
|
||||
trustedOrigin = new URL(trustedOriginValue);
|
||||
} catch {
|
||||
throw portalOriginNotFound();
|
||||
}
|
||||
if (
|
||||
trustedOrigin.origin !== trustedOriginValue ||
|
||||
trustedOrigin.origin !== requestUrl.origin ||
|
||||
trustedOrigin.pathname !== "/" ||
|
||||
trustedOrigin.search ||
|
||||
trustedOrigin.hash ||
|
||||
trustedOrigin.username ||
|
||||
trustedOrigin.password
|
||||
) {
|
||||
throw portalOriginNotFound();
|
||||
}
|
||||
|
||||
const customHostname = request.headers.get(PORTAL_CUSTOM_HOST_HEADER)?.trim().toLowerCase() ?? null;
|
||||
if (customHostname && (trustedOrigin.protocol !== "https:" || trustedOrigin.hostname.toLowerCase() !== customHostname || trustedOrigin.port)) {
|
||||
throw portalOriginNotFound();
|
||||
}
|
||||
return {
|
||||
origin: trustedOrigin.origin,
|
||||
hostname: trustedOrigin.hostname.toLowerCase(),
|
||||
tenantSlug,
|
||||
customHost: Boolean(customHostname),
|
||||
};
|
||||
}
|
||||
|
||||
export function portalPublicPath(origin: TrustedPortalOrigin, relativePath = ""): string {
|
||||
const normalizedPath = relativePath.replace(/^\/+|\/+$/gu, "");
|
||||
const prefix = origin.customHost ? "" : `/${origin.tenantSlug}`;
|
||||
return normalizedPath ? `${prefix}/${normalizedPath}` : prefix || "/";
|
||||
}
|
||||
|
||||
function portalOriginNotFound(): Response {
|
||||
return new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
import type { WebRuntimeSurface } from "@hivegrid/config";
|
||||
|
||||
const portalTenantSlugPattern = "[a-z0-9][a-z0-9-]{1,62}";
|
||||
const portalCapabilityPathPattern = new RegExp(`^/${portalTenantSlugPattern}/(?:login/magic|setup|verify-email|reset-password)/[^/]+$`, "u");
|
||||
|
||||
/**
|
||||
* Capability values live in the URL, so the transport must protect every
|
||||
* outcome, including thrown 404s, CSRF failures, redirects, and data requests.
|
||||
*/
|
||||
export function getPortalCapabilityResponseSecurityHeaders(
|
||||
request: Request,
|
||||
runtimeSurface: WebRuntimeSurface
|
||||
): Readonly<Record<"Cache-Control" | "Referrer-Policy", string>> | null {
|
||||
if (runtimeSurface !== "portal") return null;
|
||||
const pathname = new URL(request.url).pathname.replace(/\.data$/u, "").replace(/\/+$/u, "");
|
||||
if (!portalCapabilityPathPattern.test(pathname)) return null;
|
||||
return { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" };
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const { config } = vi.hoisted(() => ({
|
||||
config: {
|
||||
runtimeSurface: "portal" as "core" | "portal",
|
||||
nodeEnv: "production",
|
||||
portalSessionSecret: "p".repeat(48),
|
||||
appName: "HiveGrid",
|
||||
i18n: { enabledLocales: ["de", "en"] as const },
|
||||
routing: { appBaseDomain: "hivegrid.de", protocol: "https" as const },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@hivegrid/config")>();
|
||||
return { ...actual, loadRequiredWebConfig: () => config };
|
||||
});
|
||||
|
||||
vi.mock("~/utils/security/requestContentSecurityPolicy.server", () => ({
|
||||
getRequestDocumentContentSecurityPolicyOptions: () => ({}),
|
||||
}));
|
||||
|
||||
import { isPortalRootData } from "./portal-root";
|
||||
import { handlePortalRootAction, loadPortalRootData } from "./portal-root.server";
|
||||
|
||||
describe("portal root boundary", () => {
|
||||
beforeEach(() => {
|
||||
config.runtimeSurface = "portal";
|
||||
});
|
||||
|
||||
it("returns only minimal portal root data and no core session payload", async () => {
|
||||
const response = await loadPortalRootData(new Request("https://portal.hivegrid.de/acme", { headers: { "Accept-Language": "de-DE,de;q=0.9" } }));
|
||||
const data = await response.json();
|
||||
expect(isPortalRootData(data)).toBe(true);
|
||||
expect(data).toMatchObject({ runtimeSurface: "portal", customHost: false, locale: "de" });
|
||||
expect(data).not.toHaveProperty("userSession");
|
||||
expect(data).not.toHaveProperty("currentTenant");
|
||||
expect(data).not.toHaveProperty("appConfiguration");
|
||||
});
|
||||
|
||||
it("marks a custom-host document from the trusted outer routing context", async () => {
|
||||
const response = await loadPortalRootData(
|
||||
new Request("https://kunden.example.org/login", {
|
||||
headers: { "x-hivegrid-portal-custom-host": "kunden.example.org" },
|
||||
})
|
||||
);
|
||||
|
||||
await expect(response.json()).resolves.toMatchObject({ runtimeSurface: "portal", customHost: true });
|
||||
});
|
||||
|
||||
it("marks capability documents no-store and no-referrer at the root boundary", async () => {
|
||||
const response = await loadPortalRootData(
|
||||
new Request(`https://portal.hivegrid.de/acme/reset-password/${"t".repeat(43)}`, { headers: { "Accept-Language": "de" } })
|
||||
);
|
||||
|
||||
expect(response.headers.get("Cache-Control")).toBe("no-store");
|
||||
expect(response.headers.get("Referrer-Policy")).toBe("no-referrer");
|
||||
});
|
||||
|
||||
it("rejects core-only root actions with an opaque 404", async () => {
|
||||
const issued = await loadPortalRootData(new Request("https://portal.hivegrid.de/acme"));
|
||||
const data = await issued.json();
|
||||
const cookie = issued.headers.get("Set-Cookie")!.split(";", 1)[0]!;
|
||||
const form = new URLSearchParams({ csrf: data.csrf, action: "setTheme" });
|
||||
await expect(
|
||||
handlePortalRootAction(new Request("https://portal.hivegrid.de/acme", { method: "POST", headers: { Cookie: cookie }, body: form }))
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("persists locale through the portal-signed locale cookie", async () => {
|
||||
const issued = await loadPortalRootData(new Request("https://portal.hivegrid.de/acme"));
|
||||
const data = await issued.json();
|
||||
const cookie = issued.headers.get("Set-Cookie")!.split(";", 1)[0]!;
|
||||
const form = new URLSearchParams({ csrf: data.csrf, action: "setLocale", lng: "en" });
|
||||
const response = await handlePortalRootAction(new Request("https://portal.hivegrid.de/acme", { method: "POST", headers: { Cookie: cookie }, body: form }));
|
||||
expect(response.headers.get("Set-Cookie")).toContain("__Host-hivegrid_portal_locale=");
|
||||
});
|
||||
|
||||
it("ignores a disabled Accept-Language locale", async () => {
|
||||
const response = await loadPortalRootData(
|
||||
new Request("https://portal.hivegrid.de/acme", { headers: { "Accept-Language": "pl-PL,pl;q=0.9" } })
|
||||
);
|
||||
|
||||
await expect(response.json()).resolves.toMatchObject({ locale: "de", enabledLocales: ["de", "en"] });
|
||||
});
|
||||
|
||||
it("rejects a disabled locale action with an opaque 404", async () => {
|
||||
const issued = await loadPortalRootData(new Request("https://portal.hivegrid.de/acme"));
|
||||
const data = await issued.json();
|
||||
const cookie = issued.headers.get("Set-Cookie")!.split(";", 1)[0]!;
|
||||
const form = new URLSearchParams({ csrf: data.csrf, action: "setLocale", lng: "pl" });
|
||||
|
||||
await expect(
|
||||
handlePortalRootAction(new Request("https://portal.hivegrid.de/acme", { method: "POST", headers: { Cookie: cookie }, body: form }))
|
||||
).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { isSupportedLocale, resolveEnabledLocale, type SupportedLocale } from "~/locale/i18n";
|
||||
import { enabledLocales, getTranslations, i18nCookie } from "~/locale/i18next.server";
|
||||
import { CSP_NONCE_REQUEST_HEADER, buildDocumentContentSecurityPolicy, getRequestCspNonce } from "~/utils/security/contentSecurityPolicy";
|
||||
import { getRequestDocumentContentSecurityPolicyOptions } from "~/utils/security/requestContentSecurityPolicy.server";
|
||||
import { getPortalCapabilityResponseSecurityHeaders } from "./portal-response-security";
|
||||
|
||||
import { getPortalCsrfToken, validatePortalCsrfToken } from "./portal-csrf.server";
|
||||
import type { PortalRootData } from "./portal-root";
|
||||
|
||||
const browserBuildEnv = ((import.meta as unknown as { env?: Record<string, string | undefined> }).env ?? {}) as Record<string, string | undefined>;
|
||||
|
||||
export function isPortalRuntimeSurface(env: Readonly<{ WEB_RUNTIME_SURFACE?: string }> = process.env): boolean {
|
||||
return env.WEB_RUNTIME_SURFACE === "portal";
|
||||
}
|
||||
|
||||
export async function loadPortalRootData(request: Request): Promise<Response> {
|
||||
const config = loadRequiredWebConfig();
|
||||
if (config.runtimeSurface !== "portal") {
|
||||
throw new Response(null, { status: 404 });
|
||||
}
|
||||
|
||||
const locale = await resolvePortalLocale(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const csrf = await getPortalCsrfToken(request);
|
||||
const cspNonce = getRequestCspNonce(request);
|
||||
const headers = new Headers({ "Cache-Control": "no-store" });
|
||||
const capabilityHeaders = getPortalCapabilityResponseSecurityHeaders(request, "portal");
|
||||
if (capabilityHeaders) {
|
||||
for (const [key, value] of Object.entries(capabilityHeaders)) headers.set(key, value);
|
||||
}
|
||||
if (csrf.setCookie) headers.append("Set-Cookie", csrf.setCookie);
|
||||
if (cspNonce) {
|
||||
headers.set(CSP_NONCE_REQUEST_HEADER, cspNonce);
|
||||
headers.set(
|
||||
"Content-Security-Policy",
|
||||
buildDocumentContentSecurityPolicy(cspNonce, undefined, getRequestDocumentContentSecurityPolicyOptions(request, config, process.env, browserBuildEnv))
|
||||
);
|
||||
}
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
runtimeSurface: "portal",
|
||||
customHost: Boolean(request.headers.get("x-hivegrid-portal-custom-host")?.trim()),
|
||||
metatags: [{ title: `${t("customerPortal.admin.title")} | ${config.appName}` }],
|
||||
locale,
|
||||
enabledLocales,
|
||||
csrf: csrf.token,
|
||||
cspNonce,
|
||||
} satisfies PortalRootData,
|
||||
{ headers }
|
||||
);
|
||||
}
|
||||
|
||||
export async function handlePortalRootAction(request: Request): Promise<Response> {
|
||||
const form = await request.clone().formData();
|
||||
await validatePortalCsrfToken(request, form);
|
||||
if (form.get("action") !== "setLocale") {
|
||||
throw new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
const locale = form.get("lng")?.toString();
|
||||
if (!isSupportedLocale(locale) || !enabledLocales.includes(locale)) {
|
||||
throw new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
return Response.json({ ok: true }, { headers: { "Cache-Control": "no-store", "Set-Cookie": await i18nCookie.serialize(locale) } });
|
||||
}
|
||||
|
||||
export async function resolvePortalLocale(request: Request): Promise<SupportedLocale> {
|
||||
const cookieLocale = await i18nCookie.parse(request.headers.get("Cookie"));
|
||||
return resolveEnabledLocale({
|
||||
enabledLocales,
|
||||
cookieLocale: typeof cookieLocale === "string" ? cookieLocale : undefined,
|
||||
acceptLanguage: request.headers.get("Accept-Language"),
|
||||
});
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import type { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
|
||||
import type { SupportedLocale } from "@hivegrid/i18n";
|
||||
|
||||
export type PortalRootData = {
|
||||
readonly runtimeSurface: "portal";
|
||||
readonly customHost: boolean;
|
||||
readonly metatags: MetaTagsDto;
|
||||
readonly locale: string;
|
||||
readonly enabledLocales: readonly SupportedLocale[];
|
||||
readonly csrf: string;
|
||||
readonly cspNonce?: string;
|
||||
};
|
||||
|
||||
export function isPortalRootData(data: unknown): data is PortalRootData {
|
||||
return Boolean(data && typeof data === "object" && (data as { runtimeSurface?: unknown }).runtimeSurface === "portal");
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolvePortalRouteDispatch } from "./portal-route-dispatch";
|
||||
|
||||
describe("customer portal public route dispatch", () => {
|
||||
it.each([
|
||||
["/projects", false, "dashboard", { tenant: "projects" }],
|
||||
["/projects.data", false, "dashboard", { tenant: "projects" }],
|
||||
["/projects/projects", false, "projects", { tenant: "projects" }],
|
||||
["/projects/login", false, "auth", { tenant: "projects", "*": "login" }],
|
||||
["/projects", true, "projects", {}],
|
||||
["/projects/project_12345678", true, "project-detail", { projectId: "project_12345678" }],
|
||||
["/settings.data", true, "settings", {}],
|
||||
["/setup/token", true, "auth", { "*": "setup/token" }],
|
||||
] as const)("resolves %s (custom=%s) to %s", (pathname, customHost, target, params) => {
|
||||
expect(resolvePortalRouteDispatch(pathname, customHost)).toEqual({ target, params });
|
||||
});
|
||||
|
||||
it.each(["", "relative", "//attacker.example/login", "/projects//project_12345678", "/%E0%A4%A"])("rejects malformed path %j", (pathname) => {
|
||||
expect(resolvePortalRouteDispatch(pathname, true)).toBeNull();
|
||||
});
|
||||
});
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
export type PortalRouteTarget =
|
||||
| "auth"
|
||||
| "dashboard"
|
||||
| "document-download"
|
||||
| "export-download"
|
||||
| "logout"
|
||||
| "project-complaint"
|
||||
| "project-detail"
|
||||
| "project-upload"
|
||||
| "projects"
|
||||
| "settings"
|
||||
| "upload";
|
||||
|
||||
export type PortalRouteDispatch = {
|
||||
readonly target: PortalRouteTarget;
|
||||
readonly params: Readonly<Record<string, string | undefined>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolves the public portal URL independently from React Router's static
|
||||
* ranking. The same static alias can represent a slugless custom-host route
|
||||
* or the dashboard/auth path of a standard-host tenant with a colliding slug.
|
||||
* The outer host boundary supplies the trusted custom-host discriminator; the
|
||||
* delegated route loader still validates the injected tenant/origin context.
|
||||
*/
|
||||
export function resolvePortalRouteDispatch(pathname: string, customHost: boolean): PortalRouteDispatch | null {
|
||||
const segments = normalizedSegments(pathname);
|
||||
if (!segments) return null;
|
||||
|
||||
const tenant = customHost ? undefined : segments[0];
|
||||
if (!customHost && !tenant) return null;
|
||||
const relative = customHost ? segments : segments.slice(1);
|
||||
const baseParams = tenant ? { tenant } : {};
|
||||
|
||||
if (relative.length === 0) return { target: "dashboard", params: baseParams };
|
||||
if (relative.length === 1 && relative[0] === "projects") return { target: "projects", params: baseParams };
|
||||
if (relative.length === 1 && relative[0] === "upload") return { target: "upload", params: baseParams };
|
||||
if (relative.length === 1 && relative[0] === "settings") return { target: "settings", params: baseParams };
|
||||
if (relative.length === 1 && relative[0] === "logout") return { target: "logout", params: baseParams };
|
||||
if (relative.length === 2 && relative[0] === "exports") {
|
||||
return { target: "export-download", params: { ...baseParams, exportId: relative[1] } };
|
||||
}
|
||||
if (relative.length === 2 && relative[0] === "documents") {
|
||||
return { target: "document-download", params: { ...baseParams, releaseId: relative[1] } };
|
||||
}
|
||||
if (relative.length === 2 && relative[0] === "projects") {
|
||||
return { target: "project-detail", params: { ...baseParams, projectId: relative[1] } };
|
||||
}
|
||||
if (relative.length === 3 && relative[0] === "projects" && relative[2] === "upload") {
|
||||
return { target: "project-upload", params: { ...baseParams, projectId: relative[1] } };
|
||||
}
|
||||
if (relative.length === 4 && relative[0] === "projects" && relative[2] === "complaints") {
|
||||
return {
|
||||
target: "project-complaint",
|
||||
params: { ...baseParams, projectId: relative[1], formId: relative[3] },
|
||||
};
|
||||
}
|
||||
|
||||
return { target: "auth", params: { ...baseParams, "*": relative.join("/") } };
|
||||
}
|
||||
|
||||
function normalizedSegments(pathname: string): string[] | null {
|
||||
if (!pathname.startsWith("/") || pathname.startsWith("//")) return null;
|
||||
const withoutDataSuffix = pathname.replace(/\.data$/u, "");
|
||||
const rawSegments = withoutDataSuffix.split("/").slice(1);
|
||||
if (rawSegments.at(-1) === "") rawSegments.pop();
|
||||
if (rawSegments.some((segment) => !segment)) return null;
|
||||
try {
|
||||
return rawSegments.map((segment) => decodeURIComponent(segment));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
PORTAL_SERVICE_INBOX_BUNDLE_MS,
|
||||
PORTAL_SERVICE_INBOX_RETENTION_MS,
|
||||
buildPortalServiceInboxSourceKey,
|
||||
portalServiceInboxPriority,
|
||||
recordPortalServiceEventWithClient,
|
||||
} from "./portal-service-inbox.server";
|
||||
|
||||
function client() {
|
||||
return {
|
||||
portalActivityRoutingRule: { findFirst: vi.fn().mockResolvedValue(null) },
|
||||
portalServiceInboxItem: {
|
||||
upsert: vi.fn().mockImplementation(async ({ create }: { create: unknown }) => ({ id: "inbox-1", ...(create as object) })),
|
||||
findMany: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("portal service inbox", () => {
|
||||
it("enforces the complaint > upload > login > download priority contract", () => {
|
||||
expect(["complaint", "upload", "login", "download"].map((kind) => portalServiceInboxPriority(kind as never))).toEqual([400, 300, 200, 100]);
|
||||
});
|
||||
|
||||
it("bundles the same actor/project/kind for exactly thirty-minute windows", () => {
|
||||
const input = { tenantId: "tenant-1", portalId: "portal-1", portalUserId: "user-1", projectId: "project-1", kind: "upload" as const };
|
||||
const start = new Date("2026-07-16T12:00:00.000Z");
|
||||
expect(buildPortalServiceInboxSourceKey(input, start)).toBe(buildPortalServiceInboxSourceKey(input, new Date(start.getTime() + PORTAL_SERVICE_INBOX_BUNDLE_MS - 1)));
|
||||
expect(buildPortalServiceInboxSourceKey(input, start)).not.toBe(
|
||||
buildPortalServiceInboxSourceKey(input, new Date(start.getTime() + PORTAL_SERVICE_INBOX_BUNDLE_MS))
|
||||
);
|
||||
});
|
||||
|
||||
it("persists seven-day expiry, priority, routing, and idempotent bundle increment", async () => {
|
||||
const db = client();
|
||||
db.portalActivityRoutingRule.findFirst.mockResolvedValueOnce({ id: "rule-1", targetKind: "user", targetUserId: "owner-1" });
|
||||
const occurredAt = new Date("2026-07-16T12:00:00.000Z");
|
||||
await recordPortalServiceEventWithClient(db as never, {
|
||||
tenantId: "tenant-1",
|
||||
portalId: "portal-1",
|
||||
portalUserId: "user-1",
|
||||
projectId: "project-1",
|
||||
kind: "complaint",
|
||||
sourceId: "complaint-1",
|
||||
metadata: { subject: "Heizung" },
|
||||
occurredAt,
|
||||
});
|
||||
|
||||
expect(db.portalActivityRoutingRule.findFirst).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ orderBy: [{ priority: "desc" }, { id: "asc" }] }),
|
||||
);
|
||||
|
||||
expect(db.portalServiceInboxItem.upsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
create: expect.objectContaining({
|
||||
priority: 400,
|
||||
titleKey: "customerPortal.inbox.items.complaint",
|
||||
ownerUserId: "owner-1",
|
||||
routingRuleId: "rule-1",
|
||||
expiresAt: new Date(occurredAt.getTime() + PORTAL_SERVICE_INBOX_RETENTION_MS),
|
||||
}),
|
||||
update: expect.objectContaining({ bundledCount: { increment: 1 }, lastOccurredAt: occurredAt }),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import type { Prisma } from "@hivegrid/db/prisma-browser";
|
||||
|
||||
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
||||
|
||||
export type PortalServiceEventKind = "complaint" | "upload" | "login" | "download";
|
||||
export type PortalServiceInboxStatus = "open" | "in_progress" | "resolved" | "dismissed";
|
||||
|
||||
export const PORTAL_SERVICE_INBOX_RETENTION_MS = 7 * 24 * 60 * 60 * 1_000;
|
||||
export const PORTAL_SERVICE_INBOX_BUNDLE_MS = 30 * 60 * 1_000;
|
||||
|
||||
const PRIORITY_BY_KIND: Readonly<Record<PortalServiceEventKind, number>> = {
|
||||
complaint: 400,
|
||||
upload: 300,
|
||||
login: 200,
|
||||
download: 100,
|
||||
};
|
||||
|
||||
const TITLE_KEY_BY_KIND: Readonly<Record<PortalServiceEventKind, string>> = {
|
||||
complaint: "customerPortal.inbox.items.complaint",
|
||||
upload: "customerPortal.inbox.items.upload",
|
||||
login: "customerPortal.inbox.items.login",
|
||||
download: "customerPortal.inbox.items.download",
|
||||
};
|
||||
|
||||
export type PortalInboxClient = {
|
||||
portalActivityRoutingRule: {
|
||||
findFirst(args: unknown): Promise<{ id: string; targetKind: "user" | "role"; targetUserId: string | null } | null>;
|
||||
};
|
||||
portalServiceInboxItem: {
|
||||
upsert(args: unknown): Promise<PortalServiceInboxRow>;
|
||||
findMany(args: unknown): Promise<PortalServiceInboxRow[]>;
|
||||
updateMany(args: unknown): Promise<{ count: number }>;
|
||||
};
|
||||
};
|
||||
|
||||
export type PortalServiceInboxRow = {
|
||||
readonly id: string;
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
readonly portalUserId: string;
|
||||
readonly projectId: string | null;
|
||||
readonly kind: PortalServiceEventKind;
|
||||
readonly status: PortalServiceInboxStatus;
|
||||
readonly priority: number;
|
||||
readonly titleKey: string;
|
||||
readonly sourceKey: string;
|
||||
readonly sourceId: string | null;
|
||||
readonly metadata: unknown;
|
||||
readonly occurredAt: Date;
|
||||
readonly lastOccurredAt: Date;
|
||||
readonly bundledCount: number;
|
||||
readonly expiresAt: Date;
|
||||
readonly ownerUserId: string | null;
|
||||
readonly routingRuleId: string | null;
|
||||
};
|
||||
|
||||
export type RecordPortalServiceEventInput = {
|
||||
readonly tenantId: string;
|
||||
readonly portalId: string;
|
||||
readonly portalUserId: string;
|
||||
readonly projectId?: string | null;
|
||||
readonly kind: PortalServiceEventKind;
|
||||
readonly sourceId?: string | null;
|
||||
readonly metadata?: Readonly<Record<string, string | number | boolean | null>>;
|
||||
readonly occurredAt?: Date;
|
||||
};
|
||||
|
||||
export async function recordPortalServiceEvent(input: RecordPortalServiceEventInput): Promise<PortalServiceInboxRow> {
|
||||
return withTenantRLS(input.tenantId, (tx) => recordPortalServiceEventWithClient(tx as unknown as PortalInboxClient, input));
|
||||
}
|
||||
|
||||
export async function recordPortalServiceEventWithClient(
|
||||
client: PortalInboxClient,
|
||||
input: RecordPortalServiceEventInput
|
||||
): Promise<PortalServiceInboxRow> {
|
||||
requireIdentifier(input.tenantId);
|
||||
requireIdentifier(input.portalId);
|
||||
requireIdentifier(input.portalUserId);
|
||||
const occurredAt = input.occurredAt ?? new Date();
|
||||
if (!Number.isFinite(occurredAt.getTime())) throw new Error("customerPortal.inbox.errors.invalidTimestamp");
|
||||
|
||||
const routingRule = await client.portalActivityRoutingRule.findFirst({
|
||||
where: { tenantId: input.tenantId, portalId: input.portalId, activityType: input.kind, enabled: true },
|
||||
select: { id: true, targetKind: true, targetUserId: true },
|
||||
orderBy: [{ priority: "desc" }, { id: "asc" }],
|
||||
});
|
||||
const sourceKey = buildPortalServiceInboxSourceKey(input, occurredAt);
|
||||
const expiresAt = new Date(occurredAt.getTime() + PORTAL_SERVICE_INBOX_RETENTION_MS);
|
||||
const ownerUserId = routingRule?.targetKind === "user" ? routingRule.targetUserId : null;
|
||||
|
||||
return client.portalServiceInboxItem.upsert({
|
||||
where: { tenantId_sourceKey: { tenantId: input.tenantId, sourceKey } },
|
||||
create: {
|
||||
tenantId: input.tenantId,
|
||||
portalId: input.portalId,
|
||||
portalUserId: input.portalUserId,
|
||||
projectId: input.projectId ?? null,
|
||||
kind: input.kind,
|
||||
status: "open",
|
||||
priority: PRIORITY_BY_KIND[input.kind],
|
||||
sourceKey,
|
||||
sourceId: input.sourceId ?? null,
|
||||
titleKey: TITLE_KEY_BY_KIND[input.kind],
|
||||
metadata: (input.metadata ?? {}) as Prisma.InputJsonValue,
|
||||
occurredAt,
|
||||
lastOccurredAt: occurredAt,
|
||||
expiresAt,
|
||||
ownerUserId,
|
||||
routingRuleId: routingRule?.id ?? null,
|
||||
},
|
||||
update: {
|
||||
lastOccurredAt: occurredAt,
|
||||
expiresAt,
|
||||
sourceId: input.sourceId ?? undefined,
|
||||
metadata: (input.metadata ?? {}) as Prisma.InputJsonValue,
|
||||
bundledCount: { increment: 1 },
|
||||
ownerUserId,
|
||||
routingRuleId: routingRule?.id ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadPortalServiceInbox(tenantId: string, now = new Date()): Promise<PortalServiceInboxRow[]> {
|
||||
requireIdentifier(tenantId);
|
||||
return withTenantRLS(tenantId, (tx) =>
|
||||
(tx as unknown as PortalInboxClient).portalServiceInboxItem.findMany({
|
||||
where: { tenantId, expiresAt: { gt: now }, status: { in: ["open", "in_progress"] } },
|
||||
orderBy: [{ priority: "desc" }, { lastOccurredAt: "desc" }, { id: "asc" }],
|
||||
take: 250,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
export async function updatePortalServiceInboxItem(input: {
|
||||
readonly tenantId: string;
|
||||
readonly itemId: string;
|
||||
readonly status: PortalServiceInboxStatus;
|
||||
readonly ownerUserId?: string | null;
|
||||
}): Promise<void> {
|
||||
requireIdentifier(input.tenantId);
|
||||
requireIdentifier(input.itemId);
|
||||
await withTenantRLS(input.tenantId, (tx) => updatePortalServiceInboxItemWithClient(tx as unknown as PortalInboxClient, input));
|
||||
}
|
||||
|
||||
export async function updatePortalServiceInboxItemWithClient(
|
||||
client: PortalInboxClient,
|
||||
input: {
|
||||
readonly tenantId: string;
|
||||
readonly itemId: string;
|
||||
readonly status: PortalServiceInboxStatus;
|
||||
readonly ownerUserId?: string | null;
|
||||
},
|
||||
now = new Date(),
|
||||
): Promise<void> {
|
||||
requireIdentifier(input.tenantId);
|
||||
requireIdentifier(input.itemId);
|
||||
const count = await client.portalServiceInboxItem.updateMany({
|
||||
where: { id: input.itemId, tenantId: input.tenantId, expiresAt: { gt: now } },
|
||||
data: {
|
||||
status: input.status,
|
||||
ownerUserId: input.ownerUserId,
|
||||
resolvedAt: input.status === "resolved" || input.status === "dismissed" ? now : null,
|
||||
},
|
||||
});
|
||||
if (count.count !== 1) throw new Response(null, { status: 404, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
export function buildPortalServiceInboxSourceKey(input: RecordPortalServiceEventInput, occurredAt: Date): string {
|
||||
const bucket = Math.floor(occurredAt.getTime() / PORTAL_SERVICE_INBOX_BUNDLE_MS);
|
||||
return ["portal", input.kind, input.portalUserId, input.projectId ?? "none", bucket].join(":");
|
||||
}
|
||||
|
||||
export function portalServiceInboxPriority(kind: PortalServiceEventKind): number {
|
||||
return PRIORITY_BY_KIND[kind];
|
||||
}
|
||||
|
||||
function requireIdentifier(value: string): void {
|
||||
if (!value.trim() || value.length > 191) throw new Error("customerPortal.inbox.errors.invalidScope");
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const config = vi.hoisted(() => ({
|
||||
runtimeSurface: "portal" as "core" | "portal",
|
||||
portalSessionSecret: "portal-session-secret-with-at-least-32-bytes" as string | undefined,
|
||||
nodeEnv: "production",
|
||||
}));
|
||||
|
||||
vi.mock("@hivegrid/config", () => ({ loadRequiredWebConfig: () => config }));
|
||||
|
||||
import { clearPortalSessionCookie, PORTAL_SESSION_COOKIE_NAME, readPortalSessionCookie, serializePortalSessionCookie } from "./portal-session-cookie.server";
|
||||
|
||||
describe("portal session cookie", () => {
|
||||
beforeEach(() => {
|
||||
config.runtimeSurface = "portal";
|
||||
config.portalSessionSecret = "portal-session-secret-with-at-least-32-bytes";
|
||||
config.nodeEnv = "production";
|
||||
});
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it("uses only the dedicated signed host cookie", async () => {
|
||||
const header = await serializePortalSessionCookie("opaque-portal-session", new Date(Date.now() + 60_000));
|
||||
expect(header).toContain(`${PORTAL_SESSION_COOKIE_NAME}=`);
|
||||
expect(header).toContain("HttpOnly");
|
||||
expect(header).toContain("Secure");
|
||||
expect(header).toContain("SameSite=Lax");
|
||||
expect(header).toContain("Path=/");
|
||||
expect(header).not.toMatch(/Domain=/i);
|
||||
expect(header).not.toContain("hivegrid_app_session");
|
||||
expect(header).not.toContain("hivegrid_admin_session");
|
||||
|
||||
const request = new Request("https://portal.hivegrid.de/acme", { headers: { Cookie: header.split(";")[0] } });
|
||||
await expect(readPortalSessionCookie(request)).resolves.toBe("opaque-portal-session");
|
||||
});
|
||||
|
||||
it("does not read app or admin cookies", async () => {
|
||||
const request = new Request("https://portal.hivegrid.de/acme", {
|
||||
headers: { Cookie: "__Host-hivegrid_app_session=app; __Host-hivegrid_admin_session=admin" },
|
||||
});
|
||||
await expect(readPortalSessionCookie(request)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it("writes the sliding server expiry into the refreshed browser cookie", async () => {
|
||||
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);
|
||||
const header = await serializePortalSessionCookie("opaque-portal-session", expiresAt);
|
||||
expect(header).toContain(`Expires=${expiresAt.toUTCString()}`);
|
||||
});
|
||||
|
||||
it("fails closed outside the portal surface or without its own secret", async () => {
|
||||
config.runtimeSurface = "core";
|
||||
await expect(readPortalSessionCookie(new Request("https://app.hivegrid.de"))).rejects.toThrow(/portal runtime/);
|
||||
config.runtimeSurface = "portal";
|
||||
config.portalSessionSecret = undefined;
|
||||
await expect(readPortalSessionCookie(new Request("https://portal.hivegrid.de"))).rejects.toThrow(/portal runtime/);
|
||||
});
|
||||
|
||||
it("clears the same dedicated cookie", async () => {
|
||||
const header = await clearPortalSessionCookie();
|
||||
expect(header).toContain(`${PORTAL_SESSION_COOKIE_NAME}=`);
|
||||
expect(header).toContain("Max-Age=0");
|
||||
});
|
||||
});
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import { createCookie } from "react-router";
|
||||
|
||||
import { loadRequiredWebConfig } from "@hivegrid/config";
|
||||
|
||||
export const PORTAL_SESSION_COOKIE_NAME = "__Host-hivegrid_portal_session";
|
||||
|
||||
function portalSessionCookie() {
|
||||
const config = loadRequiredWebConfig();
|
||||
if (config.runtimeSurface !== "portal" || !config.portalSessionSecret) {
|
||||
throw new Error("Portal session cookie is available only in the portal runtime surface.");
|
||||
}
|
||||
return createCookie(PORTAL_SESSION_COOKIE_NAME, {
|
||||
httpOnly: true,
|
||||
path: "/",
|
||||
sameSite: "lax",
|
||||
// `__Host-` cookies are required to carry Secure in every environment.
|
||||
// Browsers treat localhost as a secure context, so the canonical local
|
||||
// portal host can keep the production cookie contract intact.
|
||||
secure: true,
|
||||
secrets: [config.portalSessionSecret],
|
||||
});
|
||||
}
|
||||
|
||||
export async function readPortalSessionCookie(request: Request): Promise<string | null> {
|
||||
const value = await portalSessionCookie().parse(request.headers.get("Cookie"));
|
||||
return typeof value === "string" && value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
export async function serializePortalSessionCookie(rawToken: string, expiresAt: Date): Promise<string> {
|
||||
if (!rawToken || expiresAt.getTime() <= Date.now()) throw new Error("Portal session cookie requires a live opaque token.");
|
||||
return portalSessionCookie().serialize(rawToken, { expires: expiresAt });
|
||||
}
|
||||
|
||||
export async function clearPortalSessionCookie(): Promise<string> {
|
||||
return portalSessionCookie().serialize("", { expires: new Date(0), maxAge: 0 });
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { uploadPortalFileBatch } from "./portal-upload-batch.client";
|
||||
|
||||
function response(status: number, body: unknown): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });
|
||||
}
|
||||
|
||||
describe("portal upload browser batch", () => {
|
||||
it("posts every selected file sequentially with a distinct stable file key", async () => {
|
||||
const inFlight: number[] = [];
|
||||
let active = 0;
|
||||
const fetchImpl = vi.fn(async (_action: string, _init: { body: FormData }) => {
|
||||
active += 1;
|
||||
inFlight.push(active);
|
||||
await Promise.resolve();
|
||||
active -= 1;
|
||||
return response(201, { ok: true, messageKey: "customerPortal.upload.success" });
|
||||
});
|
||||
const files = [new File(["one"], "one.pdf", { type: "application/pdf" }), new File(["two"], "two.pdf", { type: "application/pdf" })];
|
||||
|
||||
await expect(
|
||||
uploadPortalFileBatch({ action: "/acme/projects/project-1/upload", files, csrfToken: "csrf-1", batchId: "batch-1", fetchImpl }),
|
||||
).resolves.toEqual({ ok: true, messageKey: "customerPortal.upload.success" });
|
||||
|
||||
expect(inFlight).toEqual([1, 1]);
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
const firstForm = fetchImpl.mock.calls[0]?.[1].body;
|
||||
const secondForm = fetchImpl.mock.calls[1]?.[1].body;
|
||||
expect(firstForm.getAll("files")).toEqual([files[0]]);
|
||||
expect(secondForm.getAll("files")).toEqual([files[1]]);
|
||||
expect(firstForm.get("idempotencyKey")).toBe("batch-1-0");
|
||||
expect(secondForm.get("idempotencyKey")).toBe("batch-1-1");
|
||||
expect(firstForm.get("csrf")).toBe("csrf-1");
|
||||
});
|
||||
|
||||
it("retries a transient failure once with the exact same idempotency key", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response("upstream unavailable", { status: 503, headers: { "Content-Type": "text/plain" } }))
|
||||
.mockResolvedValueOnce(response(201, { ok: true, messageKey: "customerPortal.upload.success" }));
|
||||
const file = new File(["one"], "one.pdf", { type: "application/pdf" });
|
||||
|
||||
await expect(
|
||||
uploadPortalFileBatch({ action: "/acme/projects/project-1/upload", files: [file], batchId: "batch-retry", fetchImpl }),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl.mock.calls[0]?.[1].body.get("idempotencyKey")).toBe("batch-retry-0");
|
||||
expect(fetchImpl.mock.calls[1]?.[1].body.get("idempotencyKey")).toBe("batch-retry-0");
|
||||
});
|
||||
|
||||
it.each(["customerPortal.upload.errors.STORAGE_FAILED", "customerPortal.upload.errors.unavailable"])(
|
||||
"does not retry a structured 503 app error (%s)",
|
||||
async (errorKey) => {
|
||||
const fetchImpl = vi.fn(async () => response(503, { ok: false, errorKey }));
|
||||
const file = new File(["one"], "one.pdf", { type: "application/pdf" });
|
||||
|
||||
await expect(uploadPortalFileBatch({ action: "/upload", files: [file], batchId: "batch-app-error", fetchImpl })).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey,
|
||||
});
|
||||
expect(fetchImpl).toHaveBeenCalledOnce();
|
||||
},
|
||||
);
|
||||
|
||||
it("stops after a stable per-file error without starting later files", async () => {
|
||||
const fetchImpl = vi.fn(async () => response(413, { ok: false, errorKey: "customerPortal.upload.errors.fileTooLarge" }));
|
||||
const files = [new File(["one"], "one.pdf"), new File(["two"], "two.pdf")];
|
||||
|
||||
await expect(uploadPortalFileBatch({ action: "/upload", files, batchId: "batch-error", fetchImpl })).resolves.toEqual({
|
||||
ok: false,
|
||||
errorKey: "customerPortal.upload.errors.fileTooLarge",
|
||||
});
|
||||
expect(fetchImpl).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
export type PortalUploadActionResult = {
|
||||
readonly ok: boolean;
|
||||
readonly messageKey?: string;
|
||||
readonly errorKey?: string;
|
||||
};
|
||||
|
||||
type PortalUploadFetch = (
|
||||
input: string,
|
||||
init: {
|
||||
readonly method: "POST";
|
||||
readonly body: FormData;
|
||||
readonly credentials: "same-origin";
|
||||
readonly headers: Readonly<Record<string, string>>;
|
||||
},
|
||||
) => Promise<Response>;
|
||||
|
||||
export const PORTAL_UPLOAD_CLIENT_MAX_FILES = 10;
|
||||
const RETRYABLE_UPLOAD_STATUSES = new Set([502, 503, 504]);
|
||||
|
||||
type ParsedPortalUploadResponse = {
|
||||
readonly result: PortalUploadActionResult;
|
||||
readonly isStructuredAppResult: boolean;
|
||||
};
|
||||
|
||||
export function portalUploadSelectionSignature(files: readonly File[]): string {
|
||||
return files.map((file) => `${file.name}\u0000${file.type}\u0000${file.size}\u0000${file.lastModified}`).join("\u0001");
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads one file per request so the documented ten-file selection remains
|
||||
* usable without buffering up to one gibibyte in the portal web process. Each
|
||||
* file keeps the same idempotency key across the single transport retry.
|
||||
*/
|
||||
export async function uploadPortalFileBatch(input: {
|
||||
readonly action: string;
|
||||
readonly files: readonly File[];
|
||||
readonly csrfToken?: string | null;
|
||||
readonly batchId: string;
|
||||
readonly fetchImpl?: PortalUploadFetch;
|
||||
}): Promise<PortalUploadActionResult> {
|
||||
if (input.files.length === 0) return { ok: false, errorKey: "customerPortal.upload.errors.filesRequired" };
|
||||
if (input.files.length > PORTAL_UPLOAD_CLIENT_MAX_FILES) {
|
||||
return { ok: false, errorKey: "customerPortal.upload.errors.tooManyFiles" };
|
||||
}
|
||||
const fetchImpl = input.fetchImpl ?? fetch;
|
||||
let successMessageKey = "customerPortal.upload.success";
|
||||
|
||||
for (const [index, file] of input.files.entries()) {
|
||||
const idempotencyKey = `${input.batchId}-${index}`;
|
||||
const result = await uploadOnePortalFile({
|
||||
action: input.action,
|
||||
file,
|
||||
csrfToken: input.csrfToken,
|
||||
idempotencyKey,
|
||||
fetchImpl,
|
||||
});
|
||||
if (!result.ok) return result;
|
||||
successMessageKey = result.messageKey ?? successMessageKey;
|
||||
}
|
||||
|
||||
return { ok: true, messageKey: successMessageKey };
|
||||
}
|
||||
|
||||
async function uploadOnePortalFile(input: {
|
||||
readonly action: string;
|
||||
readonly file: File;
|
||||
readonly csrfToken?: string | null;
|
||||
readonly idempotencyKey: string;
|
||||
readonly fetchImpl: PortalUploadFetch;
|
||||
}): Promise<PortalUploadActionResult> {
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
try {
|
||||
const form = new FormData();
|
||||
if (input.csrfToken) form.set("csrf", input.csrfToken);
|
||||
form.set("idempotencyKey", input.idempotencyKey);
|
||||
form.set("files", input.file);
|
||||
const response = await input.fetchImpl(input.action, {
|
||||
method: "POST",
|
||||
body: form,
|
||||
credentials: "same-origin",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
const { result, isStructuredAppResult } = await readPortalUploadResponse(response);
|
||||
if (response.ok && result.ok) return result;
|
||||
if (attempt === 0 && !isStructuredAppResult && RETRYABLE_UPLOAD_STATUSES.has(response.status)) continue;
|
||||
return result.ok ? { ok: false, errorKey: "customerPortal.upload.errors.unavailable" } : result;
|
||||
} catch {
|
||||
if (attempt === 0) continue;
|
||||
return { ok: false, errorKey: "customerPortal.upload.errors.unavailable" };
|
||||
}
|
||||
}
|
||||
return { ok: false, errorKey: "customerPortal.upload.errors.unavailable" };
|
||||
}
|
||||
|
||||
async function readPortalUploadResponse(response: Response): Promise<ParsedPortalUploadResponse> {
|
||||
try {
|
||||
const value = (await response.json()) as Partial<PortalUploadActionResult>;
|
||||
if (value.ok === true) {
|
||||
return { result: { ok: true, messageKey: value.messageKey }, isStructuredAppResult: true };
|
||||
}
|
||||
if (value.ok === false && typeof value.errorKey === "string") {
|
||||
return { result: { ok: false, errorKey: value.errorKey }, isStructuredAppResult: true };
|
||||
}
|
||||
} catch {
|
||||
// The stable M002 fallback below deliberately hides transport/provider text.
|
||||
}
|
||||
return {
|
||||
result: { ok: false, errorKey: "customerPortal.upload.errors.unavailable" },
|
||||
isStructuredAppResult: false,
|
||||
};
|
||||
}
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
// @vitest-environment node
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
PORTAL_UPLOAD_ABSOLUTE_MAX_FILE_BYTES,
|
||||
PORTAL_UPLOAD_ACTIVITY_SUMMARY_KEY,
|
||||
PORTAL_UPLOAD_DEFAULT_MAX_FILE_BYTES,
|
||||
PortalUploadError,
|
||||
normalizePortalUploadLimits,
|
||||
storePortalUploadFile,
|
||||
uploadPortalFiles,
|
||||
validatePortalUploadFiles,
|
||||
type PortalUploadPersistence,
|
||||
} from "./portal-upload.server";
|
||||
|
||||
const identity = {
|
||||
tenantId: "tenant-1",
|
||||
portalId: "portal-1",
|
||||
portalUserId: "portal-user-1",
|
||||
portalSessionId: "session-1",
|
||||
tenantSlug: "acme",
|
||||
tenantFrozen: false,
|
||||
portalTitle: "Acme Portal",
|
||||
viewerFirstName: "Karla",
|
||||
viewerLastName: "Kunde",
|
||||
viewerLocale: "de",
|
||||
createdAt: new Date(),
|
||||
lastSeenAt: new Date(),
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
origin: "https://portal.hivegrid.de",
|
||||
} as const;
|
||||
|
||||
function file(name = "foto.jpg", mimeType = "image/jpeg", size = 10) {
|
||||
return { name, mimeType, bytes: new Uint8Array(size).fill(1) };
|
||||
}
|
||||
|
||||
function persistence(): PortalUploadPersistence & Record<string, ReturnType<typeof vi.fn>> {
|
||||
return {
|
||||
reserve: vi.fn().mockResolvedValue({
|
||||
uploadId: "upload-1",
|
||||
fileUploadId: "file-upload-1",
|
||||
fileId: "file-1",
|
||||
fileEntityLinkId: "link-1",
|
||||
projectLeaderUserId: "leader-1",
|
||||
alreadyCompleted: false,
|
||||
effectsCompleted: false,
|
||||
}),
|
||||
complete: vi.fn().mockResolvedValue(undefined),
|
||||
fail: vi.fn().mockResolvedValue(true),
|
||||
appendActivity: vi.fn().mockResolvedValue(undefined),
|
||||
notifyProjectLeader: vi.fn().mockResolvedValue(undefined),
|
||||
recordInbox: vi.fn().mockResolvedValue(undefined),
|
||||
markEffectsCompleted: vi.fn().mockResolvedValue(undefined),
|
||||
store: vi.fn().mockResolvedValue("tenants/tenant-1/files/file-1/original"),
|
||||
removeStored: vi.fn().mockResolvedValue(undefined),
|
||||
} as never;
|
||||
}
|
||||
|
||||
describe("portal upload", () => {
|
||||
it("uses a locale-independent activity summary key", () => {
|
||||
expect(PORTAL_UPLOAD_ACTIVITY_SUMMARY_KEY).toBe("activity.runtime.customerPortal.fileUploaded");
|
||||
});
|
||||
|
||||
it("persists private objects by canonical key even when storage has no public URL", async () => {
|
||||
const storeFileBytes = vi.fn().mockResolvedValue("");
|
||||
const upload = file("portal-photo.png", "image/png");
|
||||
await expect(
|
||||
storePortalUploadFile(
|
||||
{ identity, fileId: "file-1", file: upload },
|
||||
{ resolveStorageBucket: () => "uploads", storeFileBytes },
|
||||
),
|
||||
).resolves.toBe("tenants/tenant-1/files/file-1/original");
|
||||
expect(storeFileBytes).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
bucket: "uploads",
|
||||
body: upload.bytes,
|
||||
contentType: "image/png",
|
||||
id: "tenants/tenant-1/files/file-1/original",
|
||||
scan: expect.objectContaining({ requireMalwareScan: true }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("enforces ten files, 50 MB default, 100 MB absolute and the required media families", () => {
|
||||
const limits = normalizePortalUploadLimits();
|
||||
expect(limits).toMatchObject({ maxFiles: 10, maxFileBytes: PORTAL_UPLOAD_DEFAULT_MAX_FILE_BYTES });
|
||||
expect(() => normalizePortalUploadLimits({ maxFileBytes: PORTAL_UPLOAD_ABSOLUTE_MAX_FILE_BYTES + 1 })).toThrow(
|
||||
expect.objectContaining<Partial<PortalUploadError>>({ code: "FILE_TOO_LARGE" })
|
||||
);
|
||||
expect(() => validatePortalUploadFiles([], limits)).toThrow(expect.objectContaining({ code: "FILES_REQUIRED" }));
|
||||
expect(() => validatePortalUploadFiles(Array.from({ length: 11 }, () => file()), limits)).toThrow(
|
||||
expect.objectContaining({ code: "TOO_MANY_FILES" })
|
||||
);
|
||||
for (const mime of [
|
||||
"image/jpeg",
|
||||
"application/pdf",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"audio/mpeg",
|
||||
]) {
|
||||
expect(validatePortalUploadFiles([file("upload.bin", mime)], limits)).toHaveLength(1);
|
||||
}
|
||||
expect(() => validatePortalUploadFiles([file("script.html", "text/html")], limits)).toThrow(
|
||||
expect.objectContaining({ code: "FILE_TYPE_BLOCKED" })
|
||||
);
|
||||
});
|
||||
|
||||
it("reserves quota before storage and emits activity, inbox, and notify only after clean completion", async () => {
|
||||
const adapter = persistence();
|
||||
const result = await uploadPortalFiles({
|
||||
identity,
|
||||
projectId: "project-1",
|
||||
files: [file()],
|
||||
idempotencyKey: "request-1",
|
||||
persistence: adapter,
|
||||
});
|
||||
expect(result).toEqual([{ uploadId: "upload-1", fileId: "file-1", name: "foto.jpg", sizeBytes: 10 }]);
|
||||
expect(adapter.reserve).toHaveBeenCalledBefore(adapter.store);
|
||||
expect(adapter.store).toHaveBeenCalledBefore(adapter.complete);
|
||||
expect(adapter.complete).toHaveBeenCalledBefore(adapter.appendActivity);
|
||||
expect(adapter.appendActivity).toHaveBeenCalledOnce();
|
||||
expect(adapter.recordInbox).toHaveBeenCalledOnce();
|
||||
expect(adapter.notifyProjectLeader).toHaveBeenCalledOnce();
|
||||
expect(adapter.markEffectsCompleted).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("fails closed and removes stored bytes without publishing success effects", async () => {
|
||||
const adapter = persistence();
|
||||
adapter.complete.mockRejectedValueOnce(new Error("database unavailable"));
|
||||
await expect(
|
||||
uploadPortalFiles({ identity, projectId: "project-1", files: [file()], idempotencyKey: "request-1", persistence: adapter })
|
||||
).rejects.toMatchObject({ code: "STORAGE_FAILED" });
|
||||
expect(adapter.removeStored).toHaveBeenCalledWith({ storageKey: "tenants/tenant-1/files/file-1/original" });
|
||||
expect(adapter.fail).toHaveBeenCalledOnce();
|
||||
expect(adapter.appendActivity).not.toHaveBeenCalled();
|
||||
expect(adapter.notifyProjectLeader).not.toHaveBeenCalled();
|
||||
expect(adapter.recordInbox).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a fully completed retry without replacing storage or repeating effects", async () => {
|
||||
const adapter = persistence();
|
||||
adapter.reserve.mockResolvedValueOnce({
|
||||
uploadId: "upload-1",
|
||||
fileUploadId: "file-upload-1",
|
||||
fileId: "file-1",
|
||||
fileEntityLinkId: "link-1",
|
||||
projectLeaderUserId: "leader-1",
|
||||
alreadyCompleted: true,
|
||||
effectsCompleted: true,
|
||||
});
|
||||
|
||||
await expect(
|
||||
uploadPortalFiles({ identity, projectId: "project-1", files: [file()], idempotencyKey: "request-1", persistence: adapter }),
|
||||
).resolves.toEqual([{ uploadId: "upload-1", fileId: "file-1", name: "foto.jpg", sizeBytes: 10 }]);
|
||||
expect(adapter.store).not.toHaveBeenCalled();
|
||||
expect(adapter.complete).not.toHaveBeenCalled();
|
||||
expect(adapter.fail).not.toHaveBeenCalled();
|
||||
expect(adapter.appendActivity).not.toHaveBeenCalled();
|
||||
expect(adapter.recordInbox).not.toHaveBeenCalled();
|
||||
expect(adapter.notifyProjectLeader).not.toHaveBeenCalled();
|
||||
expect(adapter.markEffectsCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("replays only idempotent effects when storage is clean but effect completion is pending", async () => {
|
||||
const adapter = persistence();
|
||||
adapter.reserve.mockResolvedValueOnce({
|
||||
uploadId: "upload-1",
|
||||
fileUploadId: "file-upload-1",
|
||||
fileId: "file-1",
|
||||
fileEntityLinkId: "link-1",
|
||||
projectLeaderUserId: "leader-1",
|
||||
alreadyCompleted: true,
|
||||
effectsCompleted: false,
|
||||
});
|
||||
|
||||
await expect(
|
||||
uploadPortalFiles({ identity, projectId: "project-1", files: [file()], idempotencyKey: "request-1", persistence: adapter }),
|
||||
).resolves.toHaveLength(1);
|
||||
expect(adapter.store).not.toHaveBeenCalled();
|
||||
expect(adapter.complete).not.toHaveBeenCalled();
|
||||
expect(adapter.appendActivity).toHaveBeenCalledOnce();
|
||||
expect(adapter.recordInbox).toHaveBeenCalledOnce();
|
||||
expect(adapter.notifyProjectLeader).toHaveBeenCalledOnce();
|
||||
expect(adapter.markEffectsCompleted).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("keeps a clean file intact when an auxiliary effect fails so a retry can repair it", async () => {
|
||||
const adapter = persistence();
|
||||
adapter.recordInbox.mockRejectedValueOnce(new Error("inbox unavailable"));
|
||||
|
||||
await expect(
|
||||
uploadPortalFiles({ identity, projectId: "project-1", files: [file()], idempotencyKey: "request-1", persistence: adapter }),
|
||||
).rejects.toMatchObject({ code: "STORAGE_FAILED" });
|
||||
expect(adapter.fail).not.toHaveBeenCalled();
|
||||
expect(adapter.removeStored).not.toHaveBeenCalled();
|
||||
expect(adapter.markEffectsCompleted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never deletes bytes when a completion acknowledgement may have committed clean", async () => {
|
||||
const adapter = persistence();
|
||||
adapter.complete.mockRejectedValueOnce(new Error("connection closed after commit"));
|
||||
adapter.fail.mockResolvedValueOnce(false);
|
||||
|
||||
await expect(
|
||||
uploadPortalFiles({ identity, projectId: "project-1", files: [file()], idempotencyKey: "request-1", persistence: adapter }),
|
||||
).rejects.toMatchObject({ code: "STORAGE_FAILED" });
|
||||
expect(adapter.removeStored).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps frozen portals read-only before reserving quota", async () => {
|
||||
const adapter = persistence();
|
||||
await expect(
|
||||
uploadPortalFiles({ identity: { ...identity, tenantFrozen: true }, projectId: "project-1", files: [file()], idempotencyKey: "request-1", persistence: adapter })
|
||||
).rejects.toMatchObject({ code: "PORTAL_FROZEN" });
|
||||
expect(adapter.reserve).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+411
@@ -0,0 +1,411 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
|
||||
import { logActivity, type ActivityWriteClient } from "@hivegrid/activity";
|
||||
import { getWriteDbClient, type DbClient } from "@hivegrid/db/client.server";
|
||||
import { runWithPortalRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { notify, type NotificationClient } from "@hivegrid/foundation";
|
||||
import { buildFileStorageKeys } from "@hivegrid/storage";
|
||||
|
||||
import { deleteFile, resolveStorageBucket, storeFileBytes } from "~/utils/integrations/storageService";
|
||||
import type { PortalSessionIdentity } from "./portal-data.server";
|
||||
|
||||
export const PORTAL_UPLOAD_DEFAULT_MAX_FILES = 10;
|
||||
export const PORTAL_UPLOAD_DEFAULT_MAX_FILE_BYTES = 50 * 1024 * 1024;
|
||||
export const PORTAL_UPLOAD_ABSOLUTE_MAX_FILE_BYTES = 100 * 1024 * 1024;
|
||||
export const PORTAL_UPLOAD_ABSOLUTE_REQUEST_BYTES = PORTAL_UPLOAD_ABSOLUTE_MAX_FILE_BYTES + 1024 * 1024;
|
||||
export const PORTAL_UPLOAD_ABSOLUTE_QUOTA_BYTES = 1024 * 1024 * 1024 * 1024 * 1024;
|
||||
export const PORTAL_UPLOAD_ACTIVITY_SUMMARY_KEY = "activity.runtime.customerPortal.fileUploaded";
|
||||
|
||||
export const PORTAL_UPLOAD_ALLOWED_MIME_TYPES = new Set([
|
||||
"image/png",
|
||||
"image/jpeg",
|
||||
"image/webp",
|
||||
"image/heic",
|
||||
"image/heif",
|
||||
"application/pdf",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
"audio/mpeg",
|
||||
"audio/wav",
|
||||
"audio/x-wav",
|
||||
"audio/ogg",
|
||||
"audio/mp4",
|
||||
"audio/aac",
|
||||
"audio/flac",
|
||||
]);
|
||||
|
||||
export type PortalUploadFile = {
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly bytes: Uint8Array;
|
||||
};
|
||||
|
||||
export type PortalUploadLimits = {
|
||||
readonly maxFiles: number;
|
||||
readonly maxFileBytes: number;
|
||||
readonly quotaBytes: number;
|
||||
};
|
||||
|
||||
export type PortalUploadResult = {
|
||||
readonly uploadId: string;
|
||||
readonly fileId: string;
|
||||
readonly name: string;
|
||||
readonly sizeBytes: number;
|
||||
};
|
||||
|
||||
export class PortalUploadError extends Error {
|
||||
override readonly name = "PortalUploadError";
|
||||
|
||||
constructor(
|
||||
readonly code:
|
||||
| "FILES_REQUIRED"
|
||||
| "TOO_MANY_FILES"
|
||||
| "FILE_EMPTY"
|
||||
| "FILE_TOO_LARGE"
|
||||
| "FILE_TYPE_BLOCKED"
|
||||
| "FILENAME_INVALID"
|
||||
| "PORTAL_FROZEN"
|
||||
| "PROJECT_ACCESS_DENIED"
|
||||
| "QUOTA_EXCEEDED"
|
||||
| "SCAN_REJECTED"
|
||||
| "STORAGE_FAILED"
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
type ReservedPortalUpload = {
|
||||
readonly uploadId: string;
|
||||
readonly fileUploadId: string;
|
||||
readonly fileId: string;
|
||||
readonly fileEntityLinkId: string;
|
||||
readonly projectLeaderUserId: string | null;
|
||||
readonly alreadyCompleted: boolean;
|
||||
readonly effectsCompleted: boolean;
|
||||
};
|
||||
|
||||
export type PortalUploadPersistence = {
|
||||
reserve(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly file: PortalUploadFile;
|
||||
readonly checksumSha256: string;
|
||||
readonly idempotencyKey: string;
|
||||
readonly quotaLimitBytes: number;
|
||||
}): Promise<ReservedPortalUpload>;
|
||||
complete(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly reserved: ReservedPortalUpload;
|
||||
readonly projectId: string;
|
||||
readonly file: PortalUploadFile;
|
||||
readonly storageKey: string;
|
||||
readonly checksumSha256: string;
|
||||
}): Promise<void>;
|
||||
fail(input: { readonly identity: PortalSessionIdentity; readonly uploadId: string; readonly failureCode: string }): Promise<boolean>;
|
||||
appendActivity(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly uploadId: string;
|
||||
readonly fileId: string;
|
||||
readonly filename: string;
|
||||
}): Promise<void>;
|
||||
notifyProjectLeader(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly uploadId: string;
|
||||
readonly projectLeaderUserId: string;
|
||||
}): Promise<void>;
|
||||
recordInbox(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly uploadId: string;
|
||||
readonly filename: string;
|
||||
}): Promise<void>;
|
||||
markEffectsCompleted(input: { readonly identity: PortalSessionIdentity; readonly uploadId: string }): Promise<void>;
|
||||
store(input: { readonly identity: PortalSessionIdentity; readonly fileId: string; readonly file: PortalUploadFile }): Promise<string>;
|
||||
removeStored(input: { readonly storageKey: string }): Promise<void>;
|
||||
};
|
||||
|
||||
type PortalUploadStorageDependencies = {
|
||||
readonly resolveStorageBucket: typeof resolveStorageBucket;
|
||||
readonly storeFileBytes: typeof storeFileBytes;
|
||||
};
|
||||
|
||||
const defaultPortalUploadStorageDependencies: PortalUploadStorageDependencies = {
|
||||
resolveStorageBucket,
|
||||
storeFileBytes,
|
||||
};
|
||||
|
||||
export async function storePortalUploadFile(
|
||||
input: {
|
||||
readonly identity: Pick<PortalSessionIdentity, "tenantId">;
|
||||
readonly fileId: string;
|
||||
readonly file: PortalUploadFile;
|
||||
},
|
||||
dependencies: PortalUploadStorageDependencies = defaultPortalUploadStorageDependencies,
|
||||
): Promise<string> {
|
||||
const bucket = dependencies.resolveStorageBucket();
|
||||
const key = buildFileStorageKeys(input.identity.tenantId, input.fileId).original;
|
||||
await dependencies.storeFileBytes({
|
||||
bucket,
|
||||
body: input.file.bytes,
|
||||
contentType: input.file.mimeType,
|
||||
id: key,
|
||||
scan: {
|
||||
context: "formUpload",
|
||||
declaredMimeType: input.file.mimeType,
|
||||
filename: input.file.name,
|
||||
tenantId: input.identity.tenantId,
|
||||
requireMalwareScan: true,
|
||||
},
|
||||
});
|
||||
return key;
|
||||
}
|
||||
|
||||
export async function uploadPortalFiles(input: {
|
||||
readonly identity: PortalSessionIdentity;
|
||||
readonly projectId: string;
|
||||
readonly files: readonly PortalUploadFile[];
|
||||
readonly limits?: Partial<PortalUploadLimits>;
|
||||
readonly idempotencyKey: string;
|
||||
readonly persistence?: PortalUploadPersistence;
|
||||
}): Promise<readonly PortalUploadResult[]> {
|
||||
if (input.identity.tenantFrozen) throw new PortalUploadError("PORTAL_FROZEN");
|
||||
const projectId = requireIdentifier(input.projectId, "PROJECT_ACCESS_DENIED");
|
||||
const idempotencyKey = requireIdentifier(input.idempotencyKey, "FILES_REQUIRED");
|
||||
const limits = normalizePortalUploadLimits(input.limits);
|
||||
const files = validatePortalUploadFiles(input.files, limits);
|
||||
const persistence = input.persistence ?? createPortalUploadPersistence();
|
||||
const results: PortalUploadResult[] = [];
|
||||
|
||||
for (const [index, file] of files.entries()) {
|
||||
const checksumSha256 = createHash("sha256").update(file.bytes).digest("hex");
|
||||
const reserved = await persistence.reserve({
|
||||
identity: input.identity,
|
||||
projectId,
|
||||
file,
|
||||
checksumSha256,
|
||||
idempotencyKey: `${idempotencyKey}:${index}`,
|
||||
quotaLimitBytes: limits.quotaBytes,
|
||||
});
|
||||
let storageKey: string | null = null;
|
||||
if (!reserved.alreadyCompleted) {
|
||||
try {
|
||||
storageKey = await persistence.store({ identity: input.identity, fileId: reserved.fileId, file });
|
||||
await persistence.complete({ identity: input.identity, reserved, projectId, file, storageKey, checksumSha256 });
|
||||
} catch (error) {
|
||||
const code = classifyPortalUploadFailure(error);
|
||||
const failed = await persistence.fail({ identity: input.identity, uploadId: reserved.uploadId, failureCode: code }).catch(() => false);
|
||||
if (storageKey && failed) await persistence.removeStored({ storageKey }).catch(() => undefined);
|
||||
throw new PortalUploadError(code);
|
||||
}
|
||||
}
|
||||
if (!reserved.effectsCompleted) {
|
||||
try {
|
||||
await Promise.all([
|
||||
persistence.appendActivity({
|
||||
identity: input.identity,
|
||||
projectId,
|
||||
uploadId: reserved.uploadId,
|
||||
fileId: reserved.fileId,
|
||||
filename: file.name,
|
||||
}),
|
||||
persistence.recordInbox({ identity: input.identity, projectId, uploadId: reserved.uploadId, filename: file.name }),
|
||||
reserved.projectLeaderUserId
|
||||
? persistence.notifyProjectLeader({
|
||||
identity: input.identity,
|
||||
projectId,
|
||||
uploadId: reserved.uploadId,
|
||||
projectLeaderUserId: reserved.projectLeaderUserId,
|
||||
})
|
||||
: Promise.resolve(),
|
||||
]);
|
||||
await persistence.markEffectsCompleted({ identity: input.identity, uploadId: reserved.uploadId });
|
||||
} catch {
|
||||
throw new PortalUploadError("STORAGE_FAILED");
|
||||
}
|
||||
}
|
||||
results.push({ uploadId: reserved.uploadId, fileId: reserved.fileId, name: file.name, sizeBytes: file.bytes.byteLength });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export function normalizePortalUploadLimits(input: Partial<PortalUploadLimits> = {}): PortalUploadLimits {
|
||||
const maxFiles = input.maxFiles ?? PORTAL_UPLOAD_DEFAULT_MAX_FILES;
|
||||
const maxFileBytes = input.maxFileBytes ?? PORTAL_UPLOAD_DEFAULT_MAX_FILE_BYTES;
|
||||
// The database capability intersects this technical ceiling with the
|
||||
// tenant's active commercial plan. Keeping the default high prevents an
|
||||
// unrelated historical 5 GB application fallback from overriding paid
|
||||
// package and add-on storage.
|
||||
const quotaBytes = input.quotaBytes ?? PORTAL_UPLOAD_ABSOLUTE_QUOTA_BYTES;
|
||||
if (!Number.isInteger(maxFiles) || maxFiles < 1 || maxFiles > PORTAL_UPLOAD_DEFAULT_MAX_FILES) throw new PortalUploadError("TOO_MANY_FILES");
|
||||
if (!Number.isInteger(maxFileBytes) || maxFileBytes < 1 || maxFileBytes > PORTAL_UPLOAD_ABSOLUTE_MAX_FILE_BYTES) {
|
||||
throw new PortalUploadError("FILE_TOO_LARGE");
|
||||
}
|
||||
if (!Number.isSafeInteger(quotaBytes) || quotaBytes < maxFileBytes || quotaBytes > PORTAL_UPLOAD_ABSOLUTE_QUOTA_BYTES) {
|
||||
throw new PortalUploadError("QUOTA_EXCEEDED");
|
||||
}
|
||||
return { maxFiles, maxFileBytes, quotaBytes };
|
||||
}
|
||||
|
||||
export function validatePortalUploadFiles(files: readonly PortalUploadFile[], limits: PortalUploadLimits): readonly PortalUploadFile[] {
|
||||
if (files.length === 0) throw new PortalUploadError("FILES_REQUIRED");
|
||||
if (files.length > limits.maxFiles) throw new PortalUploadError("TOO_MANY_FILES");
|
||||
for (const file of files) {
|
||||
if (!file.name.trim() || file.name.length > 255 || /[\u0000-\u001f\u007f]|\.\.[/\\]/u.test(file.name)) {
|
||||
throw new PortalUploadError("FILENAME_INVALID");
|
||||
}
|
||||
if (file.bytes.byteLength === 0) throw new PortalUploadError("FILE_EMPTY");
|
||||
if (file.bytes.byteLength > limits.maxFileBytes || file.bytes.byteLength > PORTAL_UPLOAD_ABSOLUTE_MAX_FILE_BYTES) {
|
||||
throw new PortalUploadError("FILE_TOO_LARGE");
|
||||
}
|
||||
if (!PORTAL_UPLOAD_ALLOWED_MIME_TYPES.has(file.mimeType.trim().toLowerCase())) throw new PortalUploadError("FILE_TYPE_BLOCKED");
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function createPortalUploadPersistence(db: DbClient = getWriteDbClient()): PortalUploadPersistence {
|
||||
const activityClient: ActivityWriteClient = {
|
||||
activity: {
|
||||
async create({ data }) {
|
||||
const rows = await db.$queryRaw<Array<{ id: string }>>`
|
||||
SELECT id FROM public.hivegrid_portal_append_activity(
|
||||
${data.tenantId}, ${data.subjectId}, ${data.summaryText}, ${data.metadata ?? null}
|
||||
)
|
||||
`;
|
||||
const id = rows[0]?.id;
|
||||
if (!id) throw new Error("portal activity capability failed");
|
||||
return { id };
|
||||
},
|
||||
},
|
||||
};
|
||||
const notificationClient: NotificationClient = {
|
||||
notificationDelivery: {
|
||||
async create({ data }) {
|
||||
await appendPortalNotification(db, data);
|
||||
return data;
|
||||
},
|
||||
async upsert({ create }) {
|
||||
await appendPortalNotification(db, create);
|
||||
return create;
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
async reserve({ identity, projectId, file, checksumSha256, idempotencyKey, quotaLimitBytes }) {
|
||||
return runWithPortalRlsContext(identity, async () => {
|
||||
const ids = [randomUUID(), randomUUID(), randomUUID(), randomUUID()] as const;
|
||||
const rows = await db.$queryRaw<ReservedPortalUpload[]>`
|
||||
SELECT * FROM public.hivegrid_portal_reserve_upload(
|
||||
${ids[0]}, ${ids[1]}, ${ids[2]}, ${ids[3]}, ${projectId}, ${file.name}, ${file.mimeType},
|
||||
${file.bytes.byteLength}, ${checksumSha256}, ${idempotencyKey}, ${quotaLimitBytes}
|
||||
)
|
||||
`;
|
||||
const reserved = rows[0];
|
||||
if (!reserved) throw new PortalUploadError("PROJECT_ACCESS_DENIED");
|
||||
return reserved;
|
||||
});
|
||||
},
|
||||
async complete({ identity, reserved, projectId, file, storageKey, checksumSha256 }) {
|
||||
await runWithPortalRlsContext(identity, async () => {
|
||||
const rows = await db.$queryRaw<Array<{ completed: boolean }>>`
|
||||
SELECT completed FROM public.hivegrid_portal_complete_upload(
|
||||
${reserved.uploadId}, ${reserved.fileUploadId}, ${reserved.fileId}, ${reserved.fileEntityLinkId}, ${projectId},
|
||||
${file.name}, ${file.mimeType}, ${file.bytes.byteLength}, ${storageKey}, ${checksumSha256}
|
||||
)
|
||||
`;
|
||||
if (!rows[0]?.completed) throw new Error("portal upload completion capability failed");
|
||||
});
|
||||
},
|
||||
async fail({ identity, uploadId, failureCode }) {
|
||||
const rows = await runWithPortalRlsContext(identity, () =>
|
||||
db.$queryRaw<Array<{ failed: boolean }>>`SELECT public.hivegrid_portal_fail_upload(${uploadId}, ${failureCode}) AS failed`,
|
||||
);
|
||||
return rows[0]?.failed === true;
|
||||
},
|
||||
async appendActivity({ identity, projectId, uploadId, fileId }) {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
logActivity(
|
||||
{
|
||||
tenantId: identity.tenantId,
|
||||
actorUserId: null,
|
||||
actorKind: "system",
|
||||
activityType: "file_uploaded",
|
||||
subjectType: "project",
|
||||
subjectId: projectId,
|
||||
summaryText: PORTAL_UPLOAD_ACTIVITY_SUMMARY_KEY,
|
||||
metadata: { portalUserId: identity.portalUserId, uploadId, fileId },
|
||||
},
|
||||
{ client: activityClient },
|
||||
),
|
||||
);
|
||||
},
|
||||
async notifyProjectLeader({ identity, projectId, uploadId, projectLeaderUserId }) {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
notify(
|
||||
{
|
||||
tenantId: identity.tenantId,
|
||||
userId: projectLeaderUserId,
|
||||
channel: "IN_APP",
|
||||
category: "customer_portal",
|
||||
messageKey: "customerPortal.notifications.uploadReceived",
|
||||
sourceKey: `portal-upload:${uploadId}`,
|
||||
payloadMetadata: { projectId, uploadId },
|
||||
},
|
||||
notificationClient,
|
||||
),
|
||||
);
|
||||
},
|
||||
async recordInbox({ identity, projectId, uploadId, filename }) {
|
||||
await runWithPortalRlsContext(identity, () =>
|
||||
db.$queryRaw`SELECT public.hivegrid_portal_record_inbox_event('upload', ${projectId}, ${uploadId}, ${filename})`,
|
||||
);
|
||||
},
|
||||
async markEffectsCompleted({ identity, uploadId }) {
|
||||
const rows = await runWithPortalRlsContext(identity, () =>
|
||||
db.$queryRaw<Array<{ completed: boolean }>>`SELECT completed FROM public.hivegrid_portal_mark_effects_completed('upload', ${uploadId})`,
|
||||
);
|
||||
if (!rows[0]?.completed) throw new Error("portal upload effects capability failed");
|
||||
},
|
||||
async store({ identity, fileId, file }) {
|
||||
return storePortalUploadFile({ identity, fileId, file });
|
||||
},
|
||||
async removeStored({ storageKey }) {
|
||||
await deleteFile({ bucket: resolveStorageBucket(), key: storageKey });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function appendPortalNotification(db: DbClient, data: {
|
||||
tenantId: string | null;
|
||||
userId: string | null;
|
||||
channel: string;
|
||||
category: string;
|
||||
messageKey: string;
|
||||
sourceKey: string | null;
|
||||
payloadMetadata: unknown;
|
||||
}): Promise<void> {
|
||||
const rows = await db.$queryRaw<Array<{ created: boolean }>>`
|
||||
SELECT created FROM public.hivegrid_portal_notify_project_leader(
|
||||
${data.tenantId}, ${data.userId}, ${data.channel}, ${data.category}, ${data.messageKey}, ${data.sourceKey}, ${data.payloadMetadata}
|
||||
)
|
||||
`;
|
||||
if (!rows[0]?.created) throw new Error("portal notification capability failed");
|
||||
}
|
||||
|
||||
function classifyPortalUploadFailure(error: unknown): PortalUploadError["code"] {
|
||||
if (error instanceof PortalUploadError) return error.code;
|
||||
const name = error instanceof Error ? `${error.name}:${error.message}`.toLowerCase() : "";
|
||||
if (name.includes("quota")) return "QUOTA_EXCEEDED";
|
||||
if (name.includes("scan") || name.includes("malware") || name.includes("infected")) return "SCAN_REJECTED";
|
||||
return "STORAGE_FAILED";
|
||||
}
|
||||
|
||||
function requireIdentifier<T extends PortalUploadError["code"]>(value: string, code: T): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized || normalized.length > 191 || /[\u0000-\u001f\u007f]/u.test(normalized)) throw new PortalUploadError(code);
|
||||
return normalized;
|
||||
}
|
||||
Reference in new issue
Block a user