修复店小秘登录后校验失败(工作台 302 被误判为未登录)

- 已登录时 /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>
This commit is contained in:
liufumingren 2026-11-23 23:30:02 +08:00
parent ed67dd905c
commit 3c22269dd8
3 changed files with 120 additions and 26 deletions

View File

@ -86,6 +86,19 @@ function mergeCookie(cookie, setCookies) {
return Array.from(jar, ([ key, value ]) => `${key}=${value}`).join('; '); 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 明文 * @param {string} value 明文
@ -180,6 +193,41 @@ class DxmService extends PrintPlatformService {
}; };
} }
/**
* 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 * 获取登录图形验证码:同时返回验证码图片与绑定的会话 cookie
* @return {Promise<{image: string, session: string}>} 图片 data URL 与登录会话 cookie * @return {Promise<{image: string, session: string}>} 图片 data URL 与登录会话 cookie
@ -216,7 +264,10 @@ class DxmService extends PrintPlatformService {
} }
/** /**
* 检查登录态:带 cookie 访问工作台,302 到登录页即失效 * 检查登录态:带 cookie 访问工作台,最终落到登录页(/index.htm)即失效
*
* 已登录时 `/home.htm` 会 302 到 ERP 后台 `/web/home`,所以不能把 302 直接判为失效;
* 逐跳跟随重定向并合并每跳下发的 cookie(登录后平台会下发 dxm_i / dxm_w / rememberMe 等)。
* @return {Promise<{loggedIn: boolean, message: string, url: string}>} 登录态检查结果 * @return {Promise<{loggedIn: boolean, message: string, url: string}>} 登录态检查结果
*/ */
async checkSession() { async checkSession() {
@ -226,22 +277,20 @@ class DxmService extends PrintPlatformService {
return { loggedIn: false, message: '账号未保存会话 cookie,尚未登录', url }; return { loggedIn: false, message: '账号未保存会话 cookie,尚未登录', url };
} }
let res; let page;
try { try {
res = await this.request(url, { page = await this.followGet(url, this.cookie);
headers: { ...BROWSER_HEADERS, cookie: this.cookie },
redirect: 'manual',
});
} catch (err) { } catch (err) {
return { loggedIn: false, message: `检查店小秘登录态失败:${err.message}`, url }; return { loggedIn: false, message: `检查店小秘登录态失败:${err.message}`, url };
} }
const loggedIn = res.status === 200; const loggedIn = page.status === 200 && !isLoginPage(page.finalUrl, page.html);
if (!loggedIn) await this.saveLoginStatus(0); if (page.cookie && page.cookie !== this.cookie) await this.saveCookie(page.cookie);
await this.saveLoginStatus(loggedIn ? 1 : 0);
return { return {
loggedIn, loggedIn,
message: loggedIn ? '登录态有效' : '登录态已失效(访问工作台被重定向到登录页)', message: loggedIn ? '登录态有效' : `登录态已失效(访问工作台被重定向到登录页:${page.finalUrl})`,
url, url: page.finalUrl || url,
}; };
} }
@ -287,18 +336,18 @@ class DxmService extends PrintPlatformService {
} }
const finalCookie = mergeCookie(cookie, res.setCookies); const finalCookie = mergeCookie(cookie, res.setCookies);
const home = await this.request(`${this.siteUrl}${HOME_PATH}`, { const home = await this.followGet(`${this.siteUrl}${HOME_PATH}`, finalCookie);
headers: { ...BROWSER_HEADERS, cookie: finalCookie }, if (home.status !== 200 || isLoginPage(home.finalUrl, home.html)) {
redirect: 'manual', throw new Error(
}); `店小秘登录后校验失败:工作台被重定向到登录页(HTTP ${home.status},${home.finalUrl || '未返回地址'})`
if (home.status !== 200) { );
throw new Error(`店小秘登录后校验失败:访问工作台被重定向(HTTP ${home.status})`);
} }
await this.saveCookie(finalCookie); const sessionCookie = home.cookie || finalCookie;
await this.saveCookie(sessionCookie);
await this.saveLoginStatus(1); await this.saveLoginStatus(1);
return { return {
cookie: finalCookie, cookie: sessionCookie,
token: null, token: null,
redirectUrl: json.url || null, redirectUrl: json.url || null,
reused: false, reused: false,

View File

@ -95,16 +95,42 @@ describe('printPlatform/dxm loginByPassword', () => {
assert.match(options.headers.cookie, /JSESSIONID=logged-in/); assert.match(options.headers.cookie, /JSESSIONID=logged-in/);
return { status: 200, json: null, text: '', setCookies: [] }; return { status: 200, json: null, text: '', setCookies: [] };
}; };
// 登录后工作台会 302 到 ERP 后台 /web/home,由 followGet 跟随
service.followGet = async (url, cookie) => {
calls.push({ url, cookie });
return {
status: 200,
finalUrl: 'https://www.dianxiaomi.com/web/home',
html: '<title>店小秘--免费的跨境电商ERP</title>',
cookie: `${cookie}; dxm_i=user-1`,
};
};
const result = await service.login({ captcha: '1234', session: 'JSESSIONID=abc; dxm_vc=token456' }); const result = await service.login({ captcha: '1234', session: 'JSESSIONID=abc; dxm_vc=token456' });
assert.strictEqual(result.reused, false); assert.strictEqual(result.reused, false);
assert.strictEqual(result.cookie, 'JSESSIONID=logged-in; dxm_vc=token456'); assert.strictEqual(result.cookie, 'JSESSIONID=logged-in; dxm_vc=token456; dxm_i=user-1');
assert.strictEqual(saved.cookie, result.cookie); assert.strictEqual(saved.cookie, result.cookie);
assert.strictEqual(saved.status, 1); assert.strictEqual(saved.status, 1);
assert.strictEqual(calls.length, 2); assert.strictEqual(calls.length, 2);
}); });
it('登录成功但工作台仍回到登录页时提示校验失败', async () => {
const { service } = createService();
service.request = async () => ({ status: 200, json: { code: 0, url: '/home.htm' }, text: '', setCookies: [] });
service.followGet = async () => ({
status: 200,
finalUrl: 'https://www.dianxiaomi.com/index.htm',
html: '<form id="loginForm">',
cookie: '',
});
await assert.rejects(
service.login({ captcha: '1234', session: 'JSESSIONID=abc; dxm_vc=token456' }),
/登录后校验失败/
);
});
it('平台返回验证码错误时抛出可读原因且不保存会话', async () => { it('平台返回验证码错误时抛出可读原因且不保存会话', async () => {
const { service, saved } = createService(); const { service, saved } = createService();
service.request = async () => ({ service.request = async () => ({
@ -123,22 +149,35 @@ describe('printPlatform/dxm loginByPassword', () => {
}); });
describe('printPlatform/dxm checkSession', () => { describe('printPlatform/dxm checkSession', () => {
it('访问工作台 200 视为已登录', async () => { it('工作台 302 到 ERP 后台时视为已登录,并保存新下发的 cookie', async () => {
const { service, saved } = createService({ account: { cookie: 'JSESSIONID=ok' } }); const { service, saved } = createService({ account: { cookie: 'JSESSIONID=ok' } });
service.request = async () => ({ status: 200, json: null, text: '', setCookies: [] }); service.followGet = async () => ({
status: 200,
finalUrl: 'https://www.dianxiaomi.com/web/home',
html: '<title>店小秘--免费的跨境电商ERP</title>',
cookie: 'JSESSIONID=ok; dxm_i=user-1',
});
const result = await service.checkSession(); const result = await service.checkSession();
assert.strictEqual(result.loggedIn, true); assert.strictEqual(result.loggedIn, true);
assert.strictEqual(saved.status, null); assert.strictEqual(saved.status, 1);
assert.strictEqual(saved.cookie, 'JSESSIONID=ok; dxm_i=user-1');
assert.strictEqual(result.url, 'https://www.dianxiaomi.com/web/home');
}); });
it('访问工作台被 302 到登录页时标记未登录', async () => { it('最终落到登录页时标记未登录', async () => {
const { service, saved } = createService({ account: { cookie: 'JSESSIONID=expired' } }); const { service, saved } = createService({ account: { cookie: 'JSESSIONID=expired' } });
service.request = async () => ({ status: 302, json: null, text: '', setCookies: [] }); service.followGet = async () => ({
status: 200,
finalUrl: 'https://www.dianxiaomi.com/index.htm',
html: '<form id="loginForm">',
cookie: 'JSESSIONID=expired',
});
const result = await service.checkSession(); const result = await service.checkSession();
assert.strictEqual(result.loggedIn, false); assert.strictEqual(result.loggedIn, false);
assert.strictEqual(saved.status, 0); assert.strictEqual(saved.status, 0);
assert.match(result.message, /重定向到登录页/);
}); });
it('没有 cookie 时直接返回未登录', async () => { it('没有 cookie 时直接返回未登录', async () => {

View File

@ -20,10 +20,16 @@
必须带 ① 的 cookie(尤其 dxm_vc),否则验证码必然校验失败 必须带 ① 的 cookie(尤其 dxm_vc),否则验证码必然校验失败
③ GET /home.htm ③ GET /home.htm
├─ 未登录:302 → /index.htm ├─ 未登录:302 → /index.htm(官网登录页)
└─ 已登录:200(登录成功后用它确认会话真正可用,再落库) └─ 已登录:**302 → /web/home**(ERP 后台,200)
登录响应本身还会下发 dxm_i / dxm_w / dxm_t / dxm_c / dxm_s / rememberMe 等会话 cookie,
这些 cookie 是在 **302 响应头**里下发的,用 `fetch` 的 `redirect: 'follow'` 会丢失,
必须手动逐跳跟随并合并 set-cookie(`dxm.js#followGet`)。
``` ```
判断登录态只能看「最终落到哪个页面」,不能按状态码判断:
`checkSession` / 登录后校验都走 `followGet`,最终地址命中 `/index.htm`(或页面含 `id="loginForm"`)才算未登录。
### 账号密码加密格式 ### 账号密码加密格式
与前端 `dxmEncrypt.js` 一致: 与前端 `dxmEncrypt.js` 一致: