#!/usr/bin/env node /** * 真机测试:真实 Chrome + 真实 https://kfmic.yunxuetang.cn 页面。 * * 做法:启动一个独立用户目录的 Chrome(不碰你日常配置),通过 CDP 把打包产物 * yun-xue-tang-assistant.user.js 注入页面主世界——这与 Tampermonkey 在 * @grant none 下的执行环境一致,所以断言的是脚本在真实浏览器 / 真实站点 * DOM 上的行为,而不是 Node 里的 DOM 桩。 * * 用法: * node dev/real-test.mjs 有界面浏览器(默认,最接近真机) * node dev/real-test.mjs --headless 无头模式(CI 用) * node dev/real-test.mjs --keep 跑完不关浏览器(便于人工肉眼复核) * * 环境变量: * YUN_XUE_TANG_CHROME Chrome/Edge 可执行文件路径 * YUN_XUE_TANG_CDP_PORT 调试端口,默认 9333 * YUN_XUE_TANG_URL 起始页面,默认 https://kfmic.yunxuetang.cn/login.html * YUN_XUE_TANG_SHOT_DIR 截图目录,默认 docs/screenshots * * 需要 Node 22+(用到全局 WebSocket 与 fetch);只做只读探测: * 不填写账号密码、不点登录、不修改线上数据。 */ import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import { spawn } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { connect, sleep, httpJson, findChrome, forceHeadless, safetyArgs } from './real-cdp.mjs'; const HERE = path.dirname(fileURLToPath(import.meta.url)); const ROOT = path.resolve(HERE, '..'); const SCRIPT_FILE = path.join(ROOT, 'yun-xue-tang-assistant.user.js'); const SCRIPT_SRC = fs.readFileSync(SCRIPT_FILE, 'utf8'); const CANDIDATES = [ process.env.YUN_XUE_TANG_CHROME, 'C:/Program Files/Google/Chrome/Application/chrome.exe', 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe', 'C:/Program Files/Microsoft/Edge/Application/msedge.exe', 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe', '/usr/bin/google-chrome', '/usr/bin/chromium', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', ].filter(Boolean); const CHROME = findChrome(CANDIDATES); const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9333); const START_URL = process.env.YUN_XUE_TANG_URL || 'https://kfmic.yunxuetang.cn/login.html'; const HEADLESS = process.env.YUN_XUE_TANG_HEADLESS === '1' || process.argv.includes('--headless'); const KEEP = process.env.YUN_XUE_TANG_KEEP === '1' || process.argv.includes('--keep'); const SHOT_DIR = process.env.YUN_XUE_TANG_SHOT_DIR || path.join(ROOT, 'docs/screenshots'); const results = []; const consoleLogs = []; const log = (...a) => console.log(...a); function check(name, ok, detail) { results.push({ name, ok: !!ok, detail }); log((ok ? ' PASS ' : ' FAIL ') + name + (detail === undefined ? '' : ' → ' + JSON.stringify(detail))); } if (typeof WebSocket !== 'function' || typeof fetch !== 'function') { console.error('需要 Node 22 及以上(依赖全局 WebSocket / fetch),当前 ' + process.version); process.exit(2); } if (!CHROME) { console.error('找不到 Chrome/Edge,可用 YUN_XUE_TANG_CHROME=/path/to/chrome 指定'); process.exit(2); } if (!fs.existsSync(SCRIPT_FILE)) { console.error('缺少构建产物,先运行 npm run build'); process.exit(2); } // Linux 无图形化服务器:没有 DISPLAY 时强制无头,并补容器/root 必需参数 const HEADLESS_ONLY = HEADLESS || forceHeadless(); const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'yun-xue-tang-chrome-')); const args = [ `--remote-debugging-port=${PORT}`, `--user-data-dir=${userDataDir}`, '--no-first-run', '--no-default-browser-check', '--disable-sync', '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows', '--window-size=1280,900', ].concat(safetyArgs(), ['about:blank']); if (HEADLESS_ONLY) args.unshift('--headless=new'); let chrome = null; let cdp = null; try { log('[真机] 浏览器:' + CHROME + (HEADLESS_ONLY ? '(headless=new)' : '(有界面)')); chrome = spawn(CHROME, args, { stdio: 'ignore', windowsHide: true }); // ---- 1. 等 CDP 就绪 ---- let version = null; for (let i = 0; i < 100; i++) { try { const v = await httpJson(`http://127.0.0.1:${PORT}/json/version`); if (v && v.webSocketDebuggerUrl) { version = v; break; } } catch (e) { /* 还没起来 */ } await sleep(250); } if (!version) throw new Error('Chrome CDP 端口未就绪(' + PORT + ')'); check('真实浏览器进程启动', /^(Chrome|HeadlessChrome|Edg)\//.test(version.Browser || ''), version.Browser); // ---- 2. 打开真实页面 ---- const target = await httpJson(`http://127.0.0.1:${PORT}/json/new?${encodeURIComponent(START_URL)}`, 'PUT'); cdp = await connect(target.webSocketDebuggerUrl); await cdp.send('Page.enable'); await cdp.send('Runtime.enable'); await cdp.send('Log.enable'); await cdp.send('Network.enable'); cdp.onEvent((m) => { if (m.method === 'Runtime.consoleAPICalled') { const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' '); consoleLogs.push({ type: m.params.type, text: String(text) }); } else if (m.method === 'Log.entryAdded') { consoleLogs.push({ type: m.params.entry.level, text: m.params.entry.text }); } }); const evalJS = async (expr) => { const r = await cdp.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true, userGesture: true, }); if (r.exceptionDetails) { const d = r.exceptionDetails; throw new Error((d.exception && d.exception.description) || d.text); } return r.result.value; }; const json = async (expr) => JSON.parse(await evalJS(expr)); const loaded = cdp.waitEvent('Page.loadEventFired', 45000).catch(() => null); await cdp.send('Page.navigate', { url: START_URL }); await loaded; await sleep(1800); const page = await json(`JSON.stringify({ url: location.href, title: document.title, host: location.host, ua: navigator.userAgent })`); log('[真机] 页面:' + page.url); log('[真机] 标题:' + page.title); check('落在真实云学堂页面', /(^|\.)yunxuetang\.cn$/.test(page.host), page.host); check('真实浏览器内核', /Chrome\//.test(page.ua), page.ua.slice(0, 96) + '…'); // ---- 3. 注入(等价 Tampermonkey @grant none 主世界执行)---- check('注入前页面无残留实例', (await evalJS('typeof window.__yunXueTangAuto')) === 'undefined', await evalJS('typeof window.__yunXueTangAuto')); await evalJS(SCRIPT_SRC); await sleep(1200); const loadedLog = consoleLogs.find((l) => /云学堂助手 v[\d.]+ 已加载/.test(l.text)); check('控制台打印加载日志', !!loadedLog, loadedLog && loadedLog.text); // ---- 4. 面板在真实 DOM 里的渲染 ---- const panel = await json(`JSON.stringify((() => { const el = document.getElementById('yun-xue-tang-panel'); if (!el) return null; const r = el.getBoundingClientRect(); const cs = getComputedStyle(el); return { version: (document.getElementById('yun-xue-tang-version') || {}).textContent || '', w: Math.round(r.width), h: Math.round(r.height), right: Math.round(innerWidth - r.right), bottom: Math.round(innerHeight - r.bottom), visible: cs.display !== 'none' && cs.visibility !== 'hidden' && Number(cs.opacity) > 0, position: cs.position, zIndex: cs.zIndex, buttons: [...el.querySelectorAll('button')].map((b) => b.textContent.trim()), inputTypes: [...el.querySelectorAll('input')].map((i) => i.type), text: el.innerText.replace(/\\s+/g, ' ').trim().slice(0, 220), }; })())`); check('面板渲染进真实 DOM 且可见', panel && panel.visible && panel.w > 0 && panel.h > 0, panel && { 宽: panel.w, 高: panel.h, position: panel.position, zIndex: panel.zIndex }); check('面板版本号 v2.7.0', panel && panel.version === 'v2.7.0', panel && panel.version); check('固定在右下角', panel && panel.right >= 0 && panel.right < 40 && panel.bottom >= 0 && panel.bottom < 40, panel && { 距右: panel.right, 距下: panel.bottom }); check('面板含按钮与密码框', panel && panel.buttons.length >= 2 && panel.inputTypes.includes('password'), panel && { 按钮: panel.buttons, 输入框: panel.inputTypes }); // ---- 5. 真实页面上调试入口 / 页面识别 ---- const api = await json(`JSON.stringify((() => { const a = window.__yunXueTangAuto; if (!a) return null; return { keys: Object.keys(a).length, route: a.route(), isLoginPage: a.isLoginPage(), hasDispose: typeof window.__yunXueTangDispose === 'function', courseId: a.courseIdFromUrl(), summary: a.readSummary(), countdown: a.readCountdown(), }; })())`); check('window.__yunXueTangAuto 调试入口存在', !!api && api.keys > 20, api && { 导出项: api.keys }); check('真实登录页被正确识别', api && api.isLoginPage === true, api && { route: api.route, isLoginPage: api.isLoginPage }); check('__yunXueTangDispose 可用(热替换前提)', api && api.hasDispose === true, api && api.hasDispose); check('登录页上 readSummary/readCountdown 安全返回 null', api && api.summary === null && api.countdown === null, api && { summary: api.summary, countdown: api.countdown }); // ---- 6. 真实点击面板按钮(不填账号,只验证不崩)---- const click = await json(`JSON.stringify((() => { const panel = document.getElementById('yun-xue-tang-panel'); const btn = document.getElementById('yun-xue-tang-oneclick'); if (!btn) return { error: 'no #yun-xue-tang-oneclick' }; btn.click(); return { label: btn.textContent.trim(), panelVisibleAfter: getComputedStyle(panel).display !== 'none', statusLine: (document.getElementById('yun-xue-tang-status') || {}).textContent || '', panelText: panel.innerText.replace(/\\s+/g, ' ').slice(0, 200), }; })())`); await sleep(800); const afterClick = await json(`JSON.stringify(({ url: location.href, alive: typeof window.__yunXueTangAuto, panel: !!document.getElementById('yun-xue-tang-panel'), }))`); check('点击「一键登录并刷课」不崩溃', afterClick.alive === 'object' && afterClick.panel === true, { 点击前标签: click.label, ...afterClick }); const scriptErrors = () => consoleLogs.filter((l) => l.type === 'error' && /云学堂助手/.test(l.text)); check('无脚本自身 error 日志', scriptErrors().length === 0, scriptErrors().map((e) => e.text.slice(0, 140))); // ---- 7. 真实 localStorage 读写 ---- const ls = await json(`JSON.stringify((() => { const before = localStorage.getItem('yun-xue-tang-auto-play-enabled'); localStorage.setItem('yun-xue-tang-auto-play-enabled', '0'); const read = localStorage.getItem('yun-xue-tang-auto-play-enabled'); if (before === null) localStorage.removeItem('yun-xue-tang-auto-play-enabled'); else localStorage.setItem('yun-xue-tang-auto-play-enabled', before); return { read, keys: Object.keys(localStorage).filter((k) => k.indexOf('yun-xue-tang-') === 0) }; })())`); check('真实 localStorage 可读写', ls.read === '0', ls); // ---- 8. 真实热替换:dispose → 重新注入 ---- const hot = await json(`JSON.stringify((() => { window.__yunXueTangDispose(); return { panel: !!document.getElementById('yun-xue-tang-panel'), api: typeof window.__yunXueTangAuto, dispose: typeof window.__yunXueTangDispose }; })())`); await evalJS(SCRIPT_SRC); await sleep(900); const hot2 = await json(`JSON.stringify({ count: document.querySelectorAll('#yun-xue-tang-panel').length, api: typeof window.__yunXueTangAuto, version: (document.getElementById('yun-xue-tang-version') || {}).textContent, timers: 'n/a', })`); check('dispose 后真实 DOM 面板被移除', hot.panel === false && hot.api === 'undefined', hot); check('重新注入后面板唯一且版本正确', hot2.count === 1 && hot2.api === 'object' && hot2.version === 'v2.7.0', hot2); // ---- 9. 截图存证 ---- try { fs.mkdirSync(SHOT_DIR, { recursive: true }); const shot = await cdp.send('Page.captureScreenshot', { format: 'png' }); const file = path.join(SHOT_DIR, 'real-chrome-login.png'); fs.writeFileSync(file, Buffer.from(shot.data, 'base64')); const size = fs.statSync(file).size; check('真机截图已保存', size > 5000, path.relative(ROOT, file) + ' (' + size + ' 字节)'); } catch (e) { check('真机截图已保存', false, e.message); } // ---- 10. SPA 内 hash 路由(不换 document):脚本靠 hashchange 自更新,不需要重新注入 ---- const hashNav = await json(`JSON.stringify((() => { location.hash = '#/list'; return { hash: location.hash, route: window.__yunXueTangAuto.route(), panel: !!document.getElementById('yun-xue-tang-panel') }; })())`); await sleep(600); const hashAfter = await json(`JSON.stringify({ hash: location.hash, route: window.__yunXueTangAuto.route(), alive: typeof window.__yunXueTangAuto })`); check('SPA 内 hash 切换后脚本自动跟随路由', hashAfter.route === 'list' && hashAfter.alive === 'object', { 切前: hashNav, 切后: hashAfter }); // ---- 11. 未登录访问 #/list:站点整页重定向到登录页(新 document)---- // 真实 Tampermonkey 会在新 document 上按 @match 重新注入,这里同样重新注入后再断言。 // 先订阅 load 事件再触发跳转,避免竞态。 const redirected = cdp.waitEvent('Page.loadEventFired', 30000).catch(() => null); await evalJS(`(() => { window.__yunXueTangDocMarker = 'before-nav'; location.href = 'https://kfmic.yunxuetang.cn/kng/#/list'; return true; })()`); await redirected; await sleep(2500); const afterNav = await json(`JSON.stringify({ url: location.href, host: location.host, title: document.title, newDocument: window.__yunXueTangDocMarker === undefined, alive: typeof window.__yunXueTangAuto, })`); check('未登录访问 #/list 被站点重定向(document 已换新)', /(^|\.)yunxuetang\.cn$/.test(afterNav.host) && afterNav.newDocument === true, afterNav); check('新 document 上脚本未残留(重定向后必须重新注入)', afterNav.alive === 'undefined', afterNav.alive); // 模拟 Tampermonkey 在新 document 上按 @match 自动注入 await evalJS(SCRIPT_SRC); await sleep(1200); const reinjected = await json(`JSON.stringify({ url: location.href, route: window.__yunXueTangAuto ? window.__yunXueTangAuto.route() : 'no-api', isLoginPage: window.__yunXueTangAuto ? window.__yunXueTangAuto.isLoginPage() : null, panel: document.querySelectorAll('#yun-xue-tang-panel').length, version: (document.getElementById('yun-xue-tang-version') || {}).textContent, bodyScrollable: document.body.scrollHeight > 0, })`); check('重定向后重新注入:面板唯一且脚本正常', reinjected.panel === 1 && reinjected.version === 'v2.7.0' && reinjected.route !== 'no-api', reinjected); check('列表页导航无脚本报错', scriptErrors().length === 0, scriptErrors().map((e) => e.text.slice(0, 140))); // ---- 汇总控制台 ---- log('\n[真机] 控制台共 ' + consoleLogs.length + ' 条,最后 15 条:'); for (const l of consoleLogs.slice(-15)) log(' [' + l.type + '] ' + l.text.slice(0, 170)); } catch (e) { check('真机流程执行完毕', false, e && e.stack ? e.stack.split('\n').slice(0, 4).join(' | ') : String(e)); } finally { if (cdp && !KEEP) cdp.close(); if (chrome && !KEEP) { try { chrome.kill(); } catch (e) {} } if (!KEEP) { await sleep(600); try { fs.rmSync(userDataDir, { recursive: true, force: true }); } catch (e) {} } else { log('[真机] YUN_XUE_TANG_KEEP=1,浏览器保持打开:' + userDataDir); } } const failed = results.filter((r) => !r.ok); log('\n===== 真机结果:' + (results.length - failed.length) + '/' + results.length + ' 通过,失败 ' + failed.length + ' ====='); for (const f of failed) log(' FAIL ' + f.name + ' → ' + JSON.stringify(f.detail)); process.exit(failed.length ? 1 : 0);