'use strict'; /** * 测试脚本目标环境硬守卫(OPS-2,2026-10-19)。 * * 背景:`test-functionality.js` / `test-page-flows.js` 旧默认 `http://127.0.0.1:3001/api` * (主系统 API),两个小程序探针默认 `https://www.xdjchuanhui.com/api`(生产)—— * 本机跑一次测试就可能把生产数据打一遍。 * * 规则: * · 默认只允许本机(127.0.0.1 / localhost / ::1),默认端口 3022; * · 目标非本机时必须 **显式** API_BASE + ALLOW_REMOTE=1,否则 exit 1; * · ALLOW_REMOTE=1 也要 3 秒倒计时确认;非交互(stdin 非 TTY)直接硬失败。 */ function isLoopbackTarget(base) { try { const host = new URL(base).hostname.replace(/^\[|\]$/g, '').toLowerCase(); return host === '127.0.0.1' || host === 'localhost' || host === '::1'; } catch { return false; } } function sleepBlocking(ms) { // 无依赖阻塞等待(用于 TTY 下 3 秒倒计时);非 TTY 不会走到这里 Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); } /** * @param {{ base: string, explicit?: boolean, label?: string }} options * @returns {string} 归一后的 base(无尾斜杠) */ function guardTestTarget(options) { const raw = String(options.base || '').trim(); const base = raw.replace(/\/+$/, ''); console.log(`[test] target: ${base}`); if (!base) { console.error('[test] 未设置目标地址:本机默认 http://127.0.0.1:3022/api'); process.exit(1); } if (isLoopbackTarget(base)) { /** * O-12.10:本机 3001 是**主系统** API(AI 生鲜配送),不是本系统 3022。 * 旧守卫把任何 127.0.0.1 都当"安全本地" ⇒ 默认就可能把主系统数据打一遍。 * 需要显式 ALLOW_MAIN_SYSTEM=1 才放行(并在 TTY 下提示)。 */ let port = ''; try { const parsed = new URL(base); port = parsed.port || (parsed.protocol === 'https:' ? '443' : '80'); } catch { /* isLoopbackTarget 已解析过,理论上不会到这里 */ } if (port === '3001' && process.env.ALLOW_MAIN_SYSTEM !== '1') { console.error('检测到目标为本机 3001(主系统 API),已拒绝;如确需测试主系统请设置 ALLOW_MAIN_SYSTEM=1'); process.exit(1); } return base; } if (!options.explicit || process.env.ALLOW_REMOTE !== '1') { console.error('拒绝访问非本地目标,如确需请设置 ALLOW_REMOTE=1'); process.exit(1); } if (!process.stdin.isTTY) { console.error('[test] 非交互环境禁止访问非本地目标(即使 ALLOW_REMOTE=1)'); process.exit(1); } console.log(`[test] 目标非本地(${options.label || 'remote'}):${base};3 秒后继续,Ctrl+C 取消...`); sleepBlocking(3000); return base; } module.exports = { guardTestTarget, isLoopbackTarget };