qq-bot-roost 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/package.json +3 -3
- package/src/dev/platform.js +19 -7
- package/src/dev/url-guard.js +209 -0
package/README.md
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
|
|
9
9
|
<img src="https://img.shields.io/badge/Node.js-22.13%2B-339933?logo=node.js&logoColor=white" alt="Node.js 22.13+">
|
|
10
10
|
<img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="零依赖">
|
|
11
|
-
<img src="https://img.shields.io/badge/tests-
|
|
11
|
+
<img src="https://img.shields.io/badge/tests-1215%20passed-brightgreen" alt="测试 1215 项">
|
|
12
12
|
<img src="https://img.shields.io/badge/plugins-JS%20%7C%20Python%20%7C%20Go%20%7C%20any-blue" alt="多语言插件">
|
|
13
|
-
<img src="https://img.shields.io/badge/version-1.1.
|
|
13
|
+
<img src="https://img.shields.io/badge/version-1.1.1-blueviolet" alt="版本 1.1.1">
|
|
14
14
|
<img src="https://img.shields.io/badge/license-AGPL--3.0--only-blue" alt="AGPL-3.0-only">
|
|
15
15
|
<a href="https://github.com/tdcq9594/qq-bot-roost/actions"><img src="https://img.shields.io/github/actions/workflow/status/tdcq9594/qq-bot-roost/ci.yml?branch=master" alt="CI"></a>
|
|
16
16
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "qq-bot-roost",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "栖 Roost:零依赖的 QQ 官方机器人框架,填 AppID/AppSecret 即连,插件可写任意语言",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
"start": "node src/main.js",
|
|
30
30
|
"mock": "node src/main.js --mock",
|
|
31
31
|
"check": "node src/main.js --check",
|
|
32
|
-
"test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/gateway-interaction-ack.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs",
|
|
32
|
+
"test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/gateway-interaction-ack.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs && node --test test/url-guard.mjs",
|
|
33
33
|
"test:e2e": "node test/e2e.mjs",
|
|
34
|
-
"test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs",
|
|
34
|
+
"test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs && node --test test/url-guard.mjs",
|
|
35
35
|
"check:secrets": "node scripts/check-secrets.mjs",
|
|
36
36
|
"create": "node scripts/create-plugin.mjs",
|
|
37
37
|
"test:plugin": "node scripts/test-plugin.mjs",
|
package/src/dev/platform.js
CHANGED
|
@@ -37,6 +37,7 @@ import { DIRS } from '../paths.js';
|
|
|
37
37
|
import { createDevSession, parseCookies, bknOf, DEV_HOST, TICKET_KEYS } from './session.js';
|
|
38
38
|
import { DEV_ERRORS, devError } from './errors.js';
|
|
39
39
|
import { createScanLogin } from './browser.js';
|
|
40
|
+
import { fetchImageLimited } from './url-guard.js';
|
|
40
41
|
|
|
41
42
|
export { bknOf, DEV_HOST };
|
|
42
43
|
|
|
@@ -188,7 +189,7 @@ export function isAuthFailure(e) {
|
|
|
188
189
|
/**
|
|
189
190
|
* @param {{log?:(m:string)=>void, fetchImpl?:typeof fetch}} o
|
|
190
191
|
*/
|
|
191
|
-
export function createDevPlatform({ log = () => {}, fetchImpl = fetch } = {}) {
|
|
192
|
+
export function createDevPlatform({ log = () => {}, fetchImpl = fetch, lookup = null } = {}) {
|
|
192
193
|
/**
|
|
193
194
|
* 传输层:**默认走 Node 直发**。
|
|
194
195
|
*
|
|
@@ -1136,12 +1137,23 @@ export function createDevPlatform({ log = () => {}, fetchImpl = fetch } = {}) {
|
|
|
1136
1137
|
|
|
1137
1138
|
const u = String(url || '').trim();
|
|
1138
1139
|
if (!/^https?:\/\//i.test(u)) throw devError('BAD_IMAGE', '要么选一张本地图片,要么填 http(s) 图片地址');
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1140
|
+
/**
|
|
1141
|
+
* 出站校验不能只验 `^https?://`:OneBot 的 `set_qq_profile` 是**模型可触发**的,
|
|
1142
|
+
* 裸 fetch 等于把「让宿主访问任意地址」开给模型(内网 / 云元数据 / 端口探测)。
|
|
1143
|
+
* `fetchImageLimited` 逐跳校验、禁私有地址、按 2MB 流式截断。
|
|
1144
|
+
*/
|
|
1145
|
+
let got;
|
|
1146
|
+
try {
|
|
1147
|
+
got = await fetchImageLimited(u, {
|
|
1148
|
+
maxBytes: AVATAR_MAX_BYTES,
|
|
1149
|
+
fetchImpl,
|
|
1150
|
+
...(lookup ? { lookup } : {}),
|
|
1151
|
+
});
|
|
1152
|
+
} catch (e) {
|
|
1153
|
+
throw devError('BAD_IMAGE', `取图失败:${e?.message ?? e}`);
|
|
1154
|
+
}
|
|
1155
|
+
const type = check(got.type, got.buf.length);
|
|
1156
|
+
return { blob: new Blob([got.buf], { type }), filename: `avatar.${type.split('/')[1] || 'png'}`, bytes: got.buf.length };
|
|
1145
1157
|
}
|
|
1146
1158
|
|
|
1147
1159
|
/**
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 出站图片地址的安全校验
|
|
3
|
+
* ======================
|
|
4
|
+
*
|
|
5
|
+
* 为什么单独一个文件:`readImage` 有三个入口——面板 `/api/dev/avatar`、
|
|
6
|
+
* `ctx.dev.setAvatar`(内核插件)、OneBot `set_qq_profile`(**模型可触发**)。
|
|
7
|
+
* 只验 `^https?://` 等于把「让宿主去 fetch 任意地址」开给模型:内网服务、
|
|
8
|
+
* 云元数据(169.254.169.254)、本机管理端口都能打,错误回显还能当端口探针。
|
|
9
|
+
*
|
|
10
|
+
* 判据与 `dsh-roost/src/ssrf.js` 同一套(那个仓已经在用;两个仓互不依赖,
|
|
11
|
+
* 所以按同样口径各实现一份,改一边要想着另一边):
|
|
12
|
+
*
|
|
13
|
+
* · 只放行 http / https,不许带账号密码
|
|
14
|
+
* · 字面 IP 直接判私有;域名先解析,**任一**地址私有就拒(防 DNS rebinding)
|
|
15
|
+
* · `::ffff:` 映射地址还原成 IPv4 再判——`new URL` 会把
|
|
16
|
+
* `::ffff:127.0.0.1` 规范成 `::ffff:7f00:1`,只认点分会漏
|
|
17
|
+
* · 跟随重定向要**逐跳**再校验,不能只查第一跳
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { isIP } from 'node:net';
|
|
21
|
+
import { lookup as dnsLookup } from 'node:dns/promises';
|
|
22
|
+
|
|
23
|
+
/** 把 IPv6 展开成 8 个 16 位整数;不是合法 IPv6 返回 null */
|
|
24
|
+
function expandV6(ip) {
|
|
25
|
+
const s = String(ip ?? '').toLowerCase().split('%')[0];
|
|
26
|
+
if (isIP(s) !== 6) return null;
|
|
27
|
+
/** 尾部可能是点分 IPv4(`::ffff:127.0.0.1`),先换成两组十六进制 */
|
|
28
|
+
let body = s;
|
|
29
|
+
const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(body);
|
|
30
|
+
if (tail) {
|
|
31
|
+
const p = tail[1].split('.').map(Number);
|
|
32
|
+
if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
|
|
33
|
+
const hi = ((p[0] << 8) | p[1]).toString(16);
|
|
34
|
+
const lo = ((p[2] << 8) | p[3]).toString(16);
|
|
35
|
+
body = `${body.slice(0, -tail[1].length)}${hi}:${lo}`;
|
|
36
|
+
}
|
|
37
|
+
const [head, rest] = body.includes('::') ? body.split('::') : [body, null];
|
|
38
|
+
const a = head ? head.split(':') : [];
|
|
39
|
+
const b = rest ? rest.split(':') : [];
|
|
40
|
+
if (rest !== null && b.length && b[b.length - 1] === '') b.pop();
|
|
41
|
+
const fill = rest === null ? 0 : 8 - a.length - b.length;
|
|
42
|
+
if (fill < 0) return null;
|
|
43
|
+
const groups = [...a, ...Array(rest === null ? 0 : fill).fill('0'), ...b];
|
|
44
|
+
if (groups.length !== 8) return null;
|
|
45
|
+
const out = groups.map((g) => parseInt(g, 16));
|
|
46
|
+
return out.every((n) => Number.isInteger(n) && n >= 0 && n <= 0xffff) ? out : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 取出 IPv6 里**编进去的 IPv4**;没有就返回 ''。
|
|
51
|
+
*
|
|
52
|
+
* 四种形态都要认,否则一条 IPv6 就能绕过全部 IPv4 判断:
|
|
53
|
+
* `::ffff:a.b.c.d`(IPv4-mapped)、`::a.b.c.d`(IPv4-compatible,`::/96`,已废弃但仍可能被路由)、
|
|
54
|
+
* `64:ff9b::/96`(NAT64,NAT64 网关会把它翻回 IPv4)、`2002::/16`(6to4,前 32 位就是 IPv4)
|
|
55
|
+
*/
|
|
56
|
+
function embeddedV4(ip) {
|
|
57
|
+
const h = expandV6(ip);
|
|
58
|
+
if (!h) return '';
|
|
59
|
+
const v4 = (hi, lo) => `${(hi >>> 8) & 255}.${hi & 255}.${(lo >>> 8) & 255}.${lo & 255}`;
|
|
60
|
+
const zeros = (from, to) => h.slice(from, to).every((n) => n === 0);
|
|
61
|
+
/** ::ffff:a.b.c.d —— 前 5 组为 0、第 6 组是 ffff */
|
|
62
|
+
if (zeros(0, 5) && h[5] === 0xffff) return v4(h[6], h[7]);
|
|
63
|
+
/** ::a.b.c.d —— 前 6 组全 0(`::` 与 `::1` 由调用方先排除) */
|
|
64
|
+
if (zeros(0, 6)) return v4(h[6], h[7]);
|
|
65
|
+
/** 64:ff9b::/96 */
|
|
66
|
+
if (h[0] === 0x64 && h[1] === 0xff9b && zeros(2, 6)) return v4(h[6], h[7]);
|
|
67
|
+
/** 2002::/16 —— 6to4 把 IPv4 放在第 2、3 组 */
|
|
68
|
+
if (h[0] === 0x2002) return v4(h[1], h[2]);
|
|
69
|
+
return '';
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** IPv4 / IPv6 的私有、回环、链路本地、保留、组播地址 */
|
|
73
|
+
export function isPrivateIp(ip) {
|
|
74
|
+
const s = String(ip ?? '').toLowerCase().split('%')[0];
|
|
75
|
+
if (!s) return true; // 空地址一律当不安全
|
|
76
|
+
if (isIP(s) === 4) {
|
|
77
|
+
const p = s.split('.').map(Number);
|
|
78
|
+
const [a, b] = p;
|
|
79
|
+
return a === 0 || a === 10 || a === 127
|
|
80
|
+
|| (a === 169 && b === 254) // 链路本地 / 云元数据
|
|
81
|
+
|| (a === 172 && b >= 16 && b <= 31)
|
|
82
|
+
|| (a === 192 && b === 168)
|
|
83
|
+
|| (a === 100 && b >= 64 && b <= 127) // CGNAT
|
|
84
|
+
|| (a === 192 && b === 0 && p[2] === 0)
|
|
85
|
+
|| (a === 198 && (b === 18 || b === 19))
|
|
86
|
+
|| a >= 224; // 组播 + 保留
|
|
87
|
+
}
|
|
88
|
+
if (isIP(s) === 6) {
|
|
89
|
+
if (s === '::' || s === '::1') return true;
|
|
90
|
+
/** 编了 IPv4 的形态一律按里面那个 IPv4 判(映射 / 兼容 / NAT64 / 6to4) */
|
|
91
|
+
const v4 = embeddedV4(s);
|
|
92
|
+
if (v4) return isPrivateIp(v4);
|
|
93
|
+
/** 落在 `::/96` 却认不出映射目标 → fail-closed,别再放行 */
|
|
94
|
+
if (s.startsWith('::')) return true;
|
|
95
|
+
const head = s.split(':')[0];
|
|
96
|
+
if (/^f[cd]/.test(head)) return true; // fc00::/7 唯一本地
|
|
97
|
+
if (/^fe[89ab]/.test(head)) return true; // fe80::/10 链路本地
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* 校验一个出站地址。不合法就抛,消息直接给用户看(中文、说清哪一条不过)。
|
|
105
|
+
*
|
|
106
|
+
* @param {string} raw
|
|
107
|
+
* @param {{lookup?:Function}} [o] `lookup` 只为测试注入,生产用系统解析
|
|
108
|
+
* @returns {Promise<URL>}
|
|
109
|
+
*/
|
|
110
|
+
export async function assertSafeHttpUrl(raw, { lookup = dnsLookup } = {}) {
|
|
111
|
+
let u;
|
|
112
|
+
try {
|
|
113
|
+
u = new URL(String(raw));
|
|
114
|
+
} catch {
|
|
115
|
+
throw new Error('不是合法的地址');
|
|
116
|
+
}
|
|
117
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') {
|
|
118
|
+
throw new Error('只允许 http / https 地址');
|
|
119
|
+
}
|
|
120
|
+
if (u.username || u.password) {
|
|
121
|
+
throw new Error('地址里不许带账号密码');
|
|
122
|
+
}
|
|
123
|
+
const host = u.hostname.replace(/^\[|\]$/g, '');
|
|
124
|
+
if (!host) throw new Error('地址缺少主机名');
|
|
125
|
+
|
|
126
|
+
if (isIP(host)) {
|
|
127
|
+
if (isPrivateIp(host)) throw new Error('不允许访问内网 / 本机地址');
|
|
128
|
+
return u;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
let addrs = [];
|
|
132
|
+
try {
|
|
133
|
+
addrs = await lookup(host, { all: true });
|
|
134
|
+
} catch (e) {
|
|
135
|
+
throw new Error(`解析不了这个域名(${e?.message ?? e})`);
|
|
136
|
+
}
|
|
137
|
+
if (!Array.isArray(addrs) || !addrs.length) throw new Error('这个域名没有解析结果');
|
|
138
|
+
/** 任一地址私有就拒:不能「有公网就放行」——那正是 DNS rebinding 的用法 */
|
|
139
|
+
for (const a of addrs) {
|
|
140
|
+
if (isPrivateIp(a?.address)) throw new Error('这个域名指向内网 / 本机地址,已拒绝');
|
|
141
|
+
}
|
|
142
|
+
return u;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 读响应体,超过上限立刻中止(避免无 content-length 的流把内存顶满) */
|
|
146
|
+
async function readBodyLimited(res, maxBytes) {
|
|
147
|
+
const reader = res.body?.getReader?.();
|
|
148
|
+
if (!reader) {
|
|
149
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
150
|
+
if (buf.length > maxBytes) {
|
|
151
|
+
throw new Error(`这张 ${(buf.length / 1024 / 1024).toFixed(1)} MB,超过 ${maxBytes / 1024 / 1024} MB 上限`);
|
|
152
|
+
}
|
|
153
|
+
return buf;
|
|
154
|
+
}
|
|
155
|
+
const chunks = [];
|
|
156
|
+
let total = 0;
|
|
157
|
+
for (;;) {
|
|
158
|
+
const { done, value } = await reader.read();
|
|
159
|
+
if (done) break;
|
|
160
|
+
total += value?.byteLength ?? 0;
|
|
161
|
+
if (total > maxBytes) {
|
|
162
|
+
try { await reader.cancel(); } catch { /* 已经断了就算了 */ }
|
|
163
|
+
throw new Error(`这张超过 ${maxBytes / 1024 / 1024} MB 上限`);
|
|
164
|
+
}
|
|
165
|
+
chunks.push(Buffer.from(value));
|
|
166
|
+
}
|
|
167
|
+
return Buffer.concat(chunks);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 取一张图:逐跳校验地址、手动跟重定向、按上限流式读取。
|
|
172
|
+
*
|
|
173
|
+
* @param {string} raw
|
|
174
|
+
* @param {{maxBytes:number, fetchImpl?:Function, lookup?:Function,
|
|
175
|
+
* timeoutMs?:number, maxRedirects?:number}} o
|
|
176
|
+
* @returns {Promise<{buf:Buffer, type:string, finalUrl:string}>}
|
|
177
|
+
*/
|
|
178
|
+
export async function fetchImageLimited(raw, {
|
|
179
|
+
maxBytes,
|
|
180
|
+
fetchImpl = fetch,
|
|
181
|
+
lookup = dnsLookup,
|
|
182
|
+
timeoutMs = 15_000,
|
|
183
|
+
maxRedirects = 3,
|
|
184
|
+
} = {}) {
|
|
185
|
+
let cur = String(raw);
|
|
186
|
+
for (let hop = 0; hop <= maxRedirects; hop += 1) {
|
|
187
|
+
await assertSafeHttpUrl(cur, { lookup });
|
|
188
|
+
const res = await fetchImpl(cur, {
|
|
189
|
+
redirect: 'manual',
|
|
190
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
191
|
+
});
|
|
192
|
+
if (res.status >= 300 && res.status < 400) {
|
|
193
|
+
const loc = res.headers.get('location');
|
|
194
|
+
if (!loc) throw new Error(`取图被重定向(HTTP ${res.status})但没给目标地址`);
|
|
195
|
+
/** 相对地址要按当前跳解析;下一轮会再校验它是否私有 */
|
|
196
|
+
cur = new URL(loc, cur).href;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (!res.ok) throw new Error(`取图失败(HTTP ${res.status})`);
|
|
200
|
+
const type = String(res.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
|
|
201
|
+
const declared = Number(res.headers.get('content-length') || 0);
|
|
202
|
+
if (declared > maxBytes) {
|
|
203
|
+
throw new Error(`这张 ${(declared / 1024 / 1024).toFixed(1)} MB,超过 ${maxBytes / 1024 / 1024} MB 上限`);
|
|
204
|
+
}
|
|
205
|
+
const buf = await readBodyLimited(res, maxBytes);
|
|
206
|
+
return { buf, type, finalUrl: cur };
|
|
207
|
+
}
|
|
208
|
+
throw new Error('重定向次数太多,已放弃');
|
|
209
|
+
}
|