/** 本地Mock构建的登录流程走查;拦截全部外部网络,不读取真实凭据。 */ import assert from 'node:assert/strict'; import { createServer } from 'node:http'; import { readFile, stat, mkdir, writeFile } from 'node:fs/promises'; import { resolve, extname, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { chromium } from 'playwright'; const root = resolve(fileURLToPath(new URL('..', import.meta.url))); const output = resolve(root, 'test-results/login-refinement-20261130'); const evidence = resolve(output, 'browser-' + new Date().toISOString().replace(/[:.]/g, '-')); const dist = resolve(output, 'mock-build/browser'); const types = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf', '.ico': 'image/x-icon' }; await stat(resolve(dist, 'index.html')); await mkdir(output, { recursive: true }); await mkdir(evidence, { recursive: true }); const server = createServer(async (request, response) => { try { const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); let path = resolve(dist, '.' + pathname); if (path !== dist && !path.startsWith(dist + sep)) { response.writeHead(403).end(); return; } try { if (!(await stat(path)).isFile()) path = resolve(dist, 'index.html'); } catch { if (extname(pathname)) { response.writeHead(404).end(); return; } path = resolve(dist, 'index.html'); } response.writeHead(200, { 'Content-Type': types[extname(path)] ?? 'application/octet-stream', 'Cache-Control': 'no-store' }); response.end(await readFile(path)); } catch { response.writeHead(500).end(); } }); await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); const origin = `http://127.0.0.1:${server.address().port}`; const report = { mode: 'mock_only_external_network_blocked', at: new Date().toISOString(), runDirectory: evidence, checks: [], screenshots: [], errors: [], blockedExternalRequests: [] }; const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_BIN || 'C:/Program Files/Google/Chrome/Application/chrome.exe' }); const devices = { mobile: { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }, desktop: { viewport: { width: 1440, height: 1000 } } }; const check = (name, details = {}) => report.checks.push({ name, pass: true, ...details }); async function open(kind, viewport) { const context = await browser.newContext({ ...devices[kind], ...(viewport ? { viewport } : {}) }); await context.route('**/*', route => { const url = route.request().url(); if (url.startsWith(origin + '/') || url.startsWith('data:') || url.startsWith('blob:')) return route.continue(); report.blockedExternalRequests.push(new URL(url).origin); return route.abort(); }); const page = await context.newPage(); page.on('pageerror', error => report.errors.push({ kind, message: error.message })); await page.goto(origin + '/login', { waitUntil: 'networkidle' }); await page.getByRole('heading', { name: kind === 'mobile' ? '欢迎使用飞马SI' : '欢迎回来', exact: true }).waitFor(); return { context, page }; } async function snapshot(page, name) { const width = await page.evaluate(() => ({ viewport: innerWidth, document: document.documentElement.scrollWidth })); assert.ok(width.document <= width.viewport + 1, name + '存在横向溢出'); const path = resolve(evidence, name + '.png'); await page.screenshot({ path, fullPage: true }); report.screenshots.push(path); check(name + '-no-horizontal-overflow', width); } async function agree(page) { await page.getByRole('button', { name: '同意并继续', exact: true }).click(); await page.getByRole('dialog').waitFor({ state: 'hidden' }); } async function entered(page, name) { await page.waitForURL(url => /^\/(mobile|desktop)\//.test(url.pathname), { timeout: 20_000 }); check(name, { landingPath: new URL(page.url()).pathname }); } try { for (const width of [320, 390, 412]) { const { page, context } = await open('mobile', { width, height: 844 }); const logo = page.locator('img.m-logo'); assert.equal(await logo.getAttribute('src'), 'icons/logo-mark.png'); assert.ok(await logo.evaluate(image => image.complete && image.naturalWidth > 0)); await snapshot(page, 'mobile-phone-' + width); if (width === 390) { await page.getByRole('button', { name: '服务协议', exact: true }).click(); await page.getByText('正式正文暂未提供,当前无法阅读,请稍后再查看。').waitFor(); await snapshot(page, 'mobile-terms-unavailable'); await page.getByRole('button', { name: '返回', exact: true }).click(); await page.locator('input[name="phone"]').fill('13800000000'); await page.getByRole('button', { name: '获取验证码', exact: true }).click(); await page.getByRole('button', { name: '《服务协议》', exact: true }).click(); await page.keyboard.press('Tab'); assert.ok(await page.evaluate(() => !!document.activeElement?.closest('[role="dialog"]'))); await page.keyboard.press('Escape'); await page.getByRole('dialog').waitFor({ state: 'hidden' }); await page.getByRole('button', { name: '获取验证码', exact: true }).click(); await page.getByRole('dialog').waitFor(); await page.getByRole('button', { name: '取消', exact: true }).click(); check('mobile-terms-escape-cancels-without-locking'); await page.getByRole('button', { name: '账号密码登录', exact: true }).click(); const stepLogo = await page.locator('img.m-logo').boundingBox(); assert.ok(stepLogo && stepLogo.width <= 64 && stepLogo.height <= 64, '步骤页图标未收紧'); check('mobile-step-logo-keeps-compact-size'); await page.getByRole('textbox', { name: '账号', exact: true }).fill('demo-login'); await page.locator('input[name="password"]').fill('sample'); await page.getByRole('button', { name: '显示密码', exact: true }).click(); assert.equal(await page.locator('input[name="password"]').getAttribute('type'), 'text'); await page.getByRole('button', { name: '隐藏密码', exact: true }).click(); await snapshot(page, 'mobile-password'); await page.setViewportSize({ width: 390, height: 380 }); await page.getByRole('button', { name: '登录', exact: true }).scrollIntoViewIfNeeded(); assert.ok(await page.getByRole('button', { name: '登录', exact: true }).isVisible()); const submitBounds = await page.getByRole('button', { name: '登录', exact: true }).boundingBox(); assert.ok(submitBounds && submitBounds.y >= 0 && submitBounds.y + submitBounds.height <= 381, '短视口提交按钮不可滚动到可见区'); await snapshot(page, 'mobile-password-short-viewport'); await page.setViewportSize({ width: 390, height: 844 }); await page.evaluate(() => document.documentElement.classList.add('dark')); await snapshot(page, 'mobile-password-dark'); } await context.close(); } for (const kind of ['mobile', 'desktop']) { for (const method of ['mobile', 'password', 'token']) { const { page, context } = await open(kind); if (method === 'mobile') { await page.locator('input[name="phone"]').fill('13800000000'); await page.getByRole('button', { name: '获取验证码', exact: true }).click(); await page.getByRole('button', { name: '《隐私政策》', exact: true }).click(); await page.keyboard.press('Escape'); await page.getByRole('dialog').waitFor({ state: 'hidden' }); await page.getByRole('button', { name: '获取验证码', exact: true }).click(); await page.getByRole('button', { name: '《服务协议》', exact: true }).click(); await page.getByRole('button', { name: '返回', exact: true }).click(); await page.keyboard.press('Tab'); assert.ok(await page.evaluate(() => !!document.activeElement?.closest('[role="dialog"]'))); check(kind + '-consent-cancel-return-focus'); await agree(page); if (kind === 'mobile') await page.getByRole('heading', { name: '输入验证码', exact: true }).waitFor(); await page.locator('input[name="code"]').fill('000000'); await page.getByRole('button', { name: '登录', exact: true }).click(); await page.getByRole('alert').filter({ hasText: '验证码已过期' }).waitFor(); await snapshot(page, kind + '-code-expired'); if (kind === 'mobile') { await page.getByRole('button', { name: '返回修改手机号', exact: true }).click(); assert.ok((await page.getByRole('button', { name: /秒后可重新发送/ }).textContent()).includes('秒')); await page.getByRole('button', { name: '输入已收到的验证码', exact: true }).click(); } await page.locator('input[name="code"]').fill('123456'); } else if (method === 'password') { await page.getByRole('button', { name: kind === 'mobile' ? '账号密码登录' : '账号登录', exact: true }).click(); await page.locator('input[name="username"]').fill('demo-login'); await page.locator('input[name="password"]').fill('wrong-password'); await page.getByRole('button', { name: '登录', exact: true }).click(); await agree(page); await page.getByRole('alert').filter({ hasText: '账号或密码不正确' }).waitFor(); await snapshot(page, kind + '-password-error'); await page.locator('input[name="password"]').fill('123456'); } else { await page.getByRole('button', { name: kind === 'mobile' ? '登录凭证登录' : '快捷登录', exact: true }).click(); await page.locator('input[name="token"]').fill('invalid-demo'); assert.equal(await page.locator('input[name="token"]').getAttribute('type'), 'password'); await page.getByRole('button', { name: '登录', exact: true }).click(); await agree(page); await page.getByRole('alert').filter({ hasText: '登录凭证已失效' }).waitFor(); await snapshot(page, kind + '-token-error'); await page.locator('input[name="token"]').fill('demo-fmode'); } await page.getByRole('button', { name: '登录', exact: true }).click(); await entered(page, kind + '-' + method + '-success'); if (method === 'token') { await page.goto(origin + '/' + kind + '/mine', { waitUntil: 'networkidle' }); const copy = page.getByRole('button', { name: kind === 'mobile' ? '复制登录凭证' : '复制', exact: true }); assert.ok(await copy.isDisabled()); await page.getByRole('button', { name: kind === 'mobile' ? '显示登录凭证' : '显示', exact: true }).click(); await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async () => { throw new Error('isolated-test-denied'); } } })); await copy.click(); await page.getByText('未能复制,请显示凭证后手动选中复制', { exact: true }).waitFor(); check(kind + '-mine-copy-denied-visible-feedback'); await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async () => undefined } })); await copy.click(); await page.getByText('登录凭证已复制', { exact: true }).waitFor(); check(kind + '-mine-copy-success-visible-feedback'); } await context.close(); } } const { page, context } = await open('desktop'); await page.locator('input[name="phone"]').fill('a'); assert.equal(await page.locator('input[name="phone"]').inputValue(), ''); check('desktop-input-normalization-visible-value'); await snapshot(page, 'desktop-phone'); await page.getByRole('button', { name: '账号登录', exact: true }).click(); await snapshot(page, 'desktop-password'); await context.close(); assert.deepEqual(report.errors, [], '页面出现未捕获错误'); check('all-pages-no-uncaught-errors'); report.pass = true; } catch (error) { report.pass = false; report.failure = { message: error.message, stack: error.stack }; throw error; } finally { await writeFile(resolve(output, 'browser-review.json'), JSON.stringify(report, null, 2) + '\n'); await writeFile(resolve(evidence, 'browser-review.json'), JSON.stringify(report, null, 2) + '\n'); await browser.close(); await new Promise(resolve => server.close(resolve)); console.log(JSON.stringify({ pass: report.pass, checks: report.checks.length, screenshots: report.screenshots.length, errors: report.errors, failure: report.failure?.message, report: 'test-results/login-refinement-20261130/browser-review.json' }, null, 2)); }