Files
yun-xue-tang-assistant/dev/tests/points-api-probe.mjs
T
voidandClaude Sonnet 4.6 18c5e5a3be feat: 每日积分改以平台积分台账为准
- 新增 points-platform:读取 /ssp/#/my/point 背后的 rule/org 与 point/history/self
- 整门课完成不再直接 +3,等平台真的入账后按 nameType 归类计数
- 平台今日学习积分达到上限,或连续 3 门确有学习内容却未入账时收尾
- 接口不可用(未登录/跨域/网络)时退回本地计数,面板额外显示平台台账
- 新增离线回归测试与只读探测脚本

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-11-02 20:43:40 +08:00

271 lines
12 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* 只读探测:打开「我的积分」页,抓它真实调的接口与返回字段。
*
* node dev/tests/points-api-probe.mjs
*
* 用现有 profile 里的登录态(不登录、不点课程、不动进度),
* 打印 /ssp/#/my/point 加载期间与积分/学时相关的 XHR 响应,
* 以及页面渲染出来的文本,用来确认「今日获得多少积分」该读哪个字段。
*/
import path from 'node:path';
import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import { connect, httpJson, sleep } from '../../runner/cdp.mjs';
import { launchBrowser, resolveBrowser } from '../../runner/browser.mjs';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PORT = Number(process.env.YUN_XUE_TANG_CDP_PORT || 9340);
const ORIGIN = (process.env.YUN_XUE_TANG_ORIGIN || 'https://kfmic.yunxuetang.cn').replace(/\/+$/, '');
const TARGET = ORIGIN + '/ssp/#/my/point';
const LOGIN = ORIGIN + '/login.html';
const PROFILE = process.env.YUN_XUE_TANG_PROFILE_DIR
? path.resolve(ROOT, process.env.YUN_XUE_TANG_PROFILE_DIR)
: path.join(ROOT, '.run-profile');
const INTERESTING = /point|jf|score|credit|study|history|\/ssp\/rule|\/user\/point/i;
function trim(s, n = 1200) {
const t = String(s == null ? '' : s).replace(/\s+/g, ' ');
return t.length > n ? t.slice(0, n) + '…' : t;
}
async function main() {
console.log('[探测] 浏览器:' + resolveBrowser());
console.log('[探测] profile:' + PROFILE);
console.log('[探测] 页面:' + TARGET);
const browser = await launchBrowser({
binary: resolveBrowser(),
profileDir: PROFILE,
port: PORT,
headless: true,
log: (s) => console.log(s),
});
let cdp = null;
try {
const target = await httpJson(
'http://127.0.0.1:' + PORT + '/json/new?' + encodeURIComponent(LOGIN), 'PUT');
cdp = await connect(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Network.enable');
await cdp.send('Log.enable');
const reqs = new Map();
const hits = [];
const all = [];
cdp.onEvent((m) => {
if (m.method === 'Runtime.consoleAPICalled') {
const text = (m.params.args || []).map((a) => (a.value !== undefined ? a.value : a.description || '')).join(' ');
console.log('[console.' + m.params.type + '] ' + trim(text, 400));
return;
}
if (m.method === 'Log.entryAdded') {
console.log('[log.' + m.params.entry.level + '] ' + trim(m.params.entry.text, 400));
return;
}
if (m.method === 'Network.requestWillBeSent') {
const info = {
url: m.params.request.url,
method: m.params.request.method,
type: m.params.type,
headers: m.params.request.headers,
postData: m.params.request.postData,
};
reqs.set(m.params.requestId, info);
if (/XHR|Fetch/.test(info.type || '')) all.push(info);
return;
}
if (m.method === 'Network.responseReceived') {
const url = m.params.response.url || '';
if (!INTERESTING.test(url)) return;
const req = reqs.get(m.params.requestId) || {};
if (req.type && !/XHR|Fetch/.test(req.type)) return;
hits.push({
requestId: m.params.requestId,
url: url,
method: req.method || '',
status: m.params.response.status,
mime: m.params.response.mimeType,
headers: req.headers || {},
postData: req.postData || '',
});
}
});
await sleep(6000);
// 只登录,不启动刷课:注入脚本后自己填表 + 点「登录」,并清掉「登录后自动刷课」标记。
const usr = process.env.YUN_XUE_TANG_USR || '';
const pwd = process.env.YUN_XUE_TANG_PWD || '';
const scriptSrc = fs.readFileSync(path.join(ROOT, 'yun-xue-tang-assistant.user.js'), 'utf8');
await cdp.send('Runtime.evaluate', { expression: scriptSrc });
await sleep(1200);
const filled = await cdp.send('Runtime.evaluate', {
expression: `(function () {
var a = window.__yunXueTangAuto;
if (!a) return 'no-api';
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
var ok = a.fillLoginForm(${JSON.stringify(usr)}, ${JSON.stringify(pwd)});
try { a.checkLoginAgreement(); } catch (e) {}
try { a.doLoginAndStart(); } catch (e) {}
// doLoginAndStart 会写「登录后自动刷课」标记;这里立刻清掉,保证只登录不刷课
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
try { a.S.batchRunning = false; } catch (e) {}
return ok ? 'submitted' : 'no-fields';
})()`,
returnByValue: true,
});
console.log('[登录] 结果:' + filled.result.value);
await sleep(12000);
// 保险:登录页若把「自动刷课」标记写进 localStorage,这里再清一次并停批量
await cdp.send('Runtime.evaluate', {
expression: `(function () {
try { localStorage.removeItem('yun-xue-tang-auto-start-after-login'); } catch (e) {}
var a = window.__yunXueTangAuto;
if (a) { try { a.S.batchRunning = false; a.S.batchFinished = false; } catch (e) {} }
return true;
})()`,
});
hits.length = 0;
all.length = 0;
await cdp.send('Page.navigate', { url: TARGET });
await sleep(25000);
const state = await cdp.send('Runtime.evaluate', {
expression: `JSON.stringify((function () {
function findTok(s) {
try {
for (var i = 0; i < s.length; i++) {
var k = s.key(i), v = s.getItem(k) || '';
if (/eyJ[a-zA-Z0-9_-]{10,}/.test(v)) return k;
}
} catch (e) {}
return '';
}
return {
href: location.href,
ready: document.readyState,
appLen: (document.getElementById('app') || {}).innerHTML ? document.getElementById('app').innerHTML.length : 0,
ls: Object.keys(localStorage || {}),
ss: Object.keys(sessionStorage || {}),
lsTok: findTok(localStorage),
ssTok: findTok(sessionStorage),
cookies: String(document.cookie || '').split(';').map(function (s) { return s.split('=')[0].trim(); }),
};
})())`,
returnByValue: true,
}).then((r) => JSON.parse(r.result.value || '{}')).catch(() => ({}));
console.log('\n[状态] ' + JSON.stringify(state));
const info = await cdp.send('Runtime.evaluate', {
expression: 'JSON.stringify({ href: location.href, title: document.title, text: document.body ? document.body.innerText : "" })',
returnByValue: true,
}).then((r) => JSON.parse(r.result.value || '{}')).catch(() => ({}));
console.log('\n[页面] ' + info.href + ' title=' + info.title);
console.log('[页面文本] ' + trim(info.text, 800));
// 用构建产物自己的平台台账逻辑再拉一次,验证 token / CORS / 折算链路
if (state.lsTok) {
await cdp.send('Runtime.evaluate', { expression: scriptSrc });
await sleep(1200);
const ledger = await cdp.send('Runtime.evaluate', {
expression: `(async function () {
var tk = localStorage.getItem('token') || '';
var h = { 'Content-Type': 'application/json;charset=UTF-8', source: '501', 'x-yxt-product': 'xxv2', token: tk };
var d0 = new Date();
var p2 = function (n) { return n < 10 ? '0' + n : '' + n; };
var day = d0.getFullYear() + '-' + p2(d0.getMonth() + 1) + '-' + p2(d0.getDate());
var body = JSON.stringify({
startDate: day + ' 00:00:00', endDate: day + ' 23:59:59',
sourceType: -1, optionType: 0, type: 1, userId: ''
});
var out = {};
async function probe(name, url, opts) {
try {
var r = await fetch(url, opts);
out[name] = { status: r.status, body: (await r.text()).slice(0, 400) };
} catch (e) { out[name] = { error: String(e) }; }
}
await probe('rules', 'https://api-phx-tc.yunxuetang.cn/ssp/rule/org', { headers: h });
await probe('rulesQ', 'https://api-phx-tc.yunxuetang.cn/ssp/rule/org?0=' + Math.random(), { headers: h });
await probe('ledger', 'https://api-phx-tc.yunxuetang.cn/ssp/point/history/self?limit=200&offset=0', { method: 'POST', headers: h, body: body });
// 统计历史台账里 nameType / actionType 的分布,判断能否据此归类
try {
var wide = JSON.stringify({
startDate: '2025-01-01 00:00:00', endDate: d0.getFullYear() + '-12-31 23:59:59',
sourceType: -1, optionType: 0, type: 1, userId: ''
});
var lr = await fetch('https://api-phx-tc.yunxuetang.cn/ssp/point/history/self?limit=200&offset=0', { method: 'POST', headers: h, body: wide });
var lj = await lr.json();
var combos = {};
for (var rec of (lj.datas || [])) {
if (Number(rec.sourceType) !== 1002) continue;
var k = [rec.nameType, rec.actionType, rec.point].join('/');
if (!combos[k]) combos[k] = { n: 0, samples: [] };
combos[k].n++;
if (combos[k].samples.length < 3) combos[k].samples.push(String(rec.remark || '').slice(0, 40));
}
out.combos = combos;
} catch (e) { out.combos = { error: String(e) }; }
var a = window.__yunXueTangAuto;
if (a) {
var d = await a.refreshPlatformPoints(a.points, { force: true });
out.platform = {
ok: d.ok, todayPoints: d.todayPoints, maxPoints: d.maxPoints, rules: d.rules,
recordCount: d.records ? d.records.length : 0, reason: d.reason,
};
out.counts = a.points.snapshot();
}
return JSON.stringify(out);
})()`,
awaitPromise: true,
returnByValue: true,
});
console.log('\n[台账] ' + trim(ledger.result.value, 3000));
}
console.log('\n[XHR/Fetch] 共 ' + all.length + ' 条:');
const seen = new Set();
for (const r of all) {
if (seen.has(r.url)) continue;
seen.add(r.url);
console.log(' ' + r.method + ' ' + r.url);
}
console.log('\n[接口] 命中 ' + hits.length + ' 条:'); for (const h of hits) {
console.log('\n--- ' + h.method + ' ' + h.status + ' ' + h.url);
const hdr = h.headers || {};
for (const [k, v] of Object.entries(hdr)) {
console.log(' ' + k + ': ' + String(v).slice(0, 120));
}
if (h.postData) console.log(' body: ' + trim(h.postData, 600));
try {
const body = await cdp.send('Network.getResponseBody', { requestId: h.requestId });
const text = body.base64Encoded ? Buffer.from(body.body, 'base64').toString('utf8') : body.body;
console.log(trim(text, 4000));
} catch (e) {
console.log('(响应体不可读:' + e.message + ')');
}
}
const res = await cdp.send('Runtime.evaluate', {
expression: `JSON.stringify(performance.getEntriesByType('resource').map(function(e){return e.name;}).filter(function(u){return ${INTERESTING}.test(u);}))`,
returnByValue: true,
}).then((r) => JSON.parse(r.result.value || '[]')).catch(() => []);
console.log('\n[资源] ' + res.length + ' 条');
for (const u of res.slice(0, 60)) console.log(' ' + u);
} finally {
if (cdp) cdp.close();
await browser.kill();
}
}
main().catch((e) => {
console.error('[失败] ' + (e && e.stack ? e.stack : e));
process.exit(1);
});