CaiWuXiTong/scripts/hxb-bank/export-daily.mjs

645 lines
21 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.

import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import {
CDP,
evaluate,
goto,
launchEdge,
openPage,
setDownloadDir,
shot,
sleep,
} from '../erp-daily-bills/cdp.mjs';
const BASE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(BASE, '../..');
const LOGIN_URL = 'https://trecloud.hxb.com.cn/login';
const ACCOUNT_DETAIL_URL = 'https://trecloud.hxb.com.cn/muti-bank-account/accountDetail';
const PROFILE = path.join(ROOT, 'runtime/private/hxb-bank-edge-profile-full');
const PORT = 9341;
function ensureAutomationProfile() {
const sourceRoot = path.join(process.env.LOCALAPPDATA || '', 'Microsoft/Edge/User Data');
const sourceDefault = path.join(sourceRoot, 'Default');
const targetDefault = path.join(PROFILE, 'Default');
const extensionId = 'biphcfgechkjmfglclhgjaaomdgfidfp';
const targetExtension = path.join(targetDefault, 'Extensions', extensionId);
if (fs.existsSync(targetExtension)) return;
const sourceExtension = path.join(sourceDefault, 'Extensions', extensionId);
if (!fs.existsSync(sourceExtension)) {
throw new Error('常用 Edge 配置中未安装华夏银行密码扩展');
}
fs.mkdirSync(targetDefault, { recursive: true });
for (const file of ['Local State']) {
const source = path.join(sourceRoot, file);
if (fs.existsSync(source)) fs.copyFileSync(source, path.join(PROFILE, file));
}
for (const name of ['Preferences', 'Secure Preferences', 'Extension State', 'Local Extension Settings']) {
const source = path.join(sourceDefault, name);
if (fs.existsSync(source)) {
fs.cpSync(source, path.join(targetDefault, name), { recursive: true, force: true });
}
}
fs.cpSync(path.join(sourceDefault, 'Extensions'), path.join(targetDefault, 'Extensions'), {
recursive: true,
force: true,
});
}
const arg = (name, fallback = null) => {
const hit = process.argv.find((item) => item.startsWith(`--${name}=`));
return hit ? hit.slice(name.length + 3) : fallback;
};
const formatDate = (date) => [
date.getFullYear(),
String(date.getMonth() + 1).padStart(2, '0'),
String(date.getDate()).padStart(2, '0'),
].join('-');
const datePattern = /^\d{4}-\d{2}-\d{2}$/;
const fromDate = arg('from', formatDate(new Date(Date.now() - 86400000)));
const toDate = arg('to', formatDate(new Date()));
const phone = String(process.env.HXB_PHONE || '').trim();
const password = String(process.env.HXB_PASSWORD || '');
const webhook = String(process.env.HXB_DINGTALK_WEBHOOK || '').trim();
const relayBase = String(process.env.HXB_OTP_RELAY_BASE || '').replace(/\/+$/, '');
const relaySecret = String(process.env.HXB_OTP_RELAY_SECRET || '').trim();
const outputRoot = path.resolve(arg(
'out',
path.join(ROOT, 'runtime/private/hxb-bank-exports', `${fromDate}_${toDate}`),
));
const runStamp = new Date().toISOString().replace(/\D/g, '').slice(0, 14);
const runDirectory = path.join(outputRoot, `run-${runStamp}`);
const downloadDirectory = path.join(runDirectory, 'downloads');
const stateFile = path.join(runDirectory, 'last-export.json');
if (!datePattern.test(fromDate) || !datePattern.test(toDate) || fromDate > toDate) {
throw new Error('日期范围无效');
}
if (!phone || !password) {
throw new Error('缺少华夏银行登录手机号或密码');
}
if (!/^https:\/\/oapi\.dingtalk\.com\/robot\/send\?access_token=[0-9a-f]+$/.test(webhook)) {
throw new Error('缺少有效的钉钉群机器人 Webhook');
}
if (!/^https:\/\//.test(relayBase) || relaySecret.length < 32) {
throw new Error('缺少华夏验证码中继地址或密钥');
}
fs.mkdirSync(downloadDirectory, { recursive: true });
function sanitizeError(error) {
return String(error?.message || error)
.replace(/https:\/\/oapi\.dingtalk\.com\/robot\/send\?access_token=[0-9a-f]+/gi, '[webhook]')
.replace(/\b1[3-9]\d{9}\b/g, '[phone]')
.slice(0, 600);
}
function listFiles(directory) {
if (!fs.existsSync(directory)) return [];
return fs.readdirSync(directory)
.map((name) => path.join(directory, name))
.filter((file) => fs.statSync(file).isFile());
}
function hasCompleteZip(file) {
try {
const bytes = fs.readFileSync(file);
return bytes.length > 22
&& bytes.subarray(0, 4).equals(Buffer.from([0x50, 0x4b, 0x03, 0x04]))
&& bytes.includes(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
} catch {
return false;
}
}
async function waitFor(check, description, timeoutMs = 60000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const result = await check();
if (result) return result;
await sleep(700);
}
throw new Error(`${description}超时`);
}
async function bodyText(cdp, sessionId) {
return evaluate(cdp, sessionId, '(document.body?.innerText || "")');
}
async function pageState(cdp, sessionId) {
return evaluate(cdp, sessionId, `({
url: location.href,
title: document.title,
text: document.body?.innerText || '',
hasUsername: (() => {
const el = document.querySelector('#username');
return !!(el && (el.offsetWidth || el.offsetHeight));
})(),
hasPassword: (() => {
const el = document.querySelector('#SecEditBox1');
return !!(el && (el.offsetWidth || el.offsetHeight));
})(),
hasCaptcha: (() => {
const el = document.querySelector('input[name="captcha"]');
return !!(el && (el.offsetWidth || el.offsetHeight));
})()
})`);
}
async function findPoint(cdp, sessionId, expression) {
return evaluate(cdp, sessionId, `(() => {
const el = (${expression});
if (!el || !(el.offsetWidth || el.offsetHeight)) return null;
el.scrollIntoView({ block: 'center', inline: 'center' });
const rect = el.getBoundingClientRect();
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
})()`);
}
async function clickPoint(cdp, sessionId, point) {
if (!point) return false;
await cdp.send('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: point.x,
y: point.y,
button: 'left',
clickCount: 1,
}, sessionId);
await cdp.send('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: point.x,
y: point.y,
button: 'left',
clickCount: 1,
}, sessionId);
return true;
}
async function clickSelector(cdp, sessionId, selector, index = 0) {
return clickPoint(cdp, sessionId, await findPoint(
cdp,
sessionId,
`[...document.querySelectorAll(${JSON.stringify(selector)})][${index}]`,
));
}
async function clickText(cdp, sessionId, text, { contains = false, selectors = 'button,a,[role="button"],span,div' } = {}) {
return clickPoint(cdp, sessionId, await findPoint(
cdp,
sessionId,
`[...document.querySelectorAll(${JSON.stringify(selectors)})]
.find((el) => {
const label = (el.innerText || el.value || '').replace(/\\s+/g, '');
return ${contains ? 'label.includes' : 'label === '}(${JSON.stringify(String(text).replace(/\s+/g, ''))});
})`,
));
}
function typeSecureTextWithWindows(value) {
const result = spawnSync(
'powershell.exe',
[
'-NoProfile',
'-ExecutionPolicy',
'Bypass',
'-File',
path.join(BASE, 'send-secure-text.ps1'),
],
{
windowsHide: true,
encoding: 'utf8',
timeout: 20000,
env: {
...process.env,
CAIWU_SECURE_INPUT: value,
},
},
);
if (result.status !== 0) {
throw new Error('银行密码无法通过 Windows 安全键盘输入');
}
}
async function clearFocusedField(cdp, sessionId) {
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown',
key: 'Control',
code: 'ControlLeft',
windowsVirtualKeyCode: 17,
nativeVirtualKeyCode: 17,
modifiers: 2,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown',
key: 'a',
code: 'KeyA',
text: 'a',
windowsVirtualKeyCode: 65,
nativeVirtualKeyCode: 65,
modifiers: 2,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: 'a',
code: 'KeyA',
windowsVirtualKeyCode: 65,
nativeVirtualKeyCode: 65,
modifiers: 2,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: 'Control',
code: 'ControlLeft',
windowsVirtualKeyCode: 17,
nativeVirtualKeyCode: 17,
}, sessionId);
for (let attempt = 0; attempt < 20; attempt++) {
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown',
key: 'Backspace',
code: 'Backspace',
windowsVirtualKeyCode: 8,
nativeVirtualKeyCode: 8,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: 'Backspace',
code: 'Backspace',
windowsVirtualKeyCode: 8,
nativeVirtualKeyCode: 8,
}, sessionId);
}
}
async function pressEnter(cdp, sessionId) {
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown',
key: 'Enter',
code: 'Enter',
windowsVirtualKeyCode: 13,
nativeVirtualKeyCode: 13,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: 'Enter',
code: 'Enter',
windowsVirtualKeyCode: 13,
nativeVirtualKeyCode: 13,
}, sessionId);
}
async function waitForLoginPage(cdp, sessionId) {
for (let attempt = 0; attempt < 18; attempt++) {
const state = await pageState(cdp, sessionId);
if (state.hasUsername && state.hasPassword) return state;
if (/\/dashboard(?:\?|$)/.test(new URL(state.url).pathname + (new URL(state.url).search || ''))) {
return state;
}
if (attempt > 0 && attempt % 4 === 0) {
await cdp.send('Page.reload', {}, sessionId);
}
await sleep(2000);
}
throw new Error('华夏银行登录页控件未加载');
}
async function createOtpRelayRequest() {
const requestPath = '/api/hxb-verification/requests';
const body = JSON.stringify({ client_run_id: crypto.randomUUID() });
const timestamp = String(Math.floor(Date.now() / 1000));
const nonce = crypto.randomBytes(16).toString('hex');
const canonical = [
'POST',
requestPath.replace(/^\/+/, ''),
timestamp,
nonce,
crypto.createHash('sha256').update(body, 'utf8').digest('hex'),
].join('\n');
const signature = crypto.createHmac('sha256', relaySecret).update(canonical, 'utf8').digest('hex');
const response = await fetch(relayBase + requestPath, {
method: 'POST',
headers: {
'content-type': 'application/json; charset=utf-8',
'X-HXB-Timestamp': timestamp,
'X-HXB-Nonce': nonce,
'X-HXB-Signature': signature,
},
body,
cache: 'no-store',
signal: AbortSignal.timeout(20000),
});
const result = await response.json().catch(() => ({}));
if (!response.ok || !result.fill_url || !result.poll_token || !result.run_id) {
throw new Error(`验证码填写链接生成失败:${result.message || response.status}`);
}
return result;
}
async function waitForRelayOtp(challenge, timeoutMs = 240000) {
const deadline = Date.now() + timeoutMs;
const pollUrl = relayBase
+ '/api/hxb-verification/requests/'
+ encodeURIComponent(String(challenge.run_id))
+ '/code';
while (Date.now() < deadline) {
const response = await fetch(pollUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${challenge.poll_token}`,
},
cache: 'no-store',
signal: AbortSignal.timeout(15000),
});
const result = await response.json().catch(() => ({}));
if (response.status === 200 && /^\d{6}$/.test(String(result.code || ''))) {
return String(result.code);
}
if (response.status === 202) {
await sleep(1000);
continue;
}
if (response.status === 410) {
throw new Error('华夏验证码填写链接已过期,请重新运行任务');
}
throw new Error(`华夏验证码读取失败:${result.message || response.status}`);
}
throw new Error('等待华夏验证码填写超时');
}
async function postDingTalkPrompt(fillUrl) {
const response = await fetch(webhook, {
method: 'POST',
headers: { 'content-type': 'application/json; charset=utf-8' },
body: JSON.stringify({
msgtype: 'actionCard',
actionCard: {
title: '华夏银行验证码填写',
text: '请接收验证码。华夏银行短信验证码已发送,请点击下方按钮填写;链接 5 分钟内有效且只能提交一次。',
btnOrientation: '0',
singleTitle: '填写华夏验证码',
singleURL: fillUrl,
},
}),
signal: AbortSignal.timeout(20000),
});
const result = await response.json().catch(() => ({}));
if (!response.ok || Number(result.errcode) !== 0) {
throw new Error(`钉钉群提示发送失败:${result.errmsg || response.status}`);
}
}
async function loginIfNeeded(cdp, sessionId) {
await goto(cdp, sessionId, LOGIN_URL);
await cdp.send('Page.bringToFront', {}, sessionId);
await sleep(300);
const loginState = await waitForLoginPage(cdp, sessionId);
if (/\/dashboard/.test(loginState.url)) return;
if (!await clickSelector(cdp, sessionId, '#username')) {
throw new Error('未找到手机号输入框');
}
await clearFocusedField(cdp, sessionId);
await cdp.send('Input.insertText', { text: phone }, sessionId);
if (!await clickSelector(cdp, sessionId, '#SecEditBox1')) {
throw new Error('未找到密码输入框');
}
await clearFocusedField(cdp, sessionId);
await sleep(250);
typeSecureTextWithWindows(password);
await sleep(500);
const otpChallenge = await createOtpRelayRequest();
await cdp.send('Page.bringToFront', {}, sessionId);
await sleep(300);
if (!await clickText(cdp, sessionId, '发送验证码', { selectors: 'button' })) {
throw new Error('未找到发送验证码按钮');
}
await waitFor(async () => /秒后重发/.test(await bodyText(cdp, sessionId)), '短信验证码发送', 15000);
await postDingTalkPrompt(otpChallenge.fill_url);
const otp = await waitForRelayOtp(otpChallenge);
if (!await clickSelector(cdp, sessionId, 'input[name="captcha"]')) {
throw new Error('未找到短信验证码输入框');
}
await clearFocusedField(cdp, sessionId);
await cdp.send('Input.insertText', { text: otp }, sessionId);
await cdp.send('Page.bringToFront', {}, sessionId);
await sleep(300);
if (!await clickText(cdp, sessionId, '登录', { selectors: 'button' })) {
throw new Error('未找到登录按钮');
}
await waitFor(async () => {
const state = await pageState(cdp, sessionId);
return /\/dashboard/.test(state.url) ? state : null;
}, '华夏银行登录', 60000);
}
async function setDateInput(cdp, sessionId, index, value) {
const focused = await evaluate(cdp, sessionId, `(() => {
const el = document.querySelectorAll('input.el-range-input')[${index}];
if (!el) return false;
el.click();
el.focus();
el.select();
return document.activeElement === el;
})()`);
if (!focused) {
throw new Error('未找到交易日期输入框');
}
await cdp.send('Input.insertText', { text: value }, sessionId);
await pressEnter(cdp, sessionId);
await sleep(300);
}
async function queryTransactions(cdp, sessionId) {
await setDateInput(cdp, sessionId, 0, fromDate);
await setDateInput(cdp, sessionId, 1, toDate);
if (!await clickText(cdp, sessionId, '查询', { selectors: 'button' })) {
throw new Error('未找到查询按钮');
}
const deadline = Date.now() + 60000;
let lastState = null;
while (Date.now() < deadline) {
const state = await evaluate(cdp, sessionId, `(() => {
const text = document.body?.innerText || '';
const dates = [...document.querySelectorAll('input.el-range-input')].map((el) => el.value);
const visible = (el) => !!(el.offsetWidth || el.offsetHeight);
const countElement = [...document.querySelectorAll('*')]
.filter((el) => visible(el) && !(el.children.length === 1 && el.firstElementChild?.children.length === 0))
.filter((el) => /^共\\s*\\d+\\s*条$/.test((el.innerText || '').trim()))
.sort((left, right) => right.getBoundingClientRect().y - left.getBoundingClientRect().y)[0];
const countMatch = (countElement?.innerText || '').trim().match(/^共\\s*(\\d+)\\s*条$/);
const amount = (pattern) => {
const match = text.match(pattern);
return match ? Number(String(match[1]).replace(/,/g, '')) : null;
};
const countValue = (pattern) => {
const match = text.match(pattern);
return match ? Number(match[1]) : null;
};
const incomeCount = countValue(/收入总笔数\\s*(\\d+)/);
const expenseCount = countValue(/支出总笔数\\s*(\\d+)/);
const queryButton = [...document.querySelectorAll('button')]
.find((el) => visible(el) && (el.innerText || '').replace(/\\s+/g, '') === '查询');
return {
dates,
count: incomeCount !== null && expenseCount !== null
? incomeCount + expenseCount
: (countMatch ? Number(countMatch[1]) : null),
countText: countElement?.innerText?.trim() || '',
incomeCount,
expenseCount,
income: amount(/收入总金额\\s*([\\d,.]+)/),
expense: amount(/支出总金额\\s*([\\d,.]+)/),
loading: /查询中|加载中/.test(text),
queryDisabled: !!queryButton?.disabled,
};
})()`);
lastState = state;
if (state.dates?.[0] === fromDate
&& state.dates?.[1] === toDate
&& !state.loading
&& !state.queryDisabled
&& state.count !== null
&& (state.count > 0 || (Number(state.income || 0) === 0 && Number(state.expense || 0) === 0))) {
return state;
}
await sleep(700);
}
throw new Error(
`交易明细查询超时或日期未生效(日期 ${JSON.stringify(lastState?.dates || [])},`
+ `条数 ${lastState?.count ?? 'unknown'})`,
);
}
async function waitForDownload(beforeFiles, timeoutMs = 150000) {
const before = new Set(beforeFiles);
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const files = listFiles(downloadDirectory);
const completed = files
.filter((file) => !before.has(file) && /\.(xlsx|xls)$/i.test(file))
.filter((file) => {
try {
return Date.now() - fs.statSync(file).mtimeMs > 800 && hasCompleteZip(file);
} catch {
return false;
}
})
.sort((left, right) => fs.statSync(right).mtimeMs - fs.statSync(left).mtimeMs);
if (completed.length > 0) return completed[0];
const partials = files
.filter((file) => !before.has(file) && file.endsWith('.crdownload'))
.filter((file) => {
try {
return Date.now() - fs.statSync(file).mtimeMs > 1500 && hasCompleteZip(file);
} catch {
return false;
}
})
.sort((left, right) => fs.statSync(right).mtimeMs - fs.statSync(left).mtimeMs);
if (partials.length > 0) {
const finalFile = path.join(downloadDirectory, `华夏银行_账户明细_${fromDate}_${toDate}.xlsx`);
fs.copyFileSync(partials[0], finalFile);
return finalFile;
}
await sleep(700);
}
throw new Error('交易明细下载超时');
}
let cdp = null;
let child = null;
let sessionId = null;
try {
ensureAutomationProfile();
const launch = await launchEdge({
port: PORT,
profileDir: PROFILE,
headless: false,
windowSize: '1800,1100',
forceDeviceScaleFactor: 1,
});
child = launch.child;
cdp = await CDP.connect(launch.version.webSocketDebuggerUrl);
({ sessionId } = await openPage(cdp, 'about:blank'));
await setDownloadDir(cdp, downloadDirectory);
await loginIfNeeded(cdp, sessionId);
await goto(cdp, sessionId, ACCOUNT_DETAIL_URL);
await waitFor(async () => {
const state = await pageState(cdp, sessionId);
return /账户交易明细管理/.test(state.text)
&& (await evaluate(cdp, sessionId, 'document.querySelectorAll("input.el-range-input").length')) >= 2
? state
: null;
}, '账户交易明细页面加载', 60000);
const query = await queryTransactions(cdp, sessionId);
let downloadedFile = null;
if (query.count > 0) {
const beforeFiles = listFiles(downloadDirectory);
if (!await clickText(cdp, sessionId, '全部导出', { selectors: 'button' })) {
throw new Error('未找到全部导出按钮');
}
downloadedFile = await waitForDownload(beforeFiles);
}
const state = {
ok: true,
from: fromDate,
to: toDate,
rows: query.count,
income: query.income,
expense: query.expense,
file: downloadedFile,
completedAt: new Date().toISOString(),
};
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
console.log(JSON.stringify(state));
} catch (error) {
let screenshot = null;
if (cdp && sessionId) {
try {
screenshot = path.join(runDirectory, 'failure.png');
await shot(cdp, sessionId, screenshot);
} catch {
screenshot = null;
}
}
const state = {
ok: false,
from: fromDate,
to: toDate,
error: sanitizeError(error),
screenshot,
completedAt: new Date().toISOString(),
};
fs.mkdirSync(runDirectory, { recursive: true });
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
console.error(JSON.stringify(state));
process.exitCode = 1;
} finally {
cdp?.close();
if (child) {
try {
child.kill();
} catch {
// The browser may already be closed.
}
}
}