'use strict'; /** * 仓库接口消息推送 — 本地调试接收服务。 * 模拟外部适配器:接收 WMS 出站推送(notify.reply / notify.event 等), * 打印完整回信(query 签名参数 + headers + body)到控制台与日志文件,方便调试。 * * 默认配置匹配线上仓库「仓库管理系统oms」: * app_key=APP2025011514315678 * app_secret=sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890 * callback_url=http://localhost:6061/push * * 用法: * npm run debug:warehouse:push-receiver * node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log * node script/debug-warehouse-push-receiver.cjs --no-verify # 跳过 MD5 验签 */ const http = require('node:http'); const fs = require('node:fs'); const path = require('node:path'); const crypto = require('node:crypto'); const { URL } = require('node:url'); const DEFAULT_HOST = '127.0.0.1'; const DEFAULT_PORT = 6061; const DEFAULT_PATH = '/push'; const DEFAULT_APP_KEY = 'APP2025011514315678'; const DEFAULT_APP_SECRET = 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890'; const DEFAULT_LOG_FILE = path.join(process.cwd(), 'run', 'warehouse-push-receiver.log'); function parseArgs(argv) { const options = { host: process.env.PUSH_RECEIVER_HOST || DEFAULT_HOST, port: Number(process.env.PUSH_RECEIVER_PORT || DEFAULT_PORT), path: process.env.PUSH_RECEIVER_PATH || DEFAULT_PATH, appKey: process.env.PUSH_RECEIVER_APP_KEY || DEFAULT_APP_KEY, appSecret: process.env.PUSH_RECEIVER_APP_SECRET || DEFAULT_APP_SECRET, logFile: process.env.PUSH_RECEIVER_LOG_FILE || DEFAULT_LOG_FILE, verifySign: ![ '0', 'false' ].includes(String(process.env.PUSH_RECEIVER_VERIFY_SIGN || '1').toLowerCase()), help: false, }; for (const arg of argv) { if (!arg.startsWith('--')) { continue; } const [ rawKey, ...rest ] = arg.slice(2).split('='); const value = rest.join('='); switch (rawKey) { case 'host': options.host = value || options.host; break; case 'port': options.port = Number(value || options.port); break; case 'path': options.path = value.startsWith('/') ? value : `/${value}`; break; case 'app-key': options.appKey = value || options.appKey; break; case 'app-secret': options.appSecret = value || options.appSecret; break; case 'log-file': options.logFile = value || options.logFile; break; case 'no-verify': options.verifySign = false; break; case 'help': options.help = true; break; default: break; } } return options; } function printHelp() { console.log(`用法: npm run debug:warehouse:push-receiver node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log node script/debug-warehouse-push-receiver.cjs --no-verify 参数: --host=127.0.0.1 监听地址 --port=6061 监听端口 --path=/push 接收路径 --app-key=... 期望的 app_key(仅用于展示) --app-secret=... 验签密钥(MD5(appSecret + timestamp + bodyJson)) --log-file=... 日志文件(默认 run/warehouse-push-receiver.log) --no-verify 跳过 MD5 验签 环境变量: PUSH_RECEIVER_HOST / PUSH_RECEIVER_PORT / PUSH_RECEIVER_PATH PUSH_RECEIVER_APP_KEY / PUSH_RECEIVER_APP_SECRET / PUSH_RECEIVER_LOG_FILE PUSH_RECEIVER_VERIFY_SIGN=0 关闭验签`); } function readRequestBody(req) { return new Promise((resolve, reject) => { const chunks = []; req.on('data', chunk => chunks.push(chunk)); req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8'))); req.on('error', reject); }); } function writeLog(logFile, text) { const line = text.endsWith('\n') ? text : text + '\n'; try { fs.appendFileSync(logFile, line, 'utf8'); console.log(`[push-receiver] 已写入日志文件: ${logFile}`); } catch (error) { console.error('[push-receiver] 写日志文件失败:', error.message); } } function md5(value) { return crypto.createHash('md5').update(value).digest('hex'); } async function start() { const options = parseArgs(process.argv.slice(2)); if (options.help) { printHelp(); return; } const logFile = path.resolve(options.logFile); const logDir = path.dirname(logFile); fs.mkdirSync(logDir, { recursive: true }); const server = http.createServer(async (req, res) => { const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`); const startedAt = new Date().toISOString(); const rawBody = await readRequestBody(req); const query = Object.fromEntries(url.searchParams.entries()); if (url.pathname === '/health') { res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); res.end(JSON.stringify({ ok: true, service: 'warehouse-push-receiver' })); return; } if (req.method !== 'POST' || url.pathname !== options.path) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); res.end(`404 Not Found(接收路径为 ${options.path})`); return; } // MD5 验签:sign = MD5(appSecret + timestamp + bodyJson) const timestamp = String(query.timestamp || ''); const providedSign = String(query.sign || ''); const expectedSign = options.appSecret ? md5(options.appSecret + timestamp + rawBody) : ''; const signOk = !options.verifySign || (timestamp && providedSign === expectedSign); let parsedBody = rawBody; try { parsedBody = rawBody ? JSON.parse(rawBody) : null; } catch (_) { // keep raw text } const logText = [ '================ 收到仓库接口推送 ================', `[time] ${startedAt}`, `[route] POST ${url.pathname}`, `[query] ${JSON.stringify(query, null, 2)}`, options.verifySign ? `[sign] ${signOk ? '验签通过' : `验签失败(期望 ${expectedSign})`}` : '[sign] 已关闭验签', `[header] ${JSON.stringify(req.headers, null, 2)}`, `[body] ${JSON.stringify(parsedBody, null, 2)}`, '==================================================', ].join('\n'); console.log('\n' + logText); writeLog(logFile, `${logText}\n`); // 始终返回 HTTP 200 + code=200,便于 WMS 判定推送成功 const responseBody = JSON.stringify({ code: 200, message: 'ok', received_at: startedAt }); res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' }); res.end(responseBody); }); server.listen(options.port, options.host, () => { console.log('[warehouse-push-receiver] listening on http://' + options.host + ':' + options.port + options.path); console.log(`[warehouse-push-receiver] app_key=${options.appKey}`); console.log(`[warehouse-push-receiver] app_secret=${options.appSecret ? options.appSecret.slice(0, 8) + '…' : '(空)'}`); console.log(`[warehouse-push-receiver] 验签=${options.verifySign ? '开启' : '关闭'}`); console.log(`[warehouse-push-receiver] 日志文件=${logFile}`); console.log(`[warehouse-push-receiver] 健康检查: GET http://${options.host}:${options.port}/health`); console.log('[warehouse-push-receiver] 按 Ctrl+C 停止'); }); } start().catch(error => { console.error('[warehouse-push-receiver] failed:', error); process.exit(1); });