Files

111 lines
7.6 KiB
JavaScript
Raw Permalink Normal View History

2026-08-26 06:41:07 +08:00
import { createRequire } from "node:module";
import { randomUUID } from "node:crypto";
import { execFileSync } from "node:child_process";
import { mkdir } from "node:fs/promises";
import { fileURLToPath } from "node:url";
const require = createRequire(process.env.PLAYWRIGHT_REQUIRE_FROM ?? import.meta.url);
const { chromium } = require("playwright");
const outputDirectory = new URL("./screenshots/", import.meta.url);
const webURL = process.env.VISUAL_WEB_URL ?? "http://localhost:3100";
const webHostPattern = new RegExp(new URL(webURL).host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
const oidcURLPattern = new RegExp(process.env.VISUAL_OIDC_URL_PATTERN ?? "localhost:58180");
const username = process.env.VISUAL_USERNAME ?? "owner";
const password = process.env.VISUAL_PASSWORD ?? "LocalOnly123!";
const marker = randomUUID().slice(0, 8);
const inviteeHint = `受控邀请-${marker}`;
const claimCode = `DEVICE-CLAIM-${marker}-9X7K`;
const householdPublicID = "10000000-0000-0000-0000-000000000211";
const subjectPublicID = "10000000-0000-0000-0000-000000000411";
await mkdir(outputDirectory, { recursive: true });
function psql(statement) {
return execFileSync("docker", ["compose", "exec", "-T", "postgres", "psql", "-v", "ON_ERROR_STOP=1", "-U", "voice", "-d", "voice_platform", "-Atc", statement], {
cwd: process.cwd(), encoding: "utf8", stdio: ["ignore", "pipe", "pipe"]
}).trim();
}
const invitationCountBefore = Number(psql("SELECT count(*) FROM member_invitation;"));
const bindingCountBefore = Number(psql("SELECT count(*) FROM device_binding;"));
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH ?? "C:/Program Files/Google/Chrome/Application/chrome.exe" });
const page = await browser.newPage({ viewport: { width: 1440, height: 1050 }, deviceScaleFactor: 1 });
const consoleErrors = [];
const failedRequests = [];
const createRequests = [];
page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
page.on("request", (request) => {
const requestURL = new URL(request.url());
if (request.method() === "POST" && (/^\/api\/v1\/households\/[^/]+\/invitations$/.test(requestURL.pathname) || requestURL.pathname === "/api/v1/device-claims")) createRequests.push(`${request.method()} ${requestURL.pathname}`);
});
page.on("requestfailed", (request) => {
const failure = request.failure()?.errorText ?? "failed";
const requestURL = new URL(request.url());
if (request.method() === "GET" && requestURL.pathname === "/api/v1/events" && failure.includes("ERR_ABORTED")) return;
failedRequests.push(`${request.method()} ${request.url()} ${failure}`);
});
try {
await page.goto(webURL, { waitUntil: "networkidle" });
await page.getByRole("button", { name: "登录研发环境" }).click();
await page.waitForURL(oidcURLPattern);
await page.locator("#username").fill(username);
await page.locator("#password").fill(password);
await page.locator("#kc-login").click();
await page.waitForURL(webHostPattern, { timeout: 15000 });
await page.getByRole("heading", { name: "家庭业务工作台" }).waitFor();
await page.getByRole("button", { name: "家庭成员", exact: true }).click();
const invitationForm = page.locator("form.tool-form").filter({ hasText: "创建成员邀请" });
await invitationForm.waitFor();
await invitationForm.getByLabel("接收人提示").fill(inviteeHint);
await invitationForm.getByLabel("加入角色").selectOption("admin");
await invitationForm.getByRole("button", { name: "生成邀请" }).click();
let control = page.getByRole("form", { name: "家庭业务受控操作" });
await control.waitFor();
let text = await control.textContent();
const invitationTargetBound = text?.includes(householdPublicID) === true && text?.includes(inviteeHint) === true && text?.includes("管理员") === true && text?.includes("固定有效期 7天") === true && text?.includes("接收人提示仅用于人工识别,不校验接受者身份") === true && text?.includes("明文只在创建成功后显示一次") === true;
let action = control.getByRole("button", { name: "确认生成成员邀请" });
const invitationNeedsAcknowledgement = await action.isDisabled();
await control.getByLabel(/接收人提示不绑定真实身份/).check();
const invitationEnabled = await action.isEnabled();
await control.screenshot({ path: fileURLToPath(new URL("family-member-invitation-create-control.png", outputDirectory)) });
await control.getByRole("button", { name: "取消" }).click();
const invitationCancelClosed = await control.count() === 0;
const noInvitationSecret = await page.getByLabel("一次性邀请凭据").count() === 0;
await page.getByRole("button", { name: "设备管理", exact: true }).click();
const claimForm = page.locator("form.workspace__claim");
const claimInput = claimForm.getByLabel("设备绑定码");
const claimButton = claimForm.getByRole("button", { name: "绑定设备" });
await claimInput.fill("123456789012345");
const shortClaimBlocked = await claimButton.isDisabled();
await claimInput.fill(claimCode);
const validClaimEnabled = await claimButton.isEnabled();
await claimButton.click();
control = page.getByRole("form", { name: "家庭业务受控操作" });
await control.waitFor();
text = await control.textContent();
const claimTargetBound = text?.includes(householdPublicID) === true && text?.includes(subjectPublicID) === true && text?.includes("测试长者") === true && text?.includes(claimCode.slice(-4)) === true && text?.includes(`共${claimCode.length}字符`) === true && text?.includes("平台不会生成或回显完整设备码") === true;
const claimSecretMasked = text?.includes(claimCode) === false;
action = control.getByRole("button", { name: "确认绑定该设备" });
const claimNeedsAcknowledgement = await action.isDisabled();
await control.getByLabel(/已当面核对设备屏幕、设备型号和使用人/).check();
const claimEnabled = await action.isEnabled();
await control.screenshot({ path: fileURLToPath(new URL("family-device-claim-control.png", outputDirectory)) });
await control.getByRole("button", { name: "取消" }).click();
const claimCancelClosed = await control.count() === 0;
const claimInputCleared = await claimInput.inputValue() === "";
const invitationsUnchanged = Number(psql("SELECT count(*) FROM member_invitation;")) === invitationCountBefore;
const bindingsUnchanged = Number(psql("SELECT count(*) FROM device_binding;")) === bindingCountBefore;
const overflow = await page.evaluate(() => [...document.querySelectorAll("body *")]
.filter((element) => element instanceof HTMLElement && element.scrollWidth > element.clientWidth + 2 && getComputedStyle(element).overflowX === "visible")
.slice(0, 20)
.map((element) => `${element.tagName}.${element.className}: ${element.clientWidth}/${element.scrollWidth}`));
const result = { invitationTargetBound, invitationNeedsAcknowledgement, invitationEnabled, invitationCancelClosed, noInvitationSecret, shortClaimBlocked, validClaimEnabled, claimTargetBound, claimSecretMasked, claimNeedsAcknowledgement, claimEnabled, claimCancelClosed, claimInputCleared, invitationsUnchanged, bindingsUnchanged, createRequests, overflow, consoleErrors, failedRequests };
console.log(JSON.stringify(result, null, 2));
if (Object.entries(result).some(([key, value]) => !["createRequests", "overflow", "consoleErrors", "failedRequests"].includes(key) && value !== true) || createRequests.length || overflow.length || consoleErrors.length || failedRequests.length) throw new Error("Family one-time credential controls visual smoke failed");
} finally {
await browser.close();
}