650 lines
30 KiB
TypeScript
650 lines
30 KiB
TypeScript
import type { Browser, BrowserContext } from "@playwright/test";
|
|
import { CUSTOMER_PORTAL_UAT_PROJECT_ID } from "../../scripts/customer-portal-uat/contracts";
|
|
|
|
import { expectNoCriticalA11yViolations } from "./utils/axe";
|
|
import { getTenantCredentials, loginAsTenantUser, type TenantCredentials } from "./utils/auth";
|
|
import { requireCanonicalE2eLocalPath } from "./utils/local-path";
|
|
import { skipIfUnavailable, waitForHydration } from "./utils/navigation";
|
|
import {
|
|
assertPortalSetupNavigationHasNoRedirect,
|
|
derivePortalSetupJourneyContext,
|
|
isExpectedPortalJourneyLocation,
|
|
isExpectedPortalProjectDetailLocation,
|
|
portalSetupMailFixtureInputs,
|
|
portalSetupMailFixtureNeedsToken,
|
|
portalSetupMailFixtureTimeoutMs,
|
|
type PortalInvitationEntrypoint,
|
|
type PortalSetupJourneyContext,
|
|
waitForPortalSetupMailLink,
|
|
} from "./utils/portal-setup-mail-fixture";
|
|
import { skipOrFailWhenE2eFixtureMissing, skipOrFailWhenE2eInputsMissing, skipOrFailWhenE2eOptInMissing } from "./utils/readiness";
|
|
import { expect, test, type Page } from "./utils/test";
|
|
|
|
const portalBaseUrl = process.env.E2E_PORTAL_BASE_URL;
|
|
const tenantSlug = process.env.E2E_PORTAL_TENANT_SLUG;
|
|
const email = process.env.E2E_PORTAL_EMAIL;
|
|
const password = process.env.E2E_PORTAL_PASSWORD;
|
|
const invitationMutationOptIn = "E2E_ALLOW_CUSTOMER_PORTAL_P26A_INVITATION_MUTATION";
|
|
const portalSessionCookieName = "__Host-hivegrid_portal_session";
|
|
const captchaTokenSelector = 'input[name="cap-token"], input[name="mcaptcha__token"]';
|
|
|
|
async function solveCaptchaIfPresent(page: Page): Promise<void> {
|
|
const mount = page.locator('[data-ui-id="ui.captcha.mount"]');
|
|
if ((await mount.count()) === 0) return;
|
|
const hasToken = async () => {
|
|
const tokens = page.locator(captchaTokenSelector);
|
|
for (let index = 0; index < (await tokens.count()); index += 1) {
|
|
if ((await tokens.nth(index).inputValue()).trim()) return true;
|
|
}
|
|
return false;
|
|
};
|
|
if (await hasToken()) return;
|
|
const verify = page.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: 20_000 });
|
|
await verify.click();
|
|
await expect.poll(hasToken, { message: "self-hosted captcha did not produce a token", timeout: 60_000 }).toBe(true);
|
|
}
|
|
|
|
const invitationCommonInputs = [
|
|
"E2E_TENANT_EMAIL",
|
|
"E2E_TENANT_PASSWORD",
|
|
"E2E_PORTAL_BASE_URL",
|
|
"E2E_PORTAL_TENANT_SLUG",
|
|
"E2E_PORTAL_INVITATION_ENTRYPOINT",
|
|
"E2E_PORTAL_INVITATION_EMAIL",
|
|
"E2E_PORTAL_INVITATION_EXPECTED_PROJECT",
|
|
"E2E_PORTAL_INVITATION_SETUP_PASSWORD",
|
|
...portalSetupMailFixtureInputs,
|
|
] as const;
|
|
|
|
// One disposable invitation is exercised per run. `admin` additionally needs
|
|
// E2E_TENANT_CUSTOMER_PORTAL_SETTINGS_PATH plus first/last name; `contact`
|
|
// needs contact-detail and portal-settings paths; `project` needs an explicit
|
|
// project-detail path and ProjektKontakt row id. The fixture key must select
|
|
// only the newly delivered mail for the configured recipient.
|
|
|
|
type InvitationContractBase = {
|
|
readonly entrypoint: PortalInvitationEntrypoint;
|
|
readonly tenantCredentials: TenantCredentials;
|
|
readonly portalBaseUrl: string;
|
|
readonly portalCustomDomainBaseUrl?: string;
|
|
readonly tenantSlug: string;
|
|
readonly recipient: string;
|
|
readonly expectedProject: string;
|
|
readonly setupPassword: string;
|
|
readonly mailFixtureUrl: string;
|
|
readonly mailFixtureKey: string;
|
|
readonly mailFixtureToken?: string;
|
|
readonly mailFixtureTimeoutMs: number;
|
|
};
|
|
|
|
type InvitationContract =
|
|
| (InvitationContractBase & {
|
|
readonly entrypoint: "admin";
|
|
readonly settingsPath: string;
|
|
readonly firstName: string;
|
|
readonly lastName: string;
|
|
})
|
|
| (InvitationContractBase & {
|
|
readonly entrypoint: "contact";
|
|
readonly contactPath: string;
|
|
readonly settingsPath: string;
|
|
})
|
|
| (InvitationContractBase & {
|
|
readonly entrypoint: "project";
|
|
readonly projectPath: string;
|
|
readonly projectContactRowId: string;
|
|
});
|
|
|
|
test.use({ trace: "off", video: "off" });
|
|
test.describe.configure({ mode: "serial" });
|
|
|
|
test.describe("VA-P26a customer portal interim smoke", () => {
|
|
test("signs in through the separate portal session and opens an access-scoped project", async ({ page }) => {
|
|
skipOrFailWhenE2eInputsMissing(
|
|
["E2E_PORTAL_BASE_URL", "E2E_PORTAL_TENANT_SLUG", "E2E_PORTAL_EMAIL", "E2E_PORTAL_PASSWORD"],
|
|
"Customer-portal smoke inputs not configured"
|
|
);
|
|
|
|
const loginUrl = new URL(`/${tenantSlug}/login`, portalBaseUrl).toString();
|
|
const loginResponse = await page.goto(loginUrl, { waitUntil: "domcontentloaded" });
|
|
const loginStatus = loginResponse?.status() ?? 0;
|
|
if (!loginResponse || [400, 403, 404].includes(loginStatus)) {
|
|
skipOrFailWhenE2eFixtureMissing(`VA-P26a portal login ${loginUrl} returned ${loginStatus || "no response"}`);
|
|
}
|
|
expect(loginStatus).toBeGreaterThanOrEqual(200);
|
|
expect(loginStatus).toBeLessThan(400);
|
|
|
|
await expect(page.locator('[data-ui-id="ui.customerPortal.publicShell"]')).toBeVisible();
|
|
await page.getByRole("button", { name: /^(Stattdessen mit Passwort anmelden|Sign in with a password instead)$/iu }).click();
|
|
await page.locator('input[name="email"]').fill(email!);
|
|
await page.locator('input[name="password"]').fill(password!);
|
|
await solveCaptchaIfPresent(page);
|
|
await page.getByRole("button", { name: /^(Stattdessen mit Passwort anmelden|Sign in with a password instead)$/iu }).click();
|
|
|
|
await page.waitForURL((url) => url.pathname.replace(/\/$/u, "") === `/${tenantSlug}`, { timeout: 20_000 });
|
|
await expect(page.locator('[data-ui-id="ui.customerPortal.portalShell"]')).toBeVisible();
|
|
|
|
await page
|
|
.getByRole("button", { name: /^(Projekte|Projects)$/iu })
|
|
.first()
|
|
.click();
|
|
await page.waitForURL((url) => url.pathname.replace(/\/$/u, "") === `/${tenantSlug}/projects`);
|
|
|
|
const projectCards = page.locator('[data-ui-id="ui.customerPortal.projectCard"]');
|
|
if ((await projectCards.count()) === 0) {
|
|
skipOrFailWhenE2eFixtureMissing("VA-P26a fixture needs at least one active PortalProjectAccess row");
|
|
}
|
|
await expect(projectCards.first()).toBeVisible();
|
|
await projectCards
|
|
.first()
|
|
.getByRole("button", { name: /^(Projekt öffnen|Open project)$/iu })
|
|
.click();
|
|
|
|
await page.waitForURL(new RegExp(`/${tenantSlug}/projects/[^/?#]+$`, "u"));
|
|
await expect(page.locator('[data-ui-id="ui.customerPortal.portalShell"]')).toBeVisible();
|
|
await expectNoCriticalA11yViolations(page);
|
|
});
|
|
|
|
test.describe("stateful invitation lifecycle", () => {
|
|
// A failed attempt may already have created the disposable portal identity.
|
|
// Retrying or repeating this mutation in every browser project would turn
|
|
// the expected duplicate-email guard into test flakiness.
|
|
test.describe.configure({ retries: 0 });
|
|
|
|
test("invites through the configured admin, contact, or project entrypoint, completes setup, and rejects replay", async ({
|
|
page,
|
|
browser,
|
|
request,
|
|
}, testInfo) => {
|
|
test.setTimeout(240_000);
|
|
test.skip(testInfo.project.name !== "chromium", "VA-P26a invitation lifecycle mutates one disposable fixture exactly once");
|
|
skipOrFailWhenE2eOptInMissing(invitationMutationOptIn, "skipping mutating VA-P26a invitation lifecycle");
|
|
const contract = requireInvitationContract();
|
|
|
|
await loginAsTenantUser(page, contract.tenantCredentials);
|
|
const invitation = await triggerInvitation(page, contract);
|
|
const setupUrl = await waitForPortalSetupMailLink(request, {
|
|
endpoint: contract.mailFixtureUrl,
|
|
...(contract.mailFixtureToken ? { fixtureToken: contract.mailFixtureToken } : {}),
|
|
correlationKey: contract.mailFixtureKey,
|
|
recipient: contract.recipient,
|
|
entrypoint: contract.entrypoint,
|
|
deliveredAfter: invitation.deliveredAfter,
|
|
portalBaseUrl: contract.portalBaseUrl,
|
|
...(contract.portalCustomDomainBaseUrl ? { portalCustomDomainBaseUrl: contract.portalCustomDomainBaseUrl } : {}),
|
|
tenantSlug: contract.tenantSlug,
|
|
timeoutMs: contract.mailFixtureTimeoutMs,
|
|
});
|
|
|
|
await proveSetupSessionProjectAndReplay(browser, setupUrl, { ...contract, expectedProject: invitation.expectedProject });
|
|
});
|
|
});
|
|
});
|
|
|
|
function requireInvitationContract(): InvitationContract {
|
|
skipOrFailWhenE2eInputsMissing(invitationCommonInputs, "VA-P26a invitation lifecycle inputs not configured");
|
|
const entrypoint = requiredInput("E2E_PORTAL_INVITATION_ENTRYPOINT");
|
|
if (entrypoint !== "admin" && entrypoint !== "contact" && entrypoint !== "project") {
|
|
throw new Error("E2E_PORTAL_INVITATION_ENTRYPOINT must be admin, contact, or project.");
|
|
}
|
|
|
|
const conditionalInputs =
|
|
entrypoint === "admin"
|
|
? ["E2E_TENANT_CUSTOMER_PORTAL_SETTINGS_PATH", "E2E_PORTAL_INVITATION_FIRST_NAME", "E2E_PORTAL_INVITATION_LAST_NAME"]
|
|
: entrypoint === "contact"
|
|
? ["E2E_PORTAL_INVITATION_CONTACT_PATH", "E2E_TENANT_CUSTOMER_PORTAL_SETTINGS_PATH"]
|
|
: ["E2E_PORTAL_INVITATION_PROJECT_PATH", "E2E_PORTAL_INVITATION_PROJECT_CONTACT_ROW_ID"];
|
|
skipOrFailWhenE2eInputsMissing(conditionalInputs, `VA-P26a ${entrypoint} invitation inputs not configured`);
|
|
|
|
const mailFixtureUrl = requiredInput("E2E_PORTAL_SETUP_MAIL_FIXTURE_URL");
|
|
if (portalSetupMailFixtureNeedsToken(mailFixtureUrl)) {
|
|
skipOrFailWhenE2eInputsMissing(["E2E_PORTAL_SETUP_MAIL_FIXTURE_TOKEN"], "VA-P26a non-loopback mail fixture authentication not configured");
|
|
}
|
|
|
|
const tenantCredentials = getTenantCredentials();
|
|
if (!tenantCredentials) {
|
|
skipOrFailWhenE2eFixtureMissing("VA-P26a tenant credentials were not available after the readiness input gate");
|
|
}
|
|
const setupPassword = requiredSecretInput("E2E_PORTAL_INVITATION_SETUP_PASSWORD");
|
|
if (setupPassword.length < 12) {
|
|
throw new Error("E2E_PORTAL_INVITATION_SETUP_PASSWORD must contain at least 12 characters.");
|
|
}
|
|
const portalCustomDomainBaseUrl = optionalPortalCustomDomainBaseUrl();
|
|
|
|
const common = {
|
|
tenantCredentials,
|
|
portalBaseUrl: requiredPortalBaseUrl(),
|
|
tenantSlug: requiredTenantSlug(),
|
|
recipient: requiredEmailInput("E2E_PORTAL_INVITATION_EMAIL"),
|
|
expectedProject: requiredInput("E2E_PORTAL_INVITATION_EXPECTED_PROJECT"),
|
|
setupPassword,
|
|
mailFixtureUrl,
|
|
mailFixtureKey: requiredFixtureKey(),
|
|
mailFixtureTimeoutMs: portalSetupMailFixtureTimeoutMs(),
|
|
...(portalCustomDomainBaseUrl ? { portalCustomDomainBaseUrl } : {}),
|
|
...(process.env.E2E_PORTAL_SETUP_MAIL_FIXTURE_TOKEN ? { mailFixtureToken: process.env.E2E_PORTAL_SETUP_MAIL_FIXTURE_TOKEN } : {}),
|
|
};
|
|
|
|
if (entrypoint === "admin") {
|
|
return {
|
|
...common,
|
|
entrypoint,
|
|
settingsPath: requiredLocalPath("E2E_TENANT_CUSTOMER_PORTAL_SETTINGS_PATH"),
|
|
firstName: requiredInput("E2E_PORTAL_INVITATION_FIRST_NAME"),
|
|
lastName: requiredInput("E2E_PORTAL_INVITATION_LAST_NAME"),
|
|
};
|
|
}
|
|
if (entrypoint === "contact") {
|
|
return {
|
|
...common,
|
|
entrypoint,
|
|
contactPath: requiredLocalPath("E2E_PORTAL_INVITATION_CONTACT_PATH"),
|
|
settingsPath: requiredLocalPath("E2E_TENANT_CUSTOMER_PORTAL_SETTINGS_PATH"),
|
|
};
|
|
}
|
|
return {
|
|
...common,
|
|
entrypoint,
|
|
projectPath: requiredLocalPath("E2E_PORTAL_INVITATION_PROJECT_PATH"),
|
|
projectContactRowId: requiredInput("E2E_PORTAL_INVITATION_PROJECT_CONTACT_ROW_ID"),
|
|
};
|
|
}
|
|
|
|
async function triggerInvitation(page: Page, contract: InvitationContract): Promise<{ readonly deliveredAfter: Date; readonly expectedProject: string }> {
|
|
if (contract.entrypoint === "admin") return triggerAdminInvitation(page, contract);
|
|
if (contract.entrypoint === "contact") return triggerContactInvitation(page, contract);
|
|
return triggerProjectInvitation(page, contract);
|
|
}
|
|
|
|
async function triggerAdminInvitation(
|
|
page: Page,
|
|
contract: Extract<InvitationContract, { readonly entrypoint: "admin" }>
|
|
): Promise<{ readonly deliveredAfter: Date; readonly expectedProject: string }> {
|
|
const response = await page.goto(contract.settingsPath, { waitUntil: "domcontentloaded" });
|
|
await skipIfUnavailable(page, response, `VA-P26a customer-portal settings ${contract.settingsPath} are unavailable`);
|
|
await waitForHydration(page);
|
|
const admin = page.locator('[data-ui-id="ui.customerPortal.admin"]');
|
|
await expect(admin).toBeVisible();
|
|
await admin.getByRole("tab", { name: /^(Nutzer|Users)$/iu }).click();
|
|
|
|
const inviteButton = admin.getByRole("button", { name: /^(Portalzugang einladen|Invite portal account)$/iu });
|
|
const firstNameInput = admin.getByLabel(/^(Vorname|First name)$/iu);
|
|
const lastNameInput = admin.getByLabel(/^(Nachname|Last name)$/iu);
|
|
const emailInput = admin.getByLabel(/^(E-Mail-Adresse|Email address)$/iu);
|
|
if (
|
|
!(await firstNameInput.isEnabled()) ||
|
|
!(await lastNameInput.isEnabled()) ||
|
|
!(await emailInput.isEnabled()) ||
|
|
!(await portalAdminCanManageAccess(page))
|
|
) {
|
|
skipOrFailWhenE2eFixtureMissing("VA-P26a admin fixture needs portal.manage_users and portal.manage_access");
|
|
}
|
|
|
|
await firstNameInput.fill(contract.firstName);
|
|
await lastNameInput.fill(contract.lastName);
|
|
await emailInput.fill(contract.recipient);
|
|
await expect(inviteButton).toBeEnabled();
|
|
|
|
const deliveredAfter = freshDeliveryBoundary();
|
|
await inviteButton.click();
|
|
await expect(admin.getByText(contract.recipient, { exact: false })).toBeVisible();
|
|
await expect(
|
|
admin.getByText(
|
|
/^(Der Einrichtungslink wurde per E-Mail versendet und ist sieben Tage gültig\.|The setup link was sent by email and remains valid for seven days\.)$/iu
|
|
)
|
|
).toBeVisible();
|
|
|
|
const invitedName = `${contract.firstName} ${contract.lastName}`;
|
|
const expectedProject = await grantExpectedProjectAccess(page, contract.recipient, invitedName, contract.expectedProject);
|
|
return { deliveredAfter, expectedProject };
|
|
}
|
|
|
|
async function triggerContactInvitation(
|
|
page: Page,
|
|
contract: Extract<InvitationContract, { readonly entrypoint: "contact" }>
|
|
): Promise<{ readonly deliveredAfter: Date; readonly expectedProject: string }> {
|
|
const beforeResponse = await page.goto(contract.settingsPath, { waitUntil: "domcontentloaded" });
|
|
await skipIfUnavailable(page, beforeResponse, `VA-P26a customer-portal settings ${contract.settingsPath} are unavailable`);
|
|
await waitForHydration(page);
|
|
if (!(await portalAdminCanManageAccess(page))) {
|
|
skipOrFailWhenE2eFixtureMissing("VA-P26a contact fixture needs portal.manage_access");
|
|
}
|
|
|
|
const response = await page.goto(contract.contactPath, { waitUntil: "domcontentloaded" });
|
|
await skipIfUnavailable(page, response, `VA-P26a contact invitation route ${contract.contactPath} is unavailable`);
|
|
await waitForHydration(page);
|
|
const contact = page.locator('[data-ui-id="ui.crm.detail"]');
|
|
await expect(contact).toBeVisible();
|
|
await expect(contact.getByText(contract.recipient, { exact: true }).first()).toBeVisible();
|
|
const inviteButton = contact.locator('[data-ui-id="ui.crm.detail.portalInvite"]');
|
|
if ((await inviteButton.count()) !== 1 || !(await inviteButton.isEnabled())) {
|
|
skipOrFailWhenE2eFixtureMissing("VA-P26a contact fixture needs one eligible contact and portal.manage_users");
|
|
}
|
|
|
|
const deliveredAfter = freshDeliveryBoundary();
|
|
await inviteButton.click();
|
|
await expect(contact.locator('[data-ui-id="ui.crm.detail.portalInviteSuccess"]')).toBeVisible();
|
|
|
|
const settingsResponse = await page.goto(contract.settingsPath, { waitUntil: "domcontentloaded" });
|
|
await skipIfUnavailable(page, settingsResponse, `VA-P26a customer-portal settings ${contract.settingsPath} are unavailable after contact invitation`);
|
|
await waitForHydration(page);
|
|
const expectedProject = await grantExpectedProjectAccess(page, contract.recipient, null, contract.expectedProject);
|
|
return { deliveredAfter, expectedProject };
|
|
}
|
|
|
|
async function triggerProjectInvitation(
|
|
page: Page,
|
|
contract: Extract<InvitationContract, { readonly entrypoint: "project" }>
|
|
): Promise<{ readonly deliveredAfter: Date; readonly expectedProject: string }> {
|
|
const response = await page.goto(contract.projectPath, { waitUntil: "domcontentloaded" });
|
|
await skipIfUnavailable(page, response, `VA-P26a project invitation route ${contract.projectPath} is unavailable`);
|
|
await waitForHydration(page);
|
|
const project = page.locator('[data-ui-id="ui.projects.detail"]');
|
|
await expect(project).toBeVisible();
|
|
const inviteButton = project.locator(`[data-ui-id="ui.projects.detail.contacts.${cssAttributeValue(contract.projectContactRowId)}.portalInvite"]`);
|
|
if ((await inviteButton.count()) !== 1 || !(await inviteButton.isEnabled())) {
|
|
skipOrFailWhenE2eFixtureMissing("VA-P26a project fixture needs one eligible private ProjektKontakt and portal.manage_users");
|
|
}
|
|
|
|
const deliveredAfter = freshDeliveryBoundary();
|
|
await inviteButton.click();
|
|
await expect(project.locator('[data-ui-id="ui.projects.detail.portalInviteSuccess"]')).toBeVisible();
|
|
return { deliveredAfter, expectedProject: contract.expectedProject };
|
|
}
|
|
|
|
type PortalAdminHarnessSnapshot = {
|
|
readonly canManageAccess: boolean;
|
|
readonly users: readonly { readonly id: string; readonly email: string; readonly name: string }[];
|
|
readonly accessRows: readonly { readonly portalUserId: string; readonly projectId: string; readonly projectLabel: string }[];
|
|
};
|
|
|
|
async function readPortalAdminHarnessSnapshot(page: Page): Promise<PortalAdminHarnessSnapshot | null> {
|
|
return page.evaluate(() => {
|
|
const router = (
|
|
globalThis as typeof globalThis & {
|
|
__reactRouterDataRouter?: { state?: { loaderData?: Record<string, unknown> } };
|
|
}
|
|
).__reactRouterDataRouter;
|
|
const routeData = router?.state?.loaderData?.["routes/app.$tenant/settings/customer-portal"] as
|
|
| {
|
|
vm?: {
|
|
status?: string;
|
|
data?: {
|
|
permissions?: { canManageAccess?: boolean };
|
|
users?: readonly { id?: unknown; email?: unknown; name?: unknown }[];
|
|
accessRows?: readonly { portalUserId?: unknown; projectId?: unknown; projectLabel?: unknown }[];
|
|
};
|
|
};
|
|
}
|
|
| undefined;
|
|
const data = routeData?.vm?.status === "ready" ? routeData.vm.data : undefined;
|
|
if (!data || !Array.isArray(data.users) || !Array.isArray(data.accessRows)) return null;
|
|
const users = data.users.filter(
|
|
(user): user is { id: string; email: string; name: string } =>
|
|
typeof user.id === "string" && typeof user.email === "string" && typeof user.name === "string"
|
|
);
|
|
const accessRows = data.accessRows.filter(
|
|
(row): row is { portalUserId: string; projectId: string; projectLabel: string } =>
|
|
typeof row.portalUserId === "string" && typeof row.projectId === "string" && typeof row.projectLabel === "string"
|
|
);
|
|
return { canManageAccess: data.permissions?.canManageAccess === true, users, accessRows };
|
|
});
|
|
}
|
|
|
|
async function portalAdminCanManageAccess(page: Page): Promise<boolean> {
|
|
return (await readPortalAdminHarnessSnapshot(page))?.canManageAccess === true;
|
|
}
|
|
|
|
async function grantExpectedProjectAccess(page: Page, recipient: string, invitedName: string | null, preferredProject: string): Promise<string> {
|
|
await expect
|
|
.poll(
|
|
async () => {
|
|
const snapshot = await readPortalAdminHarnessSnapshot(page);
|
|
const matchingUsers = snapshot?.users.filter((user) => user.email.toLowerCase() === recipient.toLowerCase()) ?? [];
|
|
const user = matchingUsers.length === 1 ? matchingUsers[0] : undefined;
|
|
if (!snapshot?.canManageAccess || !user || (invitedName !== null && user.name !== invitedName)) return false;
|
|
return true;
|
|
},
|
|
{ timeout: 15_000 }
|
|
)
|
|
.toBe(true);
|
|
const snapshotBeforeGrant = await readPortalAdminHarnessSnapshot(page);
|
|
const matchingUsers = snapshotBeforeGrant?.users.filter((user) => user.email.toLowerCase() === recipient.toLowerCase()) ?? [];
|
|
const user = matchingUsers.length === 1 ? matchingUsers[0] : undefined;
|
|
if (!snapshotBeforeGrant?.canManageAccess || !user || (invitedName !== null && user.name !== invitedName)) {
|
|
throw new Error("VA-P26a invitation did not yield one access-manageable portal user and project.");
|
|
}
|
|
const target = { portalUserId: user.id, userName: user.name, projectId: CUSTOMER_PORTAL_UAT_PROJECT_ID };
|
|
|
|
const grant = await page.evaluate(async (input) => {
|
|
const csrf = document.querySelector<HTMLMetaElement>('meta[name="csrf-token"]')?.content;
|
|
if (!csrf) return { status: 0, ok: false };
|
|
const form = new FormData();
|
|
for (const [key, value] of Object.entries({
|
|
csrf,
|
|
intent: "set-access",
|
|
portalUserId: input.portalUserId,
|
|
projectId: input.projectId,
|
|
active: "true",
|
|
canUpload: "true",
|
|
validUntil: "",
|
|
companyName: "",
|
|
roleLabel: "",
|
|
visibleStageIds: "",
|
|
visibleDocumentTypes: "",
|
|
canSeeOtherSubcontractors: "false",
|
|
})) {
|
|
form.set(key, value);
|
|
}
|
|
const response = await fetch(window.location.pathname, { method: "POST", body: form, credentials: "same-origin", headers: { Accept: "application/json" } });
|
|
await response.arrayBuffer();
|
|
return { status: response.status };
|
|
}, target);
|
|
expect(grant).toEqual({ status: 200 });
|
|
|
|
await page.reload({ waitUntil: "domcontentloaded" });
|
|
await waitForHydration(page);
|
|
const snapshot = await readPortalAdminHarnessSnapshot(page);
|
|
const matchingAccessRows =
|
|
snapshot?.accessRows.filter(
|
|
(row) =>
|
|
row.portalUserId === target.portalUserId &&
|
|
row.projectId === target.projectId &&
|
|
(row.projectLabel === preferredProject || row.projectLabel.endsWith(` · ${preferredProject}`))
|
|
) ?? [];
|
|
expect(matchingAccessRows).toHaveLength(1);
|
|
const projectLabel = matchingAccessRows[0]!.projectLabel;
|
|
const admin = page.locator('[data-ui-id="ui.customerPortal.admin"]');
|
|
await admin.getByRole("tab", { name: /^(Nutzer|Users)$/iu }).click();
|
|
await expect(admin.getByText(`${target.userName} · ${projectLabel}`, { exact: true })).toBeVisible();
|
|
return preferredProject;
|
|
}
|
|
|
|
async function proveSetupSessionProjectAndReplay(browser: Browser, setupUrl: string, contract: InvitationContract): Promise<void> {
|
|
const journey = derivePortalSetupJourneyContext(setupUrl, contract);
|
|
const setupContext = await browser.newContext();
|
|
try {
|
|
const setupPage = await setupContext.newPage();
|
|
await openSetupCapability(setupPage, setupUrl);
|
|
// Merely opening a bearer setup capability must never authenticate the
|
|
// browser. The session is allowed only after the explicit privacy consent
|
|
// and successful one-time consume below.
|
|
await expectPortalSessionCookie(setupContext, journey.origin, false);
|
|
await submitPortalSetup(setupPage, contract.setupPassword);
|
|
await setupPage.waitForURL((url) => isExpectedPortalJourneyLocation(url, journey, journey.portalRootPath), { timeout: 20_000 });
|
|
await waitForHydration(setupPage);
|
|
await expect(setupPage.locator('[data-ui-id="ui.customerPortal.portalShell"]')).toBeVisible();
|
|
await expectPortalSessionCookie(setupContext, journey.origin, true);
|
|
await openExpectedPortalProject(setupPage, contract, journey);
|
|
|
|
const replayContext = await browser.newContext();
|
|
try {
|
|
await expectPortalSessionCookie(replayContext, journey.origin, false);
|
|
const replayPage = await replayContext.newPage();
|
|
await openSetupCapability(replayPage, setupUrl);
|
|
await submitPortalSetup(replayPage, contract.setupPassword);
|
|
const setupRoot = replayPage.locator('[data-ui-id="ui.customerPortal.auth.setup"]');
|
|
await expect(setupRoot).toBeVisible();
|
|
await expect(
|
|
setupRoot.getByText(
|
|
/^(Dieser Link ist nicht mehr gültig\. Fordere bitte einen neuen an\.|This link is no longer valid\. Please request a new one\.)$/iu
|
|
)
|
|
).toBeVisible();
|
|
assertSetupCapabilityLocation(replayPage, setupUrl);
|
|
await expect(replayPage.locator('[data-ui-id="ui.customerPortal.portalShell"]')).toHaveCount(0);
|
|
await expectPortalSessionCookie(replayContext, journey.origin, false);
|
|
} finally {
|
|
await replayContext.close();
|
|
}
|
|
} finally {
|
|
await setupContext.close();
|
|
}
|
|
}
|
|
|
|
async function openSetupCapability(page: Page, setupUrl: string): Promise<void> {
|
|
const response = await page.goto(setupUrl, { waitUntil: "domcontentloaded" }).catch(() => {
|
|
throw new Error("VA-P26a setup capability navigation failed before a safe response was returned.");
|
|
});
|
|
const status = response?.status() ?? 0;
|
|
if (response) {
|
|
assertPortalSetupNavigationHasNoRedirect(response);
|
|
}
|
|
if (!response || [400, 403, 404].includes(status)) {
|
|
skipOrFailWhenE2eFixtureMissing(`VA-P26a setup capability returned ${status || "no response"}`);
|
|
}
|
|
expect(status).toBeGreaterThanOrEqual(200);
|
|
expect(status).toBeLessThan(400);
|
|
await waitForHydration(page);
|
|
assertSetupCapabilityLocation(page, setupUrl);
|
|
await expect(page.locator('[data-ui-id="ui.customerPortal.auth.setup"]')).toBeVisible();
|
|
}
|
|
|
|
async function submitPortalSetup(page: Page, setupPassword: string): Promise<void> {
|
|
const setupRoot = page.locator('[data-ui-id="ui.customerPortal.auth.setup"]');
|
|
await setupRoot.locator('input[name="password"]').fill(setupPassword);
|
|
await setupRoot.locator('input[name="passwordConfirmation"]').fill(setupPassword);
|
|
const privacy = setupRoot.locator('[data-ui-id="ui.customerPortal.auth.setup.privacyAcknowledgement"]');
|
|
await privacy.click();
|
|
await expect(privacy).toHaveAttribute("aria-checked", "true");
|
|
await solveCaptchaIfPresent(page);
|
|
await setupRoot.locator('form button[type="submit"]').click();
|
|
}
|
|
|
|
async function openExpectedPortalProject(page: Page, contract: InvitationContractBase, journey: PortalSetupJourneyContext): Promise<void> {
|
|
await page
|
|
.getByRole("button", { name: /^(Projekte|Projects)$/iu })
|
|
.first()
|
|
.click();
|
|
await page.waitForURL((url) => isExpectedPortalJourneyLocation(url, journey, journey.projectsPath));
|
|
const projectCard = page.locator('[data-ui-id="ui.customerPortal.projectCard"]').filter({ hasText: contract.expectedProject });
|
|
if ((await projectCard.count()) !== 1) {
|
|
skipOrFailWhenE2eFixtureMissing("VA-P26a invitation fixture did not yield exactly one expected project access");
|
|
}
|
|
await expect(projectCard).toBeVisible();
|
|
await projectCard.getByRole("button", { name: /^(Projekt öffnen|Open project)$/iu }).click();
|
|
await page.waitForURL((url) => isExpectedPortalProjectDetailLocation(url, journey));
|
|
await expect(page.locator('[data-ui-id="ui.customerPortal.portalShell"]')).toBeVisible();
|
|
await expect(page.getByText(contract.expectedProject, { exact: false }).first()).toBeVisible();
|
|
}
|
|
|
|
async function expectPortalSessionCookie(context: BrowserContext, baseUrl: string, expected: boolean): Promise<void> {
|
|
const cookies = await context.cookies(new URL(baseUrl).origin);
|
|
const hasPortalSession = cookies.some((cookie) => cookie.name === portalSessionCookieName && cookie.value.length > 0);
|
|
expect(hasPortalSession).toBe(expected);
|
|
}
|
|
|
|
function assertSetupCapabilityLocation(page: Page, setupUrl: string): void {
|
|
const expected = new URL(setupUrl);
|
|
let current: URL;
|
|
try {
|
|
current = new URL(page.url());
|
|
} catch {
|
|
throw new Error("VA-P26a setup capability left the allowlisted origin or route.");
|
|
}
|
|
if (current.origin !== expected.origin || current.pathname !== expected.pathname || current.search || current.hash) {
|
|
throw new Error("VA-P26a setup capability left the allowlisted origin or route.");
|
|
}
|
|
}
|
|
|
|
function freshDeliveryBoundary(): Date {
|
|
return new Date();
|
|
}
|
|
|
|
function requiredInput(key: string): string {
|
|
const value = process.env[key]?.trim();
|
|
if (!value) throw new Error(`${key} is required after the readiness gate.`);
|
|
return value;
|
|
}
|
|
|
|
function requiredSecretInput(key: string): string {
|
|
const value = process.env[key];
|
|
if (!value?.trim()) throw new Error(`${key} is required after the readiness gate.`);
|
|
return value;
|
|
}
|
|
|
|
function requiredEmailInput(key: string): string {
|
|
const value = requiredInput(key).toLocaleLowerCase("en-US");
|
|
const [localPart, domain, ...extraParts] = value.split("@");
|
|
if (extraParts.length > 0 || !localPart || localPart.length > 64 || !domain || value.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(value)) {
|
|
throw new Error(`${key} must be a valid email address.`);
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function requiredTenantSlug(): string {
|
|
const value = requiredInput("E2E_PORTAL_TENANT_SLUG");
|
|
if (!/^[a-z0-9][a-z0-9-]{1,62}$/u.test(value)) {
|
|
throw new Error("E2E_PORTAL_TENANT_SLUG must be a canonical lowercase tenant slug.");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function requiredFixtureKey(): string {
|
|
const value = requiredInput("E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY");
|
|
if (!/^[A-Za-z0-9._:-]{1,128}$/u.test(value)) {
|
|
throw new Error("E2E_PORTAL_SETUP_MAIL_FIXTURE_KEY must be a 1-128 character correlation key.");
|
|
}
|
|
return value;
|
|
}
|
|
|
|
function requiredLocalPath(key: string): string {
|
|
return requireCanonicalE2eLocalPath(requiredInput(key), key);
|
|
}
|
|
|
|
function requiredPortalBaseUrl(): string {
|
|
const value = requiredInput("E2E_PORTAL_BASE_URL");
|
|
let url: URL;
|
|
try {
|
|
url = new URL(value);
|
|
} catch {
|
|
throw new Error("E2E_PORTAL_BASE_URL must be an absolute HTTP(S) URL.");
|
|
}
|
|
const loopback = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(url.hostname);
|
|
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || (!loopback && url.protocol !== "https:")) {
|
|
throw new Error("E2E_PORTAL_BASE_URL must be a safe portal origin and use HTTPS outside loopback.");
|
|
}
|
|
return url.origin;
|
|
}
|
|
|
|
function optionalPortalCustomDomainBaseUrl(): string | undefined {
|
|
const value = process.env.E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL?.trim();
|
|
if (!value) return undefined;
|
|
let url: URL;
|
|
try {
|
|
url = new URL(value);
|
|
} catch {
|
|
throw new Error("E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL must be an exact HTTPS root origin.");
|
|
}
|
|
if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
throw new Error("E2E_PORTAL_CUSTOM_DOMAIN_BASE_URL must be an exact HTTPS root origin.");
|
|
}
|
|
return url.origin;
|
|
}
|
|
|
|
function cssAttributeValue(value: string): string {
|
|
return value.replace(/["\\]/gu, "\\$&");
|
|
}
|