331 lines
9.0 KiB
JavaScript
331 lines
9.0 KiB
JavaScript
'use strict';
|
||
|
||
const crypto = require('node:crypto');
|
||
const fs = require('node:fs');
|
||
const path = require('node:path');
|
||
const assert = require('node:assert/strict');
|
||
const { XMLParser } = require('fast-xml-parser');
|
||
|
||
const loadDefaultConfig = require('../../config/config.default');
|
||
|
||
const BASE_URL = process.env.SYSTEM_TEST_BASE_URL || 'http://127.0.0.1:6060';
|
||
const BASE_GATEWAY_URL = process.env.SYSTEM_TEST_GATEWAY_BASE_URL || BASE_URL;
|
||
const TOKEN_FILE = process.env.SYSTEM_TEST_TOKEN_FILE
|
||
|| path.join(process.cwd(), 'test', '.runtime', 'system_user_token.json');
|
||
const USERNAME = process.env.SYSTEM_TEST_USERNAME || 'liufumingren';
|
||
const PASSWORD = process.env.SYSTEM_TEST_PASSWORD || '111111';
|
||
|
||
const DEFAULT_APP_INFO = {
|
||
name: 'wms',
|
||
baseDir: process.cwd(),
|
||
};
|
||
|
||
let cachedQimenDefaults = null;
|
||
|
||
function loadQimenDefaults() {
|
||
if (cachedQimenDefaults) {
|
||
return cachedQimenDefaults;
|
||
}
|
||
|
||
try {
|
||
const defaultConfig = loadDefaultConfig(DEFAULT_APP_INFO) || {};
|
||
cachedQimenDefaults = {
|
||
appKey: process.env.SYSTEM_TEST_QIMEN_APP_KEY || defaultConfig.qimen?.appKey || '',
|
||
secret: process.env.SYSTEM_TEST_QIMEN_SECRET || defaultConfig.qimen?.security || '',
|
||
};
|
||
} catch {
|
||
cachedQimenDefaults = {
|
||
appKey: process.env.SYSTEM_TEST_QIMEN_APP_KEY || '',
|
||
secret: process.env.SYSTEM_TEST_QIMEN_SECRET || '',
|
||
};
|
||
}
|
||
|
||
return cachedQimenDefaults;
|
||
}
|
||
|
||
function nowSec() {
|
||
return Math.floor(Date.now() / 1000);
|
||
}
|
||
|
||
function normalizeString(value) {
|
||
return value === null || value === undefined ? '' : String(value);
|
||
}
|
||
|
||
function buildTopSign(params, body, secret, signMethod = 'md5') {
|
||
const keys = Object.keys(params).sort();
|
||
let query = '';
|
||
const normalizedSignMethod = String(signMethod || '').toLowerCase();
|
||
|
||
if (normalizedSignMethod === 'md5') {
|
||
query += normalizeString(secret);
|
||
}
|
||
|
||
for (const key of keys) {
|
||
const value = params[key];
|
||
if (key && value) {
|
||
query += key + value;
|
||
}
|
||
}
|
||
|
||
if (body) {
|
||
query += body;
|
||
}
|
||
|
||
if (normalizedSignMethod === 'hmac') {
|
||
return crypto.createHmac('md5', normalizeString(secret))
|
||
.update(query, 'utf8')
|
||
.digest('hex')
|
||
.toUpperCase();
|
||
}
|
||
|
||
if (normalizedSignMethod === 'hmac_sha256') {
|
||
return crypto.createHmac('sha256', normalizeString(secret))
|
||
.update(query, 'utf8')
|
||
.digest('hex')
|
||
.toUpperCase();
|
||
}
|
||
|
||
query += normalizeString(secret);
|
||
return crypto.createHash('md5')
|
||
.update(query, 'utf8')
|
||
.digest('hex')
|
||
.toUpperCase();
|
||
}
|
||
|
||
function parseXmlBody(xmlText) {
|
||
try {
|
||
const parser = new XMLParser({
|
||
ignoreAttributes: false,
|
||
attributeNamePrefix: '@_',
|
||
allowBooleanAttributes: true,
|
||
parseTagValue: false,
|
||
parseAttributeValue: false,
|
||
trimValues: false,
|
||
ignoreDeclaration: true,
|
||
});
|
||
|
||
return parser.parse(xmlText);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function decodeJwtPayload(token) {
|
||
try {
|
||
const payloadSegment = token.split('.')[1];
|
||
if (!payloadSegment) return null;
|
||
|
||
const normalized = payloadSegment.replace(/-/g, '+').replace(/_/g, '/');
|
||
const padded = normalized + '='.repeat((4 - normalized.length % 4) % 4);
|
||
return JSON.parse(Buffer.from(padded, 'base64').toString('utf8'));
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function isTokenUsable(token) {
|
||
if (!token) return false;
|
||
const payload = decodeJwtPayload(token);
|
||
if (!payload || !payload.exp) return false;
|
||
return payload.exp - nowSec() > 120;
|
||
}
|
||
|
||
function readCachedToken() {
|
||
if (!fs.existsSync(TOKEN_FILE)) return null;
|
||
|
||
try {
|
||
const content = fs.readFileSync(TOKEN_FILE, 'utf8');
|
||
const parsed = JSON.parse(content);
|
||
const token = parsed && parsed.token;
|
||
return isTokenUsable(token) ? token : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function writeCachedToken(token) {
|
||
fs.mkdirSync(path.dirname(TOKEN_FILE), { recursive: true });
|
||
|
||
const payload = decodeJwtPayload(token);
|
||
const record = {
|
||
token,
|
||
username: USERNAME,
|
||
cachedAt: new Date().toISOString(),
|
||
exp: payload && payload.exp ? payload.exp : null,
|
||
};
|
||
|
||
fs.writeFileSync(TOKEN_FILE, JSON.stringify(record, null, 2), 'utf8');
|
||
}
|
||
|
||
async function invokeSystemMethod(method, body = {}, token, extra = {}) {
|
||
const timestamp = nowSec();
|
||
const url = `${BASE_URL}/system?method=${encodeURIComponent(method)}&v=1.0×tamp=${timestamp}`;
|
||
const platform = extra && extra.platform ? extra.platform : 'web';
|
||
const project = extra && extra.project ? extra.project : 'wms';
|
||
const headers = {
|
||
platform,
|
||
project,
|
||
'Content-Type': 'application/json',
|
||
};
|
||
|
||
if (token) {
|
||
headers.Authorization = `Bearer ${token}`;
|
||
}
|
||
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers,
|
||
body: JSON.stringify(body),
|
||
});
|
||
|
||
const text = await response.text();
|
||
let json;
|
||
try {
|
||
json = JSON.parse(text);
|
||
} catch {
|
||
throw new Error(`Invalid JSON from ${method}: ${text}`);
|
||
}
|
||
|
||
return {
|
||
status: response.status,
|
||
body: json,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 发送真实的 /qimen 请求,并返回原始响应文本。
|
||
* @param {string} method 奇门方法名,例如 deliveryorder.create。
|
||
* @param {string} xmlBody 原始 XML 请求体。
|
||
* @param {Object} [options={}] 请求选项。
|
||
* @param {string} [options.appKey] 请求 app_key;未传时读取 config.default.js 或环境变量覆盖值。
|
||
* @param {string} [options.secret] 签名密钥;未传时读取 config.default.js 或环境变量覆盖值。
|
||
* @param {string} [options.customerId] 客户编码。
|
||
* @param {string} [options.timestamp] 时间戳;未传时使用当前秒级时间戳。
|
||
* @param {string} [options.v='2.0'] 版本号。
|
||
* @param {string} [options.format='xml'] 响应格式。
|
||
* @param {string} [options.signMethod='md5'] 签名方式。
|
||
* @param {string} [options.contentType='application/xml'] 请求 Content-Type。
|
||
* @param {Object} [options.headers={}] 额外请求头。
|
||
* @return {Promise<{status: number, body: string, parsed: Object|null, url: string, queryParams: Object}>} 请求结果。
|
||
*/
|
||
async function invokeQimenMethod(method, xmlBody, options = {}) {
|
||
const qimenDefaults = loadQimenDefaults();
|
||
const timestamp = options.timestamp || String(nowSec());
|
||
const appKey = normalizeString(options.appKey || qimenDefaults.appKey);
|
||
const secret = normalizeString(options.secret || qimenDefaults.secret);
|
||
const customerId = normalizeString(options.customerId || '');
|
||
const format = normalizeString(options.format || 'xml') || 'xml';
|
||
const signMethod = normalizeString(options.signMethod || 'md5') || 'md5';
|
||
const version = normalizeString(options.v || '2.0') || '2.0';
|
||
const bodyText = normalizeString(xmlBody);
|
||
const queryParams = {
|
||
app_key: appKey,
|
||
method: normalizeString(method),
|
||
v: version,
|
||
format,
|
||
sign_method: signMethod,
|
||
timestamp,
|
||
};
|
||
|
||
if (customerId) {
|
||
queryParams.customerId = customerId;
|
||
}
|
||
|
||
queryParams.sign = buildTopSign(queryParams, bodyText, secret, signMethod);
|
||
|
||
const url = new URL(`${BASE_URL}/qimen`);
|
||
for (const [ key, value ] of Object.entries(queryParams)) {
|
||
if (value !== undefined && value !== null && value !== '') {
|
||
url.searchParams.set(key, value);
|
||
}
|
||
}
|
||
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': options.contentType || 'application/xml',
|
||
...(options.headers || {}),
|
||
},
|
||
body: bodyText,
|
||
});
|
||
|
||
const text = await response.text();
|
||
|
||
return {
|
||
status: response.status,
|
||
body: text,
|
||
parsed: format.toLowerCase() === 'xml' ? parseXmlBody(text) : null,
|
||
url: url.toString(),
|
||
queryParams,
|
||
};
|
||
}
|
||
|
||
async function getAuthToken(options = {}) {
|
||
const { forceLogin = false } = options;
|
||
|
||
if (!forceLogin) {
|
||
const cached = readCachedToken();
|
||
if (cached) {
|
||
return { token: cached, fromCache: true };
|
||
}
|
||
}
|
||
|
||
const loginRes = await invokeSystemMethod('user.login', {
|
||
username: USERNAME,
|
||
password: PASSWORD,
|
||
});
|
||
|
||
assert.equal(loginRes.status, 200, 'user.login should return HTTP 200');
|
||
assert.equal(loginRes.body.flag, 'success', `user.login should succeed: ${JSON.stringify(loginRes.body)}`);
|
||
|
||
const token = loginRes.body
|
||
&& loginRes.body.data
|
||
&& loginRes.body.data.token;
|
||
|
||
assert.ok(token, 'user.login response should contain token');
|
||
|
||
writeCachedToken(token);
|
||
return {
|
||
token,
|
||
fromCache: false,
|
||
};
|
||
}
|
||
|
||
async function invokeGatewayMethod(method, body = {}) {
|
||
const timestamp = nowSec();
|
||
const url = `${BASE_GATEWAY_URL}/internal/v1/gateway?method=${encodeURIComponent(method)}&v=1.0×tamp=${timestamp}`;
|
||
|
||
const response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
},
|
||
body: JSON.stringify(body),
|
||
});
|
||
|
||
const text = await response.text();
|
||
let json;
|
||
try {
|
||
json = JSON.parse(text);
|
||
} catch {
|
||
throw new Error(`Invalid JSON from gateway ${method}: ${text}`);
|
||
}
|
||
|
||
return {
|
||
status: response.status,
|
||
body: json,
|
||
};
|
||
}
|
||
|
||
module.exports = {
|
||
BASE_URL,
|
||
BASE_GATEWAY_URL,
|
||
TOKEN_FILE,
|
||
USERNAME,
|
||
invokeSystemMethod,
|
||
invokeQimenMethod,
|
||
invokeGatewayMethod,
|
||
getAuthToken,
|
||
readCachedToken,
|
||
};
|