Refresh HiveGrid Cloud reference snapshot

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

No files matched your search

@@ -1,5 +1,7 @@
import { expect, type Locator, type Page } from "@playwright/test";
import { waitForHydration } from "./navigation";
export type TenantCredentials = {
email: string;
password: string;
@@ -29,8 +31,9 @@ const LOGIN_OFF_URL_TIMEOUT_MS = 15_000;
// back off for the rate-limit case and surface other errors immediately.
const RATE_LIMIT_TEXT_PATTERN = /too many|zu viele/iu;
async function attemptLogin(page: Page, credentials: TenantCredentials): Promise<boolean> {
await page.goto("/login", { waitUntil: "domcontentloaded" });
async function attemptLogin(page: Page, credentials: TenantCredentials, loginPageUrl: string): Promise<boolean> {
await page.goto(loginPageUrl, { waitUntil: "domcontentloaded" });
await waitForHydration(page);
await page.locator('[data-ui-id="ui.auth.login.email"], input[type="email"], input[name="email"], input#email').first().fill(credentials.email);
await page
@@ -50,10 +53,9 @@ async function attemptLogin(page: Page, credentials: TenantCredentials): Promise
// Cache the authenticated cookies after the first real login and reuse them for
// every later spec in the same (workers:1) run. Re-logging-in per test
// saturates the server auth rate limit (10/60s per IP+email), which surfaces as
// flaky "stayed on /login" failures across the large serial suite. /login
// redirects an authenticated session away, so the cache can be validated
// cheaply and a stale entry (e.g. after a sign-out test) falls back to a real
// login.
// flaky "stayed on /login" failures across the large serial suite. The cache is
// validated against an authenticated surface; a stale entry (e.g. after a
// sign-out test) falls back to a real login.
//
// The cache is keyed by EMAIL: the suite logs in as multiple users (the tenant
// admin AND a read-only fixture). A single global cache would hand a later
@@ -61,27 +63,70 @@ async function attemptLogin(page: Page, credentials: TenantCredentials): Promise
// (so /login redirects away and the cache "matches"), silently running the
// read-only test as the admin — which then sees mutation controls and fails.
type StoredCookies = Awaited<ReturnType<ReturnType<Page["context"]>["cookies"]>>;
const cachedCookiesByEmail = new Map<string, StoredCookies>();
const cachedCookiesByIdentity = new Map<string, StoredCookies>();
async function reuseCachedLogin(page: Page, credentials: TenantCredentials): Promise<boolean> {
const cached = cachedCookiesByEmail.get(credentials.email);
async function reuseCachedLogin(page: Page, credentials: TenantCredentials, loginPageUrl: string, sessionProbeUrl: string): Promise<boolean> {
const cacheKey = loginCacheKey(credentials, loginPageUrl);
const cached = cachedCookiesByIdentity.get(cacheKey);
if (!cached || cached.length === 0) return false;
await page.context().addCookies(cached);
await page.goto("/login", { waitUntil: "domcontentloaded" });
await page.goto(sessionProbeUrl, { waitUntil: "domcontentloaded" });
if (!LOGIN_URL_PATTERN.test(page.url())) return true;
cachedCookiesByEmail.delete(credentials.email);
cachedCookiesByIdentity.delete(cacheKey);
return false;
}
async function reuseContextLogin(page: Page, sessionProbeUrl: string): Promise<boolean> {
const probeUrl = new URL(sessionProbeUrl, process.env.E2E_BASE_URL ?? "http://localhost:3000");
const cookies = await page.context().cookies(probeUrl.origin);
if (cookies.length === 0) return false;
await page.goto(sessionProbeUrl, { waitUntil: "domcontentloaded" });
return !LOGIN_URL_PATTERN.test(page.url());
}
export async function loginAsTenantUser(page: Page, credentials: TenantCredentials): Promise<void> {
if (await reuseCachedLogin(page, credentials)) {
await loginAt(page, credentials, "/login");
}
export async function loginAsAdminUser(page: Page, credentials: TenantCredentials): Promise<void> {
await loginAt(page, credentials, resolveAdminLoginUrl(), resolveAdminDashboardUrl());
}
export function resolveAdminLoginUrl(env: NodeJS.ProcessEnv = process.env): string {
return resolveAdminSurfaceUrl("/login", env);
}
export function resolveAdminDashboardUrl(env: NodeJS.ProcessEnv = process.env): string {
return resolveAdminSurfaceUrl("/dashboard", env);
}
function resolveAdminSurfaceUrl(pathname: string, env: NodeJS.ProcessEnv): string {
const explicitAdminUrl = env.E2E_ADMIN_BASE_URL?.trim();
const baseUrl = explicitAdminUrl || env.E2E_BASE_URL?.trim() || "http://localhost:3000";
const url = new URL(baseUrl);
if (!explicitAdminUrl) {
url.hostname = url.hostname === "localhost" ? "admin.localhost" : url.hostname.replace(/^app\./u, "admin.");
}
url.pathname = pathname;
url.search = "";
url.hash = "";
return url.toString();
}
async function loginAt(page: Page, credentials: TenantCredentials, loginPageUrl: string, sessionProbeUrl: string = loginPageUrl): Promise<void> {
if (await reuseContextLogin(page, sessionProbeUrl)) {
return;
}
const cacheKey = loginCacheKey(credentials, loginPageUrl);
if (await reuseCachedLogin(page, credentials, loginPageUrl, sessionProbeUrl)) {
return;
}
let rateLimited = false;
for (let attempt = 0; attempt < LOGIN_MAX_ATTEMPTS; attempt += 1) {
if (await attemptLogin(page, credentials)) {
cachedCookiesByEmail.set(credentials.email, await page.context().cookies());
if (await attemptLogin(page, credentials, loginPageUrl)) {
cachedCookiesByIdentity.set(cacheKey, await page.context().cookies());
return;
}
@@ -107,6 +152,10 @@ export async function loginAsTenantUser(page: Page, credentials: TenantCredentia
await expect(page, `Expected to leave /login after submitting tenant credentials but stayed on ${page.url()}.${hint}`).not.toHaveURL(LOGIN_URL_PATTERN);
}
function loginCacheKey(credentials: TenantCredentials, loginPageUrl: string): string {
return `${credentials.email.trim().toLowerCase()}@${new URL(loginPageUrl, "http://localhost").origin}`;
}
export async function expectPasswordRequirementsVisible(requirements: Locator): Promise<void> {
await expect(requirements).toBeVisible();
const items = requirements.locator("li");
@@ -138,39 +187,43 @@ export function tenantSettingsProfilePath(dashboardPath: string): string {
}
export function tenantSettingsAccountPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "account", process.env.E2E_TENANT_SETTINGS_ACCOUNT_PATH ?? "/app/settings/account");
return tenantSettingsPath(dashboardPath, "workspace", process.env.E2E_TENANT_SETTINGS_ACCOUNT_PATH ?? "/app/settings/workspace");
}
export function tenantSettingsSubscriptionPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "subscription", process.env.E2E_TENANT_SUBSCRIPTION_PATH ?? "/app/settings/subscription");
return tenantSettingsPath(dashboardPath, "billing", process.env.E2E_TENANT_SUBSCRIPTION_PATH ?? "/app/settings/billing");
}
export function tenantSettingsPoliciesPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "policies", process.env.E2E_TENANT_POLICIES_PATH ?? "/app/settings/policies");
return tenantSettingsPath(dashboardPath, "workspace/policies", process.env.E2E_TENANT_POLICIES_PATH ?? "/app/settings/workspace/policies");
}
export function tenantSettingsNotificationsPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "notifications", process.env.E2E_TENANT_NOTIFICATIONS_PATH ?? "/app/settings/notifications");
return tenantSettingsPath(dashboardPath, "profile/notifications", process.env.E2E_TENANT_NOTIFICATIONS_PATH ?? "/app/settings/profile/notifications");
}
export function tenantSettingsMembersPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "members", process.env.E2E_TENANT_MEMBERS_PATH ?? "/app/settings/members");
return tenantSettingsPath(dashboardPath, "team", process.env.E2E_TENANT_MEMBERS_PATH ?? "/app/settings/team");
}
export function tenantSettingsLogsPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "logs", process.env.E2E_TENANT_LOGS_PATH ?? "/app/settings/logs");
return tenantSettingsPath(dashboardPath, "compliance", process.env.E2E_TENANT_LOGS_PATH ?? "/app/settings/compliance");
}
export function tenantSettingsLogEventsPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "logs/events", process.env.E2E_TENANT_LOG_EVENTS_PATH ?? "/app/settings/logs/events");
return tenantSettingsPath(dashboardPath, "compliance/events", process.env.E2E_TENANT_LOG_EVENTS_PATH ?? "/app/settings/compliance/events");
}
export function tenantSettingsAuditExportPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "audit-export", process.env.E2E_TENANT_AUDIT_EXPORT_PATH ?? "/app/settings/audit-export");
return tenantSettingsPath(dashboardPath, "compliance/audit-export", process.env.E2E_TENANT_AUDIT_EXPORT_PATH ?? "/app/settings/compliance/audit-export");
}
export function tenantRolesAndPermissionsPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "roles-and-permissions", process.env.E2E_TENANT_ROLES_AND_PERMISSIONS_PATH ?? "/app/settings/roles-and-permissions");
return tenantSettingsPath(dashboardPath, "team/roles", process.env.E2E_TENANT_ROLES_AND_PERMISSIONS_PATH ?? "/app/settings/team/roles");
}
export function tenantLegacyRolesAndPermissionsPath(dashboardPath: string): string {
return tenantSettingsPath(dashboardPath, "roles-and-permissions", "/app/settings/roles-and-permissions");
}
function tenantSettingsPath(dashboardPath: string, section: string, fallbackPath: string): string {
@@ -0,0 +1,25 @@
import { expect, type Page } from "./test";
const captchaTokenSelector = 'input[name="cap-token"], input[name="mcaptcha__token"]';
export async function solveCaptchaIfPresent(page: Page): Promise<void> {
const mount = page.locator('[data-ui-id="ui.captcha.mount"]');
if ((await mount.count()) === 0) return;
if (await hasCaptchaToken(page)) return;
const verify = mount.getByRole("button", {
name: /^(Click to verify you're a human|Verify you're human|Ich bin ein Mensch|Klicken, um zu bestätigen, dass Sie ein Mensch sind)$/iu,
});
await expect(verify).toBeVisible({ timeout: 10_000 });
await verify.click();
await expect.poll(() => hasCaptchaToken(page), { message: "self-hosted captcha did not produce a token", timeout: 60_000 }).toBe(true);
}
async function hasCaptchaToken(page: Page): Promise<boolean> {
const tokens = page.locator(captchaTokenSelector);
for (let index = 0; index < (await tokens.count()); index += 1) {
if ((await tokens.nth(index).inputValue()).trim().length > 0) return true;
}
return false;
}
@@ -0,0 +1,28 @@
const E2E_LOCAL_PATH_ORIGIN = "https://hivegrid-e2e.invalid";
export function requireCanonicalE2eLocalPath(value: string, inputName: string): string {
let resolved: URL;
try {
resolved = new URL(value, E2E_LOCAL_PATH_ORIGIN);
} catch {
throw invalidLocalPath(inputName);
}
if (
!value.startsWith("/") ||
value.startsWith("//") ||
value.includes("\\") ||
value.includes("%") ||
/[\u0000-\u001f\u007f]/u.test(value) ||
resolved.origin !== E2E_LOCAL_PATH_ORIGIN ||
resolved.pathname !== value ||
resolved.search ||
resolved.hash
) {
throw invalidLocalPath(inputName);
}
return value;
}
function invalidLocalPath(inputName: string): Error {
return new Error(`${inputName} must be a canonical app-local absolute path without query or fragment.`);
}
@@ -1,5 +1,4 @@
import { test, type Page, type Response } from "@playwright/test";
import { encode } from "turbo-stream";
const SKIPPABLE_STATUSES = new Set([400, 403, 404]);
const MOLLIE_HOST_PATTERN = /(^|\.)mollie\.com$/u;
@@ -78,18 +77,46 @@ export function singleFetchActionError(message: string): { status: number; body:
};
}
async function encodeTurboStream(value: unknown): Promise<string> {
const stream = encode(value);
const reader = stream.getReader();
const decoder = new TextDecoder();
let out = "";
for (;;) {
const { done, value: chunk } = await reader.read();
if (done) break;
out += decoder.decode(chunk, { stream: true });
function encodeSingleFetchJson(value: unknown): string {
const values: string[] = [];
const indices = new Map<unknown, number>();
function flatten(input: unknown): number {
if (input === undefined) return -7;
if (input === null) return -5;
if (typeof input === "number") {
if (Number.isNaN(input)) return -2;
if (input === Number.NEGATIVE_INFINITY) return -3;
if (Object.is(input, -0)) return -4;
if (input === Number.POSITIVE_INFINITY) return -6;
}
const existing = indices.get(input);
if (existing !== undefined) return existing;
const index = values.length;
indices.set(input, index);
values.push("");
if (typeof input === "string" || typeof input === "number" || typeof input === "boolean") {
values[index] = JSON.stringify(input);
return index;
}
if (Array.isArray(input)) {
values[index] = `[${input.map((item) => flatten(item)).join(",")}]`;
return index;
}
if (typeof input === "object" && Object.getPrototypeOf(input) === Object.prototype) {
const entries = Object.entries(input).map(([key, item]) => `"_${flatten(key)}":${flatten(item)}`);
values[index] = `{${entries.join(",")}}`;
return index;
}
throw new TypeError("Single-fetch test fixtures must contain only JSON-compatible values");
}
out += decoder.decode();
return out;
const root = flatten(value);
return root < 0 ? `${root}\n` : `[${values.join(",")}]\n`;
}
/**
@@ -99,9 +126,9 @@ async function encodeTurboStream(value: unknown): Promise<string> {
* turbo-stream and the client (`unwrapSingleFetchResult`) hands `.data` to
* `useActionData()`. Fulfilling the `.data` POST with raw `application/json`
* instead breaks RR7's turbo-stream decoder, so `actionData` is never populated
* and the result/waiting UI never renders. We call the real `turbo-stream`
* `encode` (same package RR7 uses) so arbitrarily-shaped payloads — e.g. a full
* waiting-block execution — encode exactly as the server would. The
* and the result/waiting UI never renders. The test helper emits the JSON-only
* subset of React Router's inlined v2 wire format, which covers these fixture
* payloads without retaining a vulnerable standalone serializer dependency. The
* `X-Remix-Response: yes` header is required or RR7 rejects the response.
*/
export async function singleFetchActionData(
@@ -111,7 +138,7 @@ export async function singleFetchActionData(
return {
status,
contentType: "text/x-script",
body: await encodeTurboStream({ data: payload }),
body: encodeSingleFetchJson({ data: payload }),
headers: { "x-remix-response": "yes" },
};
}
@@ -0,0 +1,35 @@
import type { Page } from "@playwright/test";
export type OperatorCheckpointId = "starter-addon-checkout" | "domain-ownership-txt" | "domain-setup-checkout";
type OperatorCheckpointTestInfo = {
readonly project: {
readonly use: {
readonly headless?: boolean;
};
};
readonly annotations: Array<{ type: string; description?: string }>;
};
export async function pauseForOperatorCheckpoint(
page: Pick<Page, "pause">,
testInfo: OperatorCheckpointTestInfo,
checkpoint: OperatorCheckpointId,
env: NodeJS.ProcessEnv = process.env
): Promise<boolean> {
const configured = env.E2E_OPERATOR_CHECKPOINTS?.trim();
if (!configured || configured === "0") return false;
if (configured !== "1") {
throw new Error("E2E_OPERATOR_CHECKPOINTS must be unset, 0, or 1.");
}
if (env.CI?.trim()) {
throw new Error("E2E_OPERATOR_CHECKPOINTS is forbidden in CI.");
}
if (testInfo.project.use.headless !== false) {
throw new Error("E2E_OPERATOR_CHECKPOINTS requires a headed Playwright run.");
}
testInfo.annotations.push({ type: "operator-checkpoint", description: checkpoint });
await page.pause();
return true;
}
@@ -0,0 +1,301 @@
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));
}