- 已登录时 /home.htm 会 302 到 ERP 后台 /web/home,改为按「最终落地页」判断登录态 - 手动逐跳跟随重定向并合并 set-cookie:登录后会话 cookie 在 302 响应头里下发, fetch 的 redirect=follow 会丢失,导致后续请求仍是未登录会话 - checkSession 与登录后校验统一走 followGet;新下发的 cookie 一并落库 - 补单测覆盖 302 到后台 / 回登录页两种结果 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
360 lines
13 KiB
JavaScript
360 lines
13 KiB
JavaScript
'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('; ');
|
||
}
|
||
|
||
/**
|
||
* 是否仍是登录页:未登录访问工作台会 302 到 `/index.htm`(登录页)
|
||
* @param {string} finalUrl 最终地址
|
||
* @param {string} html 页面 HTML
|
||
* @return {boolean} 是否登录页
|
||
*/
|
||
function isLoginPage(finalUrl, html) {
|
||
const url = String(finalUrl || '');
|
||
if (/\/index\.htm(\?|#|$)/i.test(url)) return true;
|
||
if (/\/(login|user\/login)/i.test(url) && !/\/web\//i.test(url)) return true;
|
||
return /id=["']loginForm["']/.test(String(html || ''));
|
||
}
|
||
|
||
/**
|
||
* 加密登录字段(账号/密码),与服务端约定的格式见文件头注释
|
||
* @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),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* GET 并按跳跟随重定向,逐跳合并 set-cookie
|
||
*
|
||
* fetch 的 `redirect: 'follow'` 会丢掉中间跳的 Set-Cookie(平台登录后正是在 302 响应里下发
|
||
* dxm_i / dxm_w / rememberMe 等会话 cookie),所以这里手动跟随。
|
||
* @param {string} url 起始地址
|
||
* @param {string} cookie 起始 cookie
|
||
* @param {number} [maxHops] 最多跟随跳数
|
||
* @return {Promise<{status: number, finalUrl: string, html: string, cookie: string}>} 最终响应
|
||
*/
|
||
async followGet(url, cookie, maxHops = 6) {
|
||
let currentUrl = url;
|
||
let jar = String(cookie || '');
|
||
for (let hop = 0; hop < maxHops; hop += 1) {
|
||
const res = await fetch(currentUrl, {
|
||
redirect: 'manual',
|
||
headers: { ...BROWSER_HEADERS, cookie: jar },
|
||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||
});
|
||
const setCookie = getSetCookies(res);
|
||
if (setCookie.length) jar = mergeCookie(jar, setCookie);
|
||
|
||
if (res.status >= 300 && res.status < 400) {
|
||
const location = res.headers.get('location');
|
||
await res.arrayBuffer().catch(() => {});
|
||
if (!location) return { status: res.status, finalUrl: currentUrl, html: '', cookie: jar };
|
||
currentUrl = new URL(location, currentUrl).toString();
|
||
continue;
|
||
}
|
||
|
||
return { status: res.status, finalUrl: currentUrl, html: await res.text(), cookie: jar };
|
||
}
|
||
return { status: 0, finalUrl: currentUrl, html: '', cookie: jar };
|
||
}
|
||
|
||
/**
|
||
* 获取登录图形验证码:同时返回验证码图片与绑定的会话 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 访问工作台,最终落到登录页(/index.htm)即失效
|
||
*
|
||
* 已登录时 `/home.htm` 会 302 到 ERP 后台 `/web/home`,所以不能把 302 直接判为失效;
|
||
* 逐跳跟随重定向并合并每跳下发的 cookie(登录后平台会下发 dxm_i / dxm_w / rememberMe 等)。
|
||
* @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 page;
|
||
try {
|
||
page = await this.followGet(url, this.cookie);
|
||
} catch (err) {
|
||
return { loggedIn: false, message: `检查店小秘登录态失败:${err.message}`, url };
|
||
}
|
||
|
||
const loggedIn = page.status === 200 && !isLoginPage(page.finalUrl, page.html);
|
||
if (page.cookie && page.cookie !== this.cookie) await this.saveCookie(page.cookie);
|
||
await this.saveLoginStatus(loggedIn ? 1 : 0);
|
||
return {
|
||
loggedIn,
|
||
message: loggedIn ? '登录态有效' : `登录态已失效(访问工作台被重定向到登录页:${page.finalUrl})`,
|
||
url: page.finalUrl || 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.followGet(`${this.siteUrl}${HOME_PATH}`, finalCookie);
|
||
if (home.status !== 200 || isLoginPage(home.finalUrl, home.html)) {
|
||
throw new Error(
|
||
`店小秘登录后校验失败:工作台被重定向到登录页(HTTP ${home.status},${home.finalUrl || '未返回地址'})`
|
||
);
|
||
}
|
||
|
||
const sessionCookie = home.cookie || finalCookie;
|
||
await this.saveCookie(sessionCookie);
|
||
await this.saveLoginStatus(1);
|
||
return {
|
||
cookie: sessionCookie,
|
||
token: null,
|
||
redirectUrl: json.url || null,
|
||
reused: false,
|
||
shopName: '',
|
||
};
|
||
}
|
||
}
|
||
|
||
module.exports = DxmService;
|