c7b035dce9
无影云桌面等受限网络里 myip.ipip.net 不可达,页面却能正常调自家接口, 导致青果白名单拿不到本机出口 IP。新增 /api/user-secrets/client-ip 回显服务端看到的来源 IP(XFF 逐跳取首个公网地址),前端优先用它, 失败再退回第三方回显。
63 lines
2.0 KiB
TypeScript
63 lines
2.0 KiB
TypeScript
import { test } from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
|
||
import { parsePublicIp, resolvePublicIp } from '../src/shared/utils/public-ip.ts'
|
||
|
||
test('test_public_ip_parses_ipip_response', () => {
|
||
assert.equal(parsePublicIp('当前 IP:36.251.68.43 来自于:中国 福建 福州 联通'), '36.251.68.43')
|
||
})
|
||
|
||
test('test_public_ip_parses_plain_and_json_like_text', () => {
|
||
assert.equal(parsePublicIp('1.2.3.4'), '1.2.3.4')
|
||
assert.equal(parsePublicIp('{"ip":"8.8.8.8"}'), '8.8.8.8')
|
||
})
|
||
|
||
test('test_public_ip_rejects_invalid_values', () => {
|
||
assert.equal(parsePublicIp('没有地址'), null)
|
||
assert.equal(parsePublicIp('999.1.1.1'), null)
|
||
assert.equal(parsePublicIp('1.1.1'), null)
|
||
assert.equal(parsePublicIp('1.1.1.1.1'), null)
|
||
assert.equal(parsePublicIp('01.2.3.4'), null)
|
||
assert.equal(parsePublicIp(''), null)
|
||
assert.equal(parsePublicIp(null), null)
|
||
assert.equal(parsePublicIp(123), null)
|
||
})
|
||
|
||
test('test_public_ip_prefers_server_echo', async () => {
|
||
const ip = await resolvePublicIp(
|
||
async () => '8.149.69.98',
|
||
async () => {
|
||
throw new Error('第三方回显不该被调用')
|
||
},
|
||
)
|
||
assert.equal(ip, '8.149.69.98')
|
||
})
|
||
|
||
test('test_public_ip_falls_back_when_server_echo_fails', async () => {
|
||
const ip = await resolvePublicIp(
|
||
async () => {
|
||
throw new Error('401')
|
||
},
|
||
async () => '36.251.68.43',
|
||
)
|
||
assert.equal(ip, '36.251.68.43')
|
||
})
|
||
|
||
test('test_public_ip_falls_back_when_server_echo_is_not_ipv4', async () => {
|
||
// 服务端可能回显 IPv6:青果白名单要的是 IPv4,仍交给公网回显兜底
|
||
const ip = await resolvePublicIp(async () => '2408:8207:1234::1', async () => '36.251.68.43')
|
||
assert.equal(ip, '36.251.68.43')
|
||
})
|
||
|
||
test('test_public_ip_reports_error_only_when_both_channels_fail', async () => {
|
||
await assert.rejects(
|
||
resolvePublicIp(
|
||
async () => null,
|
||
async () => {
|
||
throw new Error('获取当前 IP 失败,请手动填写')
|
||
},
|
||
),
|
||
/获取当前 IP 失败/,
|
||
)
|
||
})
|