Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/tests/e2e/utils/portal-setup-mail-fixture.ts
T

302 lines
13 KiB
TypeScript

import type { APIRequestContext, APIResponse } from "@playwright/test";
export type PortalInvitationEntrypoint = "admin" | "contact" | "project";
export const portalSetupMailFixtureInputs = ["E2E_PORTAL_SETUP_MAIL_FIXTURE_URL", "E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY"] as const;
const DEFAULT_POLL_TIMEOUT_MS = 45_000;
const MAX_POLL_TIMEOUT_MS = 90_000;
const POLL_INTERVAL_MS = 1_000;
const DELIVERY_TIMESTAMP_TOLERANCE_MS = 5_000;
const SETUP_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
type PortalSetupMailFixtureResponse = {
readonly correlationKey?: unknown;
readonly recipient?: unknown;
readonly source?: unknown;
readonly purpose?: unknown;
readonly deliveredAt?: unknown;
readonly setupUrl?: unknown;
};
export type PortalSetupJourneyContext = {
readonly origin: string;
readonly tenantPathPrefix: string;
readonly portalRootPath: string;
readonly projectsPath: string;
};
/**
* Test-only mailbox contract for VA-P26a.
*
* The endpoint receives a POST with `{ correlationKey, recipient, source,
* purpose: "setup", deliveredAfter }`. `202`, `204`, and `404` mean that the
* freshly delivered message in the dedicated disposable inbox is not visible
* yet. A ready response is `200` JSON and must echo those fields plus
* `deliveredAt` and the capability-bearing `setupUrl`. The adapter must observe
* actual provider delivery; reading HiveGrid's database, outbox, or queue is not
* a valid implementation of this contract. The endpoint, response body, and
* setup URL are deliberately never included in thrown errors because they can
* contain credentials or a live one-time token.
*/
export async function waitForPortalSetupMailLink(
request: APIRequestContext,
input: {
readonly endpoint: string;
readonly fixtureToken?: string;
readonly correlationKey: string;
readonly recipient: string;
readonly entrypoint: PortalInvitationEntrypoint;
readonly deliveredAfter: Date;
readonly portalBaseUrl: string;
readonly portalCustomDomainBaseUrl?: string;
readonly tenantSlug: string;
readonly timeoutMs?: number;
/** Unit-test seam; production callers use the fixed one-second interval. */
readonly pollIntervalMs?: number;
}
): Promise<string> {
const endpoint = requireSafeFixtureEndpoint(input.endpoint, Boolean(input.fixtureToken));
const expectedPortalOrigin = requireSafeOrigin(input.portalBaseUrl, "E2E_PORTAL_BASE_URL");
const expectedCustomPortalOrigin = input.portalCustomDomainBaseUrl
? requireSafeHttpsRootOrigin(input.portalCustomDomainBaseUrl, "E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL")
: undefined;
const timeoutMs = input.timeoutMs ?? portalSetupMailFixtureTimeoutMs();
const source = input.entrypoint === "admin" ? "portal_admin_invite" : input.entrypoint === "contact" ? "portal_contact_invite" : "portal_project_invite";
const deadline = Date.now() + timeoutMs;
const pollIntervalMs = normalizePollInterval(input.pollIntervalMs);
for (;;) {
const remainingMs = deadline - Date.now();
if (remainingMs <= 0) {
throw new Error("Portal setup mail fixture did not return a fresh matching setup mail before the configured timeout.");
}
let response: APIResponse;
try {
response = await request.post(endpoint.href, {
data: {
correlationKey: input.correlationKey,
recipient: input.recipient,
source,
purpose: "setup",
deliveredAfter: input.deliveredAfter.toISOString(),
},
failOnStatusCode: false,
headers: {
"Cache-Control": "no-store",
...(input.fixtureToken ? { Authorization: `Bearer ${input.fixtureToken}` } : {}),
},
maxRedirects: 0,
timeout: Math.min(5_000, remainingMs),
});
} catch {
// A mailbox/readiness adapter may briefly be unavailable while the mail
// worker or provider catches up. Keep the live capability and endpoint
// out of errors and retry only within the bounded poll deadline.
await wait(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));
continue;
}
if ([202, 204, 404].includes(response.status())) {
await wait(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));
continue;
}
if ([408, 425, 429].includes(response.status()) || response.status() >= 500) {
await wait(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));
continue;
}
if (response.status() !== 200) {
throw new Error(`Portal setup mail fixture returned unexpected HTTP status ${response.status()}.`);
}
const payload = (await response.json().catch(() => null)) as PortalSetupMailFixtureResponse | null;
if (!payload || typeof payload !== "object") {
throw new Error("Portal setup mail fixture returned an invalid JSON contract.");
}
if (
payload.correlationKey !== input.correlationKey ||
normalizeEmail(payload.recipient) !== normalizeEmail(input.recipient) ||
payload.source !== source ||
payload.purpose !== "setup"
) {
throw new Error("Portal setup mail fixture returned a response for a different invitation contract.");
}
const deliveredAt = typeof payload.deliveredAt === "string" ? new Date(payload.deliveredAt) : null;
if (!deliveredAt || !Number.isFinite(deliveredAt.getTime())) {
throw new Error("Portal setup mail fixture returned an invalid delivery timestamp.");
}
// Provider timestamps often have only second precision and the browser
// runner and mailbox adapter can differ by a few seconds. The unique
// correlation key + recipient remains the primary freshness boundary.
if (deliveredAt.getTime() + DELIVERY_TIMESTAMP_TOLERANCE_MS < input.deliveredAfter.getTime()) {
await wait(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));
continue;
}
if (typeof payload.setupUrl !== "string") {
throw new Error("Portal setup mail fixture response is missing its setup URL.");
}
return requireSafeSetupUrl(payload.setupUrl, expectedPortalOrigin, input.tenantSlug, expectedCustomPortalOrigin);
}
}
/**
* Re-validates the capability without exposing it and derives the only portal
* origin/path mode the browser journey may use. Standard-host routes retain
* the tenant prefix; an explicitly allowlisted custom host uses root routes.
*/
export function derivePortalSetupJourneyContext(
setupUrl: string,
input: {
readonly portalBaseUrl: string;
readonly portalCustomDomainBaseUrl?: string;
readonly tenantSlug: string;
}
): PortalSetupJourneyContext {
const standardOrigin = requireSafeOrigin(input.portalBaseUrl, "E2E_PORTAL_BASE_URL");
const customOrigin = input.portalCustomDomainBaseUrl
? requireSafeHttpsRootOrigin(input.portalCustomDomainBaseUrl, "E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL")
: undefined;
const safeSetupUrl = requireSafeSetupUrl(setupUrl, standardOrigin, input.tenantSlug, customOrigin);
const effectiveOrigin = new URL(safeSetupUrl).origin;
const tenantPathPrefix = effectiveOrigin === standardOrigin ? `/${encodeURIComponent(input.tenantSlug)}` : "";
return {
origin: effectiveOrigin,
tenantPathPrefix,
portalRootPath: tenantPathPrefix || "/",
projectsPath: `${tenantPathPrefix}/projects`,
};
}
export function isExpectedPortalJourneyLocation(url: URL, journey: PortalSetupJourneyContext, expectedPath: string): boolean {
return url.origin === journey.origin && normalizePortalPath(url.pathname) === expectedPath && !url.search && !url.hash;
}
export function isExpectedPortalProjectDetailLocation(url: URL, journey: PortalSetupJourneyContext): boolean {
if (url.origin !== journey.origin || url.search || url.hash) return false;
const prefix = `${journey.projectsPath}/`;
if (!url.pathname.startsWith(prefix)) return false;
const projectId = url.pathname.slice(prefix.length);
return projectId.length > 0 && !projectId.includes("/");
}
export function assertPortalSetupNavigationHasNoRedirect(response: { readonly request: () => { readonly redirectedFrom: () => unknown | null } }): void {
if (response.request().redirectedFrom() !== null) {
throw new Error("VA-P26a setup capability navigation used a forbidden redirect chain.");
}
}
export function portalSetupMailFixtureTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {
const raw = env.E2E_PORTAL_SETUP_MAIL_FIXTURE_TIMEOUT_MS?.trim();
if (!raw) return DEFAULT_POLL_TIMEOUT_MS;
const value = Number(raw);
if (!Number.isSafeInteger(value) || value < 1_000 || value > MAX_POLL_TIMEOUT_MS) {
throw new Error(`E2E_PORTAL_SETUP_MAIL_FIXTURE_TIMEOUT_MS must be an integer from 1000 to ${MAX_POLL_TIMEOUT_MS}.`);
}
return value;
}
function normalizePollInterval(value: number | undefined): number {
if (value === undefined) return POLL_INTERVAL_MS;
if (!Number.isSafeInteger(value) || value < 1 || value > POLL_INTERVAL_MS) {
throw new Error(`Portal setup mail fixture poll interval must be an integer from 1 to ${POLL_INTERVAL_MS}.`);
}
return value;
}
export function portalSetupMailFixtureNeedsToken(rawEndpoint: string): boolean {
const endpoint = parseHttpUrl(rawEndpoint, "E2E_PORTAL_SETUP_MAIL_FIXTURE_URL");
const loopback = isLoopbackHostname(endpoint.hostname);
if (!loopback && endpoint.protocol !== "https:") {
throw new Error("E2E_PORTAL_SETUP_MAIL_FIXTURE_URL must use HTTPS outside loopback.");
}
return !loopback;
}
function requireSafeFixtureEndpoint(rawEndpoint: string, hasToken: boolean): URL {
const endpoint = parseHttpUrl(rawEndpoint, "E2E_PORTAL_SETUP_MAIL_FIXTURE_URL");
const loopback = isLoopbackHostname(endpoint.hostname);
if (loopback && hasToken) {
throw new Error("E2E_PORTAL_SETUP_MAIL_FIXTURE_TOKEN must be unset for a loopback mail fixture.");
}
if (!loopback && endpoint.protocol !== "https:") {
throw new Error("E2E_PORTAL_SETUP_MAIL_FIXTURE_URL must use HTTPS outside loopback.");
}
if (!loopback && !hasToken) {
throw new Error("E2E_PORTAL_SETUP_MAIL_FIXTURE_TOKEN is required for a non-loopback mail fixture.");
}
return endpoint;
}
function requireSafeOrigin(rawUrl: string, inputName: string): string {
const url = parseHttpUrl(rawUrl, inputName);
if (!isLoopbackHostname(url.hostname) && url.protocol !== "https:") {
throw new Error(`${inputName} must use HTTPS outside loopback.`);
}
return url.origin;
}
function requireSafeHttpsRootOrigin(rawUrl: string, inputName: string): string {
const url = parseHttpUrl(rawUrl, inputName);
if (url.protocol !== "https:" || url.pathname !== "/" || url.search || url.hash) {
throw new Error(`${inputName} must be an exact HTTPS root origin.`);
}
return url.origin;
}
function requireSafeSetupUrl(rawUrl: string, expectedOrigin: string, tenantSlug: string, expectedCustomOrigin?: string): string {
const setupUrl = parseHttpUrl(rawUrl, "portal setup mail fixture setupUrl");
if (setupUrl.username || setupUrl.password || setupUrl.search || setupUrl.hash) {
throw new Error("Portal setup mail fixture returned a setup URL outside the expected portal host contract.");
}
const expectedPrefix =
setupUrl.origin === expectedOrigin
? `/${encodeURIComponent(tenantSlug)}/setup/`
: expectedCustomOrigin && setupUrl.origin === expectedCustomOrigin
? "/setup/"
: null;
if (!expectedPrefix) {
throw new Error("Portal setup mail fixture returned a setup URL outside the expected portal host contract.");
}
if (!setupUrl.pathname.startsWith(expectedPrefix)) {
throw new Error("Portal setup mail fixture returned a setup URL outside the expected setup route.");
}
const token = setupUrl.pathname.slice(expectedPrefix.length);
if (!SETUP_TOKEN_PATTERN.test(token)) {
throw new Error("Portal setup mail fixture returned an invalid setup capability shape.");
}
return setupUrl.href;
}
function parseHttpUrl(rawUrl: string, inputName: string): URL {
let url: URL;
try {
url = new URL(rawUrl);
} catch {
throw new Error(`${inputName} must be an absolute HTTP(S) URL.`);
}
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
throw new Error(`${inputName} must be an absolute HTTP(S) URL without embedded credentials.`);
}
return url;
}
function normalizeEmail(value: unknown): string | null {
return typeof value === "string" ? value.trim().toLocaleLowerCase("en-US") : null;
}
function normalizePortalPath(pathname: string): string {
return pathname === "/" ? pathname : pathname.replace(/\/$/u, "");
}
function isLoopbackHostname(hostname: string): boolean {
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
}
async function wait(milliseconds: number): Promise<void> {
await new Promise<void>((resolve) => setTimeout(resolve, milliseconds));
}