review-login-refinement.mjs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /** 本地Mock构建的登录流程走查;拦截全部外部网络,不读取真实凭据。 */
  2. import assert from 'node:assert/strict';
  3. import { createServer } from 'node:http';
  4. import { readFile, stat, mkdir, writeFile } from 'node:fs/promises';
  5. import { resolve, extname, sep } from 'node:path';
  6. import { fileURLToPath } from 'node:url';
  7. import { chromium } from 'playwright';
  8. const root = resolve(fileURLToPath(new URL('..', import.meta.url)));
  9. const output = resolve(root, 'test-results/login-refinement-20261130');
  10. const evidence = resolve(output, 'browser-' + new Date().toISOString().replace(/[:.]/g, '-'));
  11. const dist = resolve(output, 'mock-build/browser');
  12. 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' };
  13. await stat(resolve(dist, 'index.html'));
  14. await mkdir(output, { recursive: true });
  15. await mkdir(evidence, { recursive: true });
  16. const server = createServer(async (request, response) => {
  17. try {
  18. const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
  19. let path = resolve(dist, '.' + pathname);
  20. if (path !== dist && !path.startsWith(dist + sep)) { response.writeHead(403).end(); return; }
  21. try { if (!(await stat(path)).isFile()) path = resolve(dist, 'index.html'); }
  22. catch { if (extname(pathname)) { response.writeHead(404).end(); return; } path = resolve(dist, 'index.html'); }
  23. response.writeHead(200, { 'Content-Type': types[extname(path)] ?? 'application/octet-stream', 'Cache-Control': 'no-store' });
  24. response.end(await readFile(path));
  25. } catch { response.writeHead(500).end(); }
  26. });
  27. await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
  28. const origin = `http://127.0.0.1:${server.address().port}`;
  29. const report = { mode: 'mock_only_external_network_blocked', at: new Date().toISOString(), runDirectory: evidence, checks: [], screenshots: [], errors: [], blockedExternalRequests: [] };
  30. const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_BIN || 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
  31. const devices = { mobile: { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }, desktop: { viewport: { width: 1440, height: 1000 } } };
  32. const check = (name, details = {}) => report.checks.push({ name, pass: true, ...details });
  33. async function open(kind, viewport) {
  34. const context = await browser.newContext({ ...devices[kind], ...(viewport ? { viewport } : {}) });
  35. await context.route('**/*', route => {
  36. const url = route.request().url();
  37. if (url.startsWith(origin + '/') || url.startsWith('data:') || url.startsWith('blob:')) return route.continue();
  38. report.blockedExternalRequests.push(new URL(url).origin);
  39. return route.abort();
  40. });
  41. const page = await context.newPage();
  42. page.on('pageerror', error => report.errors.push({ kind, message: error.message }));
  43. await page.goto(origin + '/login', { waitUntil: 'networkidle' });
  44. await page.getByRole('heading', { name: kind === 'mobile' ? '欢迎使用飞马SI' : '欢迎回来', exact: true }).waitFor();
  45. return { context, page };
  46. }
  47. async function snapshot(page, name) {
  48. const width = await page.evaluate(() => ({ viewport: innerWidth, document: document.documentElement.scrollWidth }));
  49. assert.ok(width.document <= width.viewport + 1, name + '存在横向溢出');
  50. const path = resolve(evidence, name + '.png');
  51. await page.screenshot({ path, fullPage: true }); report.screenshots.push(path); check(name + '-no-horizontal-overflow', width);
  52. }
  53. async function agree(page) {
  54. await page.getByRole('button', { name: '同意并继续', exact: true }).click();
  55. await page.getByRole('dialog').waitFor({ state: 'hidden' });
  56. }
  57. async function entered(page, name) {
  58. await page.waitForURL(url => /^\/(mobile|desktop)\//.test(url.pathname), { timeout: 20_000 });
  59. check(name, { landingPath: new URL(page.url()).pathname });
  60. }
  61. try {
  62. for (const width of [320, 390, 412]) {
  63. const { page, context } = await open('mobile', { width, height: 844 });
  64. const logo = page.locator('img.m-logo');
  65. assert.equal(await logo.getAttribute('src'), 'icons/logo-mark.png');
  66. assert.ok(await logo.evaluate(image => image.complete && image.naturalWidth > 0));
  67. await snapshot(page, 'mobile-phone-' + width);
  68. if (width === 390) {
  69. await page.getByRole('button', { name: '服务协议', exact: true }).click();
  70. await page.getByText('正式正文暂未提供,当前无法阅读,请稍后再查看。').waitFor();
  71. await snapshot(page, 'mobile-terms-unavailable');
  72. await page.getByRole('button', { name: '返回', exact: true }).click();
  73. await page.locator('input[name="phone"]').fill('13800000000');
  74. await page.getByRole('button', { name: '获取验证码', exact: true }).click();
  75. await page.getByRole('button', { name: '《服务协议》', exact: true }).click();
  76. await page.keyboard.press('Tab');
  77. assert.ok(await page.evaluate(() => !!document.activeElement?.closest('[role="dialog"]')));
  78. await page.keyboard.press('Escape');
  79. await page.getByRole('dialog').waitFor({ state: 'hidden' });
  80. await page.getByRole('button', { name: '获取验证码', exact: true }).click();
  81. await page.getByRole('dialog').waitFor();
  82. await page.getByRole('button', { name: '取消', exact: true }).click();
  83. check('mobile-terms-escape-cancels-without-locking');
  84. await page.getByRole('button', { name: '账号密码登录', exact: true }).click();
  85. const stepLogo = await page.locator('img.m-logo').boundingBox();
  86. assert.ok(stepLogo && stepLogo.width <= 64 && stepLogo.height <= 64, '步骤页图标未收紧');
  87. check('mobile-step-logo-keeps-compact-size');
  88. await page.getByRole('textbox', { name: '账号', exact: true }).fill('demo-login');
  89. await page.locator('input[name="password"]').fill('sample');
  90. await page.getByRole('button', { name: '显示密码', exact: true }).click();
  91. assert.equal(await page.locator('input[name="password"]').getAttribute('type'), 'text');
  92. await page.getByRole('button', { name: '隐藏密码', exact: true }).click();
  93. await snapshot(page, 'mobile-password');
  94. await page.setViewportSize({ width: 390, height: 380 });
  95. await page.getByRole('button', { name: '登录', exact: true }).scrollIntoViewIfNeeded();
  96. assert.ok(await page.getByRole('button', { name: '登录', exact: true }).isVisible());
  97. const submitBounds = await page.getByRole('button', { name: '登录', exact: true }).boundingBox();
  98. assert.ok(submitBounds && submitBounds.y >= 0 && submitBounds.y + submitBounds.height <= 381, '短视口提交按钮不可滚动到可见区');
  99. await snapshot(page, 'mobile-password-short-viewport');
  100. await page.setViewportSize({ width: 390, height: 844 });
  101. await page.evaluate(() => document.documentElement.classList.add('dark'));
  102. await snapshot(page, 'mobile-password-dark');
  103. }
  104. await context.close();
  105. }
  106. for (const kind of ['mobile', 'desktop']) {
  107. for (const method of ['mobile', 'password', 'token']) {
  108. const { page, context } = await open(kind);
  109. if (method === 'mobile') {
  110. await page.locator('input[name="phone"]').fill('13800000000');
  111. await page.getByRole('button', { name: '获取验证码', exact: true }).click();
  112. await page.getByRole('button', { name: '《隐私政策》', exact: true }).click();
  113. await page.keyboard.press('Escape');
  114. await page.getByRole('dialog').waitFor({ state: 'hidden' });
  115. await page.getByRole('button', { name: '获取验证码', exact: true }).click();
  116. await page.getByRole('button', { name: '《服务协议》', exact: true }).click();
  117. await page.getByRole('button', { name: '返回', exact: true }).click();
  118. await page.keyboard.press('Tab');
  119. assert.ok(await page.evaluate(() => !!document.activeElement?.closest('[role="dialog"]')));
  120. check(kind + '-consent-cancel-return-focus');
  121. await agree(page);
  122. if (kind === 'mobile') await page.getByRole('heading', { name: '输入验证码', exact: true }).waitFor();
  123. await page.locator('input[name="code"]').fill('000000');
  124. await page.getByRole('button', { name: '登录', exact: true }).click();
  125. await page.getByRole('alert').filter({ hasText: '验证码已过期' }).waitFor();
  126. await snapshot(page, kind + '-code-expired');
  127. if (kind === 'mobile') {
  128. await page.getByRole('button', { name: '返回修改手机号', exact: true }).click();
  129. assert.ok((await page.getByRole('button', { name: /秒后可重新发送/ }).textContent()).includes('秒'));
  130. await page.getByRole('button', { name: '输入已收到的验证码', exact: true }).click();
  131. }
  132. await page.locator('input[name="code"]').fill('123456');
  133. } else if (method === 'password') {
  134. await page.getByRole('button', { name: kind === 'mobile' ? '账号密码登录' : '账号登录', exact: true }).click();
  135. await page.locator('input[name="username"]').fill('demo-login');
  136. await page.locator('input[name="password"]').fill('wrong-password');
  137. await page.getByRole('button', { name: '登录', exact: true }).click(); await agree(page);
  138. await page.getByRole('alert').filter({ hasText: '账号或密码不正确' }).waitFor();
  139. await snapshot(page, kind + '-password-error');
  140. await page.locator('input[name="password"]').fill('123456');
  141. } else {
  142. await page.getByRole('button', { name: kind === 'mobile' ? '登录凭证登录' : '快捷登录', exact: true }).click();
  143. await page.locator('input[name="token"]').fill('invalid-demo');
  144. assert.equal(await page.locator('input[name="token"]').getAttribute('type'), 'password');
  145. await page.getByRole('button', { name: '登录', exact: true }).click(); await agree(page);
  146. await page.getByRole('alert').filter({ hasText: '登录凭证已失效' }).waitFor();
  147. await snapshot(page, kind + '-token-error');
  148. await page.locator('input[name="token"]').fill('demo-fmode');
  149. }
  150. await page.getByRole('button', { name: '登录', exact: true }).click();
  151. await entered(page, kind + '-' + method + '-success');
  152. if (method === 'token') {
  153. await page.goto(origin + '/' + kind + '/mine', { waitUntil: 'networkidle' });
  154. const copy = page.getByRole('button', { name: kind === 'mobile' ? '复制登录凭证' : '复制', exact: true });
  155. assert.ok(await copy.isDisabled());
  156. await page.getByRole('button', { name: kind === 'mobile' ? '显示登录凭证' : '显示', exact: true }).click();
  157. await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async () => { throw new Error('isolated-test-denied'); } } }));
  158. await copy.click();
  159. await page.getByText('未能复制,请显示凭证后手动选中复制', { exact: true }).waitFor();
  160. check(kind + '-mine-copy-denied-visible-feedback');
  161. await page.evaluate(() => Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async () => undefined } }));
  162. await copy.click();
  163. await page.getByText('登录凭证已复制', { exact: true }).waitFor();
  164. check(kind + '-mine-copy-success-visible-feedback');
  165. }
  166. await context.close();
  167. }
  168. }
  169. const { page, context } = await open('desktop');
  170. await page.locator('input[name="phone"]').fill('a');
  171. assert.equal(await page.locator('input[name="phone"]').inputValue(), '');
  172. check('desktop-input-normalization-visible-value');
  173. await snapshot(page, 'desktop-phone');
  174. await page.getByRole('button', { name: '账号登录', exact: true }).click();
  175. await snapshot(page, 'desktop-password');
  176. await context.close();
  177. assert.deepEqual(report.errors, [], '页面出现未捕获错误');
  178. check('all-pages-no-uncaught-errors');
  179. report.pass = true;
  180. } catch (error) {
  181. report.pass = false; report.failure = { message: error.message, stack: error.stack };
  182. throw error;
  183. } finally {
  184. await writeFile(resolve(output, 'browser-review.json'), JSON.stringify(report, null, 2) + '\n');
  185. await writeFile(resolve(evidence, 'browser-review.json'), JSON.stringify(report, null, 2) + '\n');
  186. await browser.close();
  187. await new Promise(resolve => server.close(resolve));
  188. 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));
  189. }