feat(log): 启动日志打印真实可访问地址,回环绑定时显式告警

绑定 0.0.0.0 时日志直接拼 http://0.0.0.0:3000——浏览器打不开,
排障时只会看到"已启动"却不知道访问哪个 IP。

- 新增 src/config/access-hint.ts:describeAccess() 把绑定地址翻译成
  监听描述 + 可访问地址(回环 / 具体网卡 / 通配取真实网卡 IPv4);
  独立成模块是为了可测——main.ts 顶层会执行 bootstrap(),不能被 import
- main.ts:启动日志改为「监听 …(全部网卡,外部可访问)」+ 真实访问地址;
  HOST=127.0.0.1 时用 warn 明确提示"只能本机访问"并给出修复方法
- 新增 test/access-log.spec.ts(4 项)覆盖三种绑定模式,
  断言通配模式绝不出现 0.0.0.0 形式的 URL

实测三种模式日志输出正确;单测 35/35、契约与 29 条路由校验通过。
This commit is contained in:
2026-09-15 02:04:51 +08:00
parent 44451028dd
commit 76725e5ce3
3 changed files with 94 additions and 3 deletions
+39
View File
@@ -0,0 +1,39 @@
import { networkInterfaces } from 'node:os';
/** 服务实际监听地址与外界可用的访问地址。 */
export interface AccessHint {
/** 供日志展示的监听描述,例如 `0.0.0.0:3000(全部网卡,外部可访问)`。 */
listen: string;
/** 可访问地址,第一个恒为回环地址。 */
urls: string[];
/** 是否只监听回环(此时外部一定访问不到)。 */
loopbackOnly: boolean;
}
/**
* 把绑定地址翻译成"人能看懂、能直接用"的访问地址。
*
* 绑定 0.0.0.0 时,日志里写 http://0.0.0.0:3000 是没有意义的(浏览器打不开),
* 必须换成真实网卡地址,否则排障时会被误导——"服务已启动"但没人知道该访问哪个 IP。
*/
export function describeAccess(bindHost: string, port: number): AccessHint {
const wildcard = ['0.0.0.0', '::', '*', ''].includes(bindHost);
if (!wildcard) {
const loopbackOnly = ['127.0.0.1', 'localhost', '::1'].includes(bindHost);
return {
listen: `${bindHost}:${port}(${loopbackOnly ? '仅本机可访问' : '仅该地址可访问'})`,
urls: [`http://${bindHost}:${port}`],
loopbackOnly,
};
}
const urls = [`http://127.0.0.1:${port}`];
for (const addresses of Object.values(networkInterfaces())) {
for (const address of addresses ?? []) {
if (address.family === 'IPv4' && !address.internal) {
urls.push(`http://${address.address}:${port}`);
}
}
}
return { listen: `0.0.0.0:${port}(全部网卡,外部可访问)`, urls, loopbackOnly: false };
}