chore: Playwright и axe для браузерного QA веб-парта

Зависимости и навык spfx-qa для проверки портала в браузере (сценарии,
снимки, проверка доступности). Каталоги сессии и отчётов (.auth/,
.qa-reports/) — в .gitignore.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Тимур Городецкий
2026-10-09 12:18:14 +05:00
parent c80972469f
commit b64ec76998
10 changed files with 704 additions and 15 deletions
+117
View File
@@ -0,0 +1,117 @@
// Общий модуль для работы с реальным тенантом под учёткой пользователя.
// ЛЮБОЙ Playwright-сценарий в режиме --tenant обязан создавать контекст через newTenantContext().
//
// Что делает:
// - пускает браузер только на разрешённый сайт (+ служебные хосты Microsoft);
// - отменяет запросы, меняющие данные (создание/изменение/удаление) в SharePoint и Graph;
// - пропускает чтение, включая чтение через POST по белому списку;
// - пишет журнал всех заблокированных и разрешённых не-GET запросов;
// - по желанию записывает HAR с реальными ответами (для превращения бага в тест).
const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS']);
// SharePoint/Graph эндпоинты, которые читают данные, хотя используют POST
const READ_VIA_POST = [
/\/_api\/contextinfo/i,
/\/RenderListDataAsStream/i,
/\/GetItems\b/i,
/\/_api\/search\/postquery/i,
/\/GetUpdatedFormDigest/i,
/\/_api\/SP\.Utilities\.Utility\.ResolvePrincipalInCurrentContext/i,
/\/_api\/SP\.UI\.ApplicationPages\.ClientPeoplePickerWebServiceInterface\.clientPeoplePickerSearchUser/i,
/\/_api\/sp\.userprofiles\.peoplemanager/i,
/graph\.microsoft\.com\/.*\/\$batch/i, // проверяется отдельно по телу
/graph\.microsoft\.com\/.*\/search\/query/i,
/graph\.microsoft\.com\/.*\/getByIds/i,
];
const DATA_HOST = /(\.sharepoint\.com|graph\.microsoft\.com)$/i;
const EXTRA_TEST_HOST = process.env.GUARD_TEST_HOST; // только для самопроверки скрипта
// Дополнительные API проекта, где запись тоже надо блокировать (например, api.tsnu.kz).
// Задаются через opts.dataHosts или переменную окружения QA_DATA_HOSTS="api.tsnu.kz,other.host"
let extraDataHosts = (process.env.QA_DATA_HOSTS || '').split(',').map(h => h.trim().toLowerCase()).filter(Boolean);
function isDataHost(host) {
host = host.toLowerCase();
return DATA_HOST.test(host) || extraDataHosts.includes(host) || (EXTRA_TEST_HOST && host === EXTRA_TEST_HOST);
}
function batchIsReadOnly(body) {
if (!body) return false;
try {
const json = JSON.parse(body); // Graph JSON batch
return Array.isArray(json.requests) && json.requests.every(r => READ_METHODS.has(String(r.method).toUpperCase()));
} catch {
// SharePoint OData $batch (multipart): ищем методы внутри частей
const methods = [...body.matchAll(/^(GET|POST|PUT|PATCH|MERGE|DELETE)\s+https?:\/\//gim)].map(m => m[1].toUpperCase());
return methods.length > 0 && methods.every(m => m === 'GET');
}
}
export function classify(request) {
const url = new URL(request.url());
const method = request.method().toUpperCase();
const override = (request.headers()['x-http-method'] || '').toUpperCase();
if (!isDataHost(url.hostname)) return { action: 'allow', reason: 'not-data-host' };
if (READ_METHODS.has(method) && !override) return { action: 'allow', reason: 'read' };
if (['MERGE', 'DELETE', 'PUT', 'PATCH'].includes(override)) return { action: 'block', reason: `x-http-method ${override}` };
if (/\/\$batch/i.test(url.pathname)) {
return batchIsReadOnly(request.postData())
? { action: 'allow', reason: 'read-only batch' }
: { action: 'block', reason: 'batch with writes or unparsed' };
}
if (READ_VIA_POST.some(re => re.test(url.href))) return { action: 'allow', reason: 'read via POST (allowlist)' };
return { action: 'block', reason: `${method} to data endpoint` };
}
/**
* @param browser Playwright Browser
* @param opts { storageState, siteUrl, dataHosts?, harPath?, localBuild?, viewport?, isMobile?, deviceScaleFactor? }
* @returns { context, log } log.blocked / log.allowedWrites / log.offsite
*/
export async function newTenantContext(browser, opts) {
if (!opts.storageState) throw new Error('storageState обязателен');
if (!opts.siteUrl) throw new Error('siteUrl обязателен: адрес сайта, на котором разрешено тестирование');
if (opts.dataHosts) extraDataHosts = [...new Set([...extraDataHosts, ...opts.dataHosts.map(h => h.toLowerCase())])];
const site = new URL(opts.siteUrl);
const log = { blocked: [], allowedNonGet: [], offsite: [] };
const context = await browser.newContext({
storageState: opts.storageState,
viewport: opts.viewport,
isMobile: opts.isMobile,
deviceScaleFactor: opts.deviceScaleFactor,
// Нужно только для локальной сборки SPFx (https://localhost:4321 с dev-сертификатом)
ignoreHTTPSErrors: Boolean(opts.localBuild),
...(opts.harPath ? { recordHar: { path: opts.harPath, content: 'embed', urlFilter: url => /\/_api\/|graph\.microsoft\.com/.test(url) || isDataHost(new URL(url).hostname) } } : {}),
});
await context.route('**/*', async route => {
const req = route.request();
const url = new URL(req.url());
// Навигация документа на другой SharePoint-сайт — не пускаем
if (req.isNavigationRequest() && req.frame() === req.frame().page()?.mainFrame()
&& /\.sharepoint\.com$/i.test(url.hostname)
&& !(url.hostname === site.hostname && url.pathname.toLowerCase().startsWith(site.pathname.toLowerCase()))) {
log.offsite.push(url.href.slice(0, 200));
return route.abort('blockedbyclient');
}
const c = classify(req);
if (c.action === 'block') {
log.blocked.push({ method: req.method(), url: url.href.slice(0, 200), reason: c.reason });
return route.abort('blockedbyclient');
}
if (!READ_METHODS.has(req.method().toUpperCase()) && isDataHost(url.hostname)) {
log.allowedNonGet.push({ method: req.method(), url: url.href.slice(0, 200), reason: c.reason });
}
return route.continue();
});
return { context, log };
}
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env node
// Проба для /spfx-qa: открывает URL на нескольких ширинах, собирает доказательства, печатает JSON.
// Зависимости (devDependencies проекта): playwright, @axe-core/playwright (опционально).
//
// node probe.mjs --url <url> --out <dir> --name <prefix> [--widths 320,640,1024,375]
// [--wait-for <css>] [--timeout 20000]
// [--tenant --storage-state .auth/tenant.json --site <url сайта> [--data-hosts api.tsnu.kz] [--har <файл.har>] [--local-build]]
//
// В режиме --tenant запросы, меняющие данные, блокируются (см. guard.mjs).
import { chromium } from 'playwright';
import fs from 'node:fs/promises';
import path from 'node:path';
import { newTenantContext } from './guard.mjs';
const args = Object.fromEntries(
process.argv.slice(2).reduce((acc, a, i, arr) => {
if (!a.startsWith('--')) return acc;
const next = arr[i + 1];
acc.push([a.slice(2), next && !next.startsWith('--') ? next : true]);
return acc;
}, [])
);
const url = args.url;
const out = args.out || '.qa-reports/tmp';
const name = args.name || 'probe';
const widths = String(args.widths || '320,640,1024,375').split(',').map(Number);
const timeout = Number(args.timeout || 20000);
const tenant = Boolean(args.tenant);
if (!url) { console.error('--url обязателен'); process.exit(2); }
const host = new URL(url).hostname;
const isLocal = /^(localhost|127\.0\.0\.1|\[::1\])$|\.(localhost|test)$/.test(host);
if (!isLocal && !tenant) {
console.error(`Не локальный адрес (${host}). Для тенанта нужен явный флаг --tenant.`);
process.exit(2);
}
if (tenant && (!args['storage-state'] || !args.site)) {
console.error('Режим --tenant требует --storage-state (сессию сохраняет пользователь сам: save-session.mjs) и --site (разрешённый сайт).');
process.exit(2);
}
let AxeBuilder = null;
try { ({ default: AxeBuilder } = await import('@axe-core/playwright')); } catch { /* axe не установлен */ }
await fs.mkdir(out, { recursive: true });
const browser = await chromium.launch();
const result = { url, surface: tenant ? 'tenant' : 'harness', date: new Date().toISOString(), axe: Boolean(AxeBuilder), runs: [] };
// Признаки непереведённых строк и утёкших значений в тексте
const SUSPICIOUS = [/\bundefined\b/, /\[object Object\]/, /\bNaN\b/, /\b[A-Z][A-Za-z]+Strings\.[A-Za-z]+/, /\{\d+\}/];
for (const width of widths) {
const mobile = width === 375;
const viewport = { width, height: mobile ? 812 : 900 };
let context, guardLog = null;
if (tenant) {
const har = args.har ? String(args.har).replace(/\.har$/, `-${width}.har`) : undefined;
({ context, log: guardLog } = await newTenantContext(browser, {
storageState: args['storage-state'], siteUrl: args.site, harPath: har,
dataHosts: args['data-hosts'] ? String(args['data-hosts']).split(',') : undefined,
localBuild: Boolean(args['local-build']), viewport, isMobile: mobile, deviceScaleFactor: mobile ? 2 : 1,
}));
} else {
context = await browser.newContext({ viewport, deviceScaleFactor: mobile ? 2 : 1, isMobile: mobile });
}
const page = await context.newPage();
const run = { width, consoleErrors: [], consoleWarnings: [], pageErrors: [], failedRequests: [], dataRequests: 0 };
page.on('console', m => {
if (m.type() === 'error') run.consoleErrors.push(m.text().slice(0, 500));
if (m.type() === 'warning' && /react|key|unmounted|act\(/i.test(m.text())) run.consoleWarnings.push(m.text().slice(0, 300));
});
page.on('pageerror', e => run.pageErrors.push(String(e.message).slice(0, 500)));
page.on('requestfailed', r => { if (r.failure()?.errorText !== 'net::ERR_BLOCKED_BY_CLIENT') run.failedRequests.push({ url: r.url().slice(0, 200), error: r.failure()?.errorText }); });
page.on('response', r => { if (r.status() >= 400) run.failedRequests.push({ url: r.url().slice(0, 200), status: r.status() }); });
page.on('request', r => {
if (/\/_api\/|graph\.microsoft\.com|\/api\//.test(r.url())) run.dataRequests++;
});
const t0 = Date.now();
try {
await page.goto(url, { waitUntil: 'domcontentloaded', timeout });
if (args['wait-for']) await page.waitForSelector(String(args['wait-for']), { timeout });
await page.waitForLoadState('networkidle', { timeout }).catch(() => {});
run.loadMs = Date.now() - t0;
run.overflowX = await page.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1);
const text = await page.evaluate(() => document.body.innerText);
run.suspiciousText = SUSPICIOUS.flatMap(re => (text.match(new RegExp(re, 'g')) || []).slice(0, 3));
run.textSample = text.slice(0, 1500);
if (AxeBuilder) {
const axe = await new AxeBuilder({ page }).analyze();
run.a11y = axe.violations
.filter(v => ['serious', 'critical'].includes(v.impact))
.map(v => ({ id: v.id, impact: v.impact, help: v.help, nodes: v.nodes.length }));
}
const shot = path.join(out, `${name}-${width}.jpg`);
await page.screenshot({ path: shot, type: 'jpeg', quality: 60, fullPage: true });
run.screenshot = shot;
} catch (e) {
run.error = String(e.message).slice(0, 500);
}
if (guardLog) run.guard = guardLog;
await context.close();
result.runs.push(run);
}
await browser.close();
console.log(JSON.stringify(result, null, 2));
@@ -0,0 +1,27 @@
#!/usr/bin/env node
// Запускает ПОЛЬЗОВАТЕЛЬ (не агент). Открывает видимый браузер, вы логинитесь сами
// (пароль, MFA), затем нажимаете Enter в терминале — сессия сохраняется в файл.
// ВНИМАНИЕ: файл = доступ к вашей учётке M365. Не коммитьте, не пересылайте, удаляйте после тестов.
//
// node save-session.mjs https://<test-tenant>.sharepoint.com/sites/<qa-site> [.auth/tenant.json]
import { chromium } from 'playwright';
import readline from 'node:readline/promises';
import fs from 'node:fs/promises';
import path from 'node:path';
const [url, file = '.auth/tenant.json'] = process.argv.slice(2);
if (!url) { console.error('Укажите URL тестового сайта'); process.exit(2); }
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
await (await context.newPage()).goto(url);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
await rl.question('Залогиньтесь в открытом окне, дождитесь загрузки сайта и нажмите Enter… ');
rl.close();
await fs.mkdir(path.dirname(file), { recursive: true });
await context.storageState({ path: file });
await browser.close();
console.log(`Сессия сохранена в ${file}. Проверьте, что путь есть в .gitignore.`);