liufumingren 78f07651f1 店小秘接入基础:图形验证码登录
- 新增 dxm 平台实现:取图形验证码、AES 加密账号密码登录、登录态检查
- 账号接口返回 requires_login_captcha;新增 GET /external-print-accounts/:id/login-captcha
- 验证码绑定的会话存 Redis,登录成功/失败后都清理,支持多实例
- 前端登录按钮按平台能力弹出验证码输入框
- 补 dxm 平台字典迁移、接入文档与单元测试

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-23 21:32:25 +08:00

311 lines
10 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.

'use strict';
/**
* 店小秘(dianxiaomi)外部打单平台服务。
*
* 平台记录:external_print_platforms.code = 'dxm'。
* 当前实现「接入基础」:图形验证码 + 账号密码登录 + 登录态检查;
* 店铺/商品/订单/取号等业务接口待按平台真实报文补齐(基类会明确报未实现)。
*
* 登录协议(2026-11-23 实测):
* 1. GET /verify/code.htm?t=<时间戳> 返回 4 位图形验证码,响应同时下发
* JSESSIONID 与 dxm_vc(验证码绑定会话),登录必须带上同一组 cookie;
* 2. POST /user/userLoginNew2.json 表单字段 account / password(AES 加密串)、
* dxmVerify(验证码)、loginVerifyCode / remeber / loginRedUrl / url;
* 返回 { code: 0 成功, error, url },code=-1 为验证码错误;
* 3. GET /home.htm 未登录会 302 到 /index.htm,200 即登录态有效。
*
* 账号密码加密格式(与前端 dxmEncrypt.js 一致):
* "0" + 4位随机hex + 16字节IV(hex) + 16字节Key(hex) + AES-128-CBC 密文(hex)
*/
const crypto = require('crypto');
const PrintPlatformService = require('./base');
/** 平台配置未填链接时的默认站点 */
const DEFAULT_SITE_URL = 'https://www.dianxiaomi.com';
/** 图形验证码 */
const CAPTCHA_PATH = '/verify/code.htm';
/** 账号密码登录 */
const LOGIN_PATH = '/user/userLoginNew2.json';
/** 工作台首页:未登录会 302 到登录页 */
const HOME_PATH = '/home.htm';
const REQUEST_TIMEOUT_MS = 30000;
const USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36';
const BROWSER_HEADERS = {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'accept-language': 'zh-CN,zh;q=0.9',
'user-agent': USER_AGENT,
};
const AJAX_HEADERS = {
accept: 'application/json, text/javascript, */*; q=0.01',
'accept-language': 'zh-CN,zh;q=0.9',
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
'user-agent': USER_AGENT,
'x-requested-with': 'XMLHttpRequest',
};
/**
* 读取响应里的 set-cookie(兼容没有 getSetCookie 的运行时)
* @param {Response} res fetch 响应
* @return {string[]} set-cookie 列表
*/
function getSetCookies(res) {
if (typeof res.headers.getSetCookie === 'function') return res.headers.getSetCookie();
const raw = res.headers.get('set-cookie');
return raw ? [ raw ] : [];
}
/**
* 合并 set-cookie 到已有 cookie:同名覆盖,其余保留
* @param {string} cookie 已有 cookie
* @param {string[]} setCookies 响应头 set-cookie
* @return {string} 合并后的 cookie
*/
function mergeCookie(cookie, setCookies) {
const jar = new Map();
for (const item of String(cookie || '').split(';')) {
const kv = item.trim();
const idx = kv.indexOf('=');
if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1));
}
for (const raw of setCookies || []) {
const kv = String(raw).split(';')[0].trim();
const idx = kv.indexOf('=');
if (idx > 0) jar.set(kv.slice(0, idx), kv.slice(idx + 1));
}
return Array.from(jar, ([ key, value ]) => `${key}=${value}`).join('; ');
}
/**
* 加密登录字段(账号/密码),与服务端约定的格式见文件头注释
* @param {string} value 明文
* @return {string} 加密串
*/
function encryptLoginField(value) {
const key = crypto.randomBytes(16);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
const encrypted = Buffer.concat([ cipher.update(String(value), 'utf8'), cipher.final() ]);
return `0${crypto.randomBytes(2).toString('hex')}${iv.toString('hex')}${key.toString('hex')}${encrypted.toString('hex')}`;
}
class DxmService extends PrintPlatformService {
static get code() {
return 'dxm';
}
/** 店小秘登录必须带图形验证码 */
static get loginRequiresCaptcha() {
return true;
}
/**
* 加密登录字段(导出给测试/排查用)
* @param {string} value 明文
* @return {string} 加密串
*/
static encryptLoginField(value) {
return encryptLoginField(value);
}
/**
* 店铺来源:店小秘按「已授权店铺」拉取
* @return {Array<{code: string, name: string}>} 来源清单
*/
listShopSources() {
return [{ code: 'shop', name: '店铺' }];
}
/**
* 站点根地址(平台配置的链接为空时用默认域名)
* @return {string} 站点根地址,不带结尾斜杠
*/
get siteUrl() {
const url = String(this.platform.url || '').trim();
if (!url) return DEFAULT_SITE_URL;
const withProtocol = /^https?:\/\//i.test(url) ? url : `https://${url}`;
return withProtocol.replace(/\/+$/, '');
}
/**
* 统一 JSON/文本请求入口(各实现可被测试替换)
* @param {string} url 完整请求地址
* @param {Object} [options] fetch 选项
* @return {Promise<{status: number, json: Object|null, text: string, setCookies: string[]}>} 响应
*/
async request(url, options = {}) {
const res = await fetch(url, {
redirect: 'follow',
...options,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
const text = await res.text();
let json = null;
try {
json = JSON.parse(text);
} catch {
json = null;
}
return { status: res.status, json, text, setCookies: getSetCookies(res) };
}
/**
* 二进制请求(图形验证码是图片)
* @param {string} url 完整请求地址
* @param {Object} [options] fetch 选项
* @return {Promise<{status: number, buffer: Buffer, contentType: string, setCookies: string[]}>} 响应
*/
async requestBinary(url, options = {}) {
const res = await fetch(url, {
redirect: 'follow',
...options,
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
const buffer = Buffer.from(await res.arrayBuffer());
return {
status: res.status,
buffer,
contentType: String(res.headers.get('content-type') || ''),
setCookies: getSetCookies(res),
};
}
/**
* 获取登录图形验证码:同时返回验证码图片与绑定的会话 cookie
* @return {Promise<{image: string, session: string}>} 图片 data URL 与登录会话 cookie
*/
async getLoginCaptcha() {
const res = await this.requestBinary(`${this.siteUrl}${CAPTCHA_PATH}?t=${Date.now()}`, {
headers: { ...BROWSER_HEADERS, referer: `${this.siteUrl}/` },
});
if (res.status !== 200 || !res.buffer.length) {
throw new Error(`店小秘获取验证码失败:HTTP ${res.status}`);
}
const mime = (res.contentType.split(';')[0] || '').trim() || 'image/jpeg';
return {
image: `data:${mime};base64,${res.buffer.toString('base64')}`,
session: mergeCookie('', res.setCookies),
};
}
/**
* 登录:cookie 有效时直接复用;否则用「账号 + 密码 + 图形验证码」登录
* @param {Object} [options] 登录参数
* @param {string} [options.captcha] 图形验证码(平台要求验证码时为必填)
* @param {string} [options.session] 获取验证码时绑定的会话 cookie
* @return {Promise<{cookie: string, token: null, redirectUrl: string|null, reused: boolean, shopName: string}>} 登录结果
*/
async login(options = {}) {
if (this.cookie) {
const status = await this.checkSession();
if (status.loggedIn) {
return { cookie: this.cookie, token: null, redirectUrl: null, reused: true, shopName: status.shopName || '' };
}
}
return this.loginByPassword(options);
}
/**
* 检查登录态:带 cookie 访问工作台,302 到登录页即失效
* @return {Promise<{loggedIn: boolean, message: string, url: string}>} 登录态检查结果
*/
async checkSession() {
const url = `${this.siteUrl}${HOME_PATH}`;
if (!this.cookie) {
await this.saveLoginStatus(0);
return { loggedIn: false, message: '账号未保存会话 cookie,尚未登录', url };
}
let res;
try {
res = await this.request(url, {
headers: { ...BROWSER_HEADERS, cookie: this.cookie },
redirect: 'manual',
});
} catch (err) {
return { loggedIn: false, message: `检查店小秘登录态失败:${err.message}`, url };
}
const loggedIn = res.status === 200;
if (!loggedIn) await this.saveLoginStatus(0);
return {
loggedIn,
message: loggedIn ? '登录态有效' : '登录态已失效(访问工作台被重定向到登录页)',
url,
};
}
/**
* 账号密码 + 图形验证码登录
* @param {Object} [options] 登录参数
* @param {string} [options.captcha] 图形验证码
* @param {string} [options.session] 获取验证码时绑定的会话 cookie
* @return {Promise<{cookie: string, token: null, redirectUrl: string|null, reused: boolean, shopName: string}>} 登录结果
*/
async loginByPassword({ captcha = '', session = '' } = {}) {
const code = String(captcha || '').trim();
if (!code) throw new Error('店小秘登录需要图形验证码:请先获取验证码');
const cookie = String(session || '').trim();
if (!cookie) throw new Error('店小秘验证码已过期:请刷新验证码后重试');
const { account, password } = this.getCredentials();
const body = new URLSearchParams({
account: encryptLoginField(account),
password: encryptLoginField(password),
dxmVerify: code,
loginVerifyCode: '',
remeber: '',
loginRedUrl: '',
url: '',
});
const res = await this.request(`${this.siteUrl}${LOGIN_PATH}`, {
method: 'POST',
headers: {
...AJAX_HEADERS,
origin: this.siteUrl,
referer: `${this.siteUrl}/index.htm`,
cookie,
},
body: body.toString(),
});
const json = res.json || {};
if (Number(json.code) !== 0) {
const reason = String(json.error || '').trim() || `平台返回 code=${json.code}`;
throw new Error(`店小秘登录失败:${reason}`);
}
const finalCookie = mergeCookie(cookie, res.setCookies);
const home = await this.request(`${this.siteUrl}${HOME_PATH}`, {
headers: { ...BROWSER_HEADERS, cookie: finalCookie },
redirect: 'manual',
});
if (home.status !== 200) {
throw new Error(`店小秘登录后校验失败:访问工作台被重定向(HTTP ${home.status})`);
}
await this.saveCookie(finalCookie);
await this.saveLoginStatus(1);
return {
cookie: finalCookie,
token: null,
redirectUrl: json.url || null,
reused: false,
shopName: '',
};
}
}
module.exports = DxmService;