@duanz/pi-d-reach 1.0.0 → 1.0.2
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/SKILL.md +7 -5
- package/package.json +1 -1
- package/plugin/index.ts +600 -378
- package/plugin/pwa.ts +93 -21
- package/plugin/runtime.ts +771 -0
- package/plugin/scripts/fanout.sh +290 -140
- package/plugin/scripts/mcp_call.py +39 -3
- package/plugin/scripts/quota.py +49 -11
- package/plugin/scripts/quota_probe.py +31 -8
- package/plugin/scripts/render.mjs +164 -5
- package/references/channels.md +6 -5
- package/scripts/fanout.sh +290 -140
- package/scripts/mcp_call.py +39 -3
- package/scripts/quota.py +49 -11
- package/scripts/quota_probe.py +31 -8
|
@@ -15,6 +15,7 @@ Parallel 的免费档三个工具都是「问一次答一次」,用不上那
|
|
|
15
15
|
import json
|
|
16
16
|
import os
|
|
17
17
|
import sys
|
|
18
|
+
import time
|
|
18
19
|
import urllib.error
|
|
19
20
|
import urllib.request
|
|
20
21
|
|
|
@@ -22,7 +23,20 @@ PROTO = "2024-11-05"
|
|
|
22
23
|
TIMEOUT = 40
|
|
23
24
|
|
|
24
25
|
|
|
25
|
-
def
|
|
26
|
+
def _budget_secs() -> float:
|
|
27
|
+
raw = os.environ.get("D_REACH_MCP_BUDGET", "").strip()
|
|
28
|
+
if not raw:
|
|
29
|
+
return 45.0
|
|
30
|
+
try:
|
|
31
|
+
val = float(raw)
|
|
32
|
+
return val if val > 0 else 45.0
|
|
33
|
+
except ValueError:
|
|
34
|
+
return 45.0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _post(
|
|
38
|
+
endpoint: str, body: dict, session: str | None, timeout: float = TIMEOUT
|
|
39
|
+
) -> tuple[str, str | None]:
|
|
26
40
|
data = json.dumps(body).encode()
|
|
27
41
|
req = urllib.request.Request(endpoint, data=data, method="POST")
|
|
28
42
|
req.add_header("Content-Type", "application/json")
|
|
@@ -37,7 +51,7 @@ def _post(endpoint: str, body: dict, session: str | None) -> tuple[str, str | No
|
|
|
37
51
|
req.add_header("MCP-Protocol-Version", PROTO)
|
|
38
52
|
if session:
|
|
39
53
|
req.add_header("Mcp-Session-Id", session)
|
|
40
|
-
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
|
|
54
|
+
with urllib.request.urlopen(req, timeout=max(0.05, min(TIMEOUT, timeout))) as resp:
|
|
41
55
|
raw = resp.read().decode("utf-8", "replace")
|
|
42
56
|
sid = resp.headers.get("Mcp-Session-Id") or session
|
|
43
57
|
return raw, sid
|
|
@@ -76,6 +90,13 @@ def main() -> int:
|
|
|
76
90
|
print(f"MCP_ERROR: 参数不是合法 JSON({e})")
|
|
77
91
|
return 1
|
|
78
92
|
|
|
93
|
+
budget = _budget_secs()
|
|
94
|
+
deadline = time.monotonic() + budget
|
|
95
|
+
|
|
96
|
+
rem = deadline - time.monotonic()
|
|
97
|
+
if rem <= 0:
|
|
98
|
+
print(f"MCP_ERROR: 总超时({budget:g}s)")
|
|
99
|
+
return 1
|
|
79
100
|
try:
|
|
80
101
|
raw, sid = _post(
|
|
81
102
|
endpoint,
|
|
@@ -90,6 +111,7 @@ def main() -> int:
|
|
|
90
111
|
},
|
|
91
112
|
},
|
|
92
113
|
None,
|
|
114
|
+
timeout=min(TIMEOUT, rem),
|
|
93
115
|
)
|
|
94
116
|
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
95
117
|
print(f"MCP_ERROR: initialize 失败({e})")
|
|
@@ -99,11 +121,24 @@ def main() -> int:
|
|
|
99
121
|
return 1
|
|
100
122
|
|
|
101
123
|
# notifications/initialized 是单向通知,服务端可能回 202 空体,失败也无所谓
|
|
124
|
+
rem = deadline - time.monotonic()
|
|
125
|
+
if rem <= 0:
|
|
126
|
+
print(f"MCP_ERROR: 总超时({budget:g}s)")
|
|
127
|
+
return 1
|
|
102
128
|
try:
|
|
103
|
-
_post(
|
|
129
|
+
_post(
|
|
130
|
+
endpoint,
|
|
131
|
+
{"jsonrpc": "2.0", "method": "notifications/initialized"},
|
|
132
|
+
sid,
|
|
133
|
+
timeout=min(TIMEOUT, rem),
|
|
134
|
+
)
|
|
104
135
|
except (urllib.error.URLError, TimeoutError, OSError):
|
|
105
136
|
pass
|
|
106
137
|
|
|
138
|
+
rem = deadline - time.monotonic()
|
|
139
|
+
if rem <= 0:
|
|
140
|
+
print(f"MCP_ERROR: 总超时({budget:g}s)")
|
|
141
|
+
return 1
|
|
107
142
|
try:
|
|
108
143
|
raw, _ = _post(
|
|
109
144
|
endpoint,
|
|
@@ -114,6 +149,7 @@ def main() -> int:
|
|
|
114
149
|
"params": {"name": tool, "arguments": args},
|
|
115
150
|
},
|
|
116
151
|
sid,
|
|
152
|
+
timeout=min(TIMEOUT, rem),
|
|
117
153
|
)
|
|
118
154
|
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
119
155
|
print(f"MCP_ERROR: tools/call 失败({e})")
|
package/plugin/scripts/quota.py
CHANGED
|
@@ -17,11 +17,13 @@
|
|
|
17
17
|
Firecrawl Research Index(论文端点)官方明确免费,本技能也不记账。
|
|
18
18
|
免 Key 不限量通道(Firecrawl Dev Index / TinyFish / StackExchange / HN / OpenAlex / Crossref / 掘金 / gh …)不记账。
|
|
19
19
|
"""
|
|
20
|
+
import calendar
|
|
20
21
|
import contextlib
|
|
21
22
|
import fcntl
|
|
22
23
|
import json
|
|
23
24
|
import os
|
|
24
25
|
import sys
|
|
26
|
+
import threading
|
|
25
27
|
from datetime import datetime, timezone
|
|
26
28
|
from pathlib import Path
|
|
27
29
|
|
|
@@ -75,9 +77,28 @@ def _load():
|
|
|
75
77
|
return d
|
|
76
78
|
|
|
77
79
|
|
|
80
|
+
def _reset_stale_buckets(d, now=None):
|
|
81
|
+
"""写回前归零已跨月/跨日的旧服务桶,避免过时计数滞留磁盘。"""
|
|
82
|
+
now = now or datetime.now(timezone.utc)
|
|
83
|
+
cur_month = now.strftime("%Y-%m")
|
|
84
|
+
cur_day = now.strftime("%Y-%m-%d")
|
|
85
|
+
for svc, b in list(d.items()):
|
|
86
|
+
if svc.startswith("_") or not isinstance(b, dict):
|
|
87
|
+
continue
|
|
88
|
+
if b.get("month") != cur_month or b.get("day") != cur_day:
|
|
89
|
+
_bucket(d, svc, now=now)
|
|
90
|
+
|
|
91
|
+
|
|
78
92
|
def _save(d):
|
|
93
|
+
_reset_stale_buckets(d)
|
|
79
94
|
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
-
FILE.
|
|
95
|
+
tmp = FILE.with_name(f"{FILE.name}.tmp.{os.getpid()}.{threading.get_ident()}")
|
|
96
|
+
try:
|
|
97
|
+
tmp.write_text(json.dumps(d, indent=2, ensure_ascii=False))
|
|
98
|
+
tmp.replace(FILE)
|
|
99
|
+
except Exception:
|
|
100
|
+
tmp.unlink(missing_ok=True)
|
|
101
|
+
raise
|
|
81
102
|
|
|
82
103
|
|
|
83
104
|
@contextlib.contextmanager
|
|
@@ -88,7 +109,7 @@ def _locked():
|
|
|
88
109
|
并发量真上去(>50 进程/秒)再换 per-service 锁。
|
|
89
110
|
"""
|
|
90
111
|
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
91
|
-
lock_path = FILE.
|
|
112
|
+
lock_path = FILE.with_name(FILE.name + ".lock")
|
|
92
113
|
with open(lock_path, "a+") as fh:
|
|
93
114
|
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
94
115
|
try:
|
|
@@ -97,18 +118,30 @@ def _locked():
|
|
|
97
118
|
fcntl.flock(fh, fcntl.LOCK_UN)
|
|
98
119
|
|
|
99
120
|
|
|
100
|
-
def
|
|
121
|
+
def _nonneg_int(val):
|
|
122
|
+
try:
|
|
123
|
+
n = int(val)
|
|
124
|
+
return n if n >= 0 else 0
|
|
125
|
+
except (TypeError, ValueError):
|
|
126
|
+
return 0
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _bucket(d, svc, now=None):
|
|
101
130
|
"""跨月/跨日自动归零。"""
|
|
102
|
-
now = datetime.now(timezone.utc)
|
|
131
|
+
now = now or datetime.now(timezone.utc)
|
|
132
|
+
cur_month = now.strftime("%Y-%m")
|
|
133
|
+
cur_day = now.strftime("%Y-%m-%d")
|
|
103
134
|
b = d.get(svc)
|
|
104
135
|
if not isinstance(b, dict):
|
|
105
|
-
b = {"month":
|
|
106
|
-
"monthly": 0, "daily": 0}
|
|
136
|
+
b = {"month": cur_month, "day": cur_day, "monthly": 0, "daily": 0}
|
|
107
137
|
d[svc] = b
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
138
|
+
return b
|
|
139
|
+
b["monthly"] = _nonneg_int(b.get("monthly"))
|
|
140
|
+
b["daily"] = _nonneg_int(b.get("daily"))
|
|
141
|
+
if b.get("month") != cur_month:
|
|
142
|
+
b["monthly"], b["month"] = 0, cur_month
|
|
143
|
+
if b.get("day") != cur_day:
|
|
144
|
+
b["daily"], b["day"] = 0, cur_day
|
|
112
145
|
return b
|
|
113
146
|
|
|
114
147
|
|
|
@@ -175,7 +208,7 @@ SPEND_WARN_USD = 20.0
|
|
|
175
208
|
def _budget(d):
|
|
176
209
|
"""给 agent 看的规划视图:到裕度线还剩多少,以及今日可用建议。"""
|
|
177
210
|
now = datetime.now(timezone.utc)
|
|
178
|
-
days_in_month =
|
|
211
|
+
days_in_month = calendar.monthrange(now.year, now.month)[1]
|
|
179
212
|
days_left = max(days_in_month - now.day + 1, 1)
|
|
180
213
|
lines, advice = [], []
|
|
181
214
|
lines.append(f"裕度:保留 {RESERVE:.0%}(裕度线 = 上限的 {1 - RESERVE:.0%});"
|
|
@@ -222,6 +255,11 @@ def _budget(d):
|
|
|
222
255
|
if st == "ok" and name == "firecrawl":
|
|
223
256
|
out += (f"\n {name}: 剩余 {v.get('remaining')}/{v.get('total')} credits"
|
|
224
257
|
f",账期至 {str(v.get('period_end'))[:10]}")
|
|
258
|
+
elif st == "ok" and name == "brightdata":
|
|
259
|
+
_note = v.get("unit_note") or ""
|
|
260
|
+
out += (f"\n {name}: 剩余 {v.get('remaining')}/{v.get('total')} credits"
|
|
261
|
+
f",账期至 {str(v.get('period_end'))[:10]}"
|
|
262
|
+
+ (f"({_note.split(';')[0]})" if _note else ""))
|
|
225
263
|
elif st == "ok" and name == "tinyfish":
|
|
226
264
|
out += f"\n {name}: 钱包 {v.get('balance')} {v.get('currency')}"
|
|
227
265
|
elif st == "ok":
|
|
@@ -18,10 +18,13 @@
|
|
|
18
18
|
jina 只有 dashboard,无公开额度 API
|
|
19
19
|
langsearch 官方只给 token 日额度,无查询端点
|
|
20
20
|
"""
|
|
21
|
+
import contextlib
|
|
22
|
+
import fcntl
|
|
21
23
|
import json
|
|
22
24
|
import os
|
|
23
25
|
import re
|
|
24
26
|
import sys
|
|
27
|
+
import threading
|
|
25
28
|
import time
|
|
26
29
|
import urllib.request
|
|
27
30
|
from concurrent.futures import ThreadPoolExecutor
|
|
@@ -167,24 +170,43 @@ PROBES = {
|
|
|
167
170
|
}
|
|
168
171
|
|
|
169
172
|
|
|
173
|
+
@contextlib.contextmanager
|
|
174
|
+
def _locked():
|
|
175
|
+
"""与 quota.py 共用同一把锁,避免官方校准覆盖并发计数写入。"""
|
|
176
|
+
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
177
|
+
lock_path = FILE.with_name(FILE.name + ".lock")
|
|
178
|
+
with open(lock_path, "a+") as fh:
|
|
179
|
+
fcntl.flock(fh, fcntl.LOCK_EX)
|
|
180
|
+
try:
|
|
181
|
+
yield
|
|
182
|
+
finally:
|
|
183
|
+
fcntl.flock(fh, fcntl.LOCK_UN)
|
|
184
|
+
|
|
185
|
+
|
|
170
186
|
def load():
|
|
171
187
|
try:
|
|
172
|
-
|
|
188
|
+
d = json.loads(FILE.read_text())
|
|
189
|
+
return d if isinstance(d, dict) else {}
|
|
173
190
|
except Exception:
|
|
174
191
|
return {}
|
|
175
192
|
|
|
176
193
|
|
|
177
194
|
def save(d):
|
|
178
195
|
FILE.parent.mkdir(parents=True, exist_ok=True)
|
|
179
|
-
tmp = FILE.
|
|
180
|
-
|
|
181
|
-
|
|
196
|
+
tmp = FILE.with_name(f"{FILE.name}.tmp.{os.getpid()}.{threading.get_ident()}")
|
|
197
|
+
try:
|
|
198
|
+
tmp.write_text(json.dumps(d, indent=2))
|
|
199
|
+
tmp.replace(FILE)
|
|
200
|
+
except Exception:
|
|
201
|
+
tmp.unlink(missing_ok=True)
|
|
202
|
+
raise
|
|
182
203
|
|
|
183
204
|
|
|
184
205
|
def run(max_age=0):
|
|
185
206
|
"""max_age>0 时:如果上次校准已在 N 秒内,直接复用,不重复请求厂商接口。"""
|
|
186
207
|
if max_age:
|
|
187
|
-
|
|
208
|
+
with _locked():
|
|
209
|
+
old = (load().get("_official") or {})
|
|
188
210
|
stamps = [v.get("probed_at") for v in old.values() if v.get("state") == "ok"]
|
|
189
211
|
if stamps:
|
|
190
212
|
try:
|
|
@@ -204,9 +226,10 @@ def run(max_age=0):
|
|
|
204
226
|
stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
205
227
|
for v in out.values():
|
|
206
228
|
v["probed_at"] = stamp
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
229
|
+
with _locked():
|
|
230
|
+
d = load()
|
|
231
|
+
d["_official"] = out
|
|
232
|
+
save(d)
|
|
210
233
|
return out
|
|
211
234
|
|
|
212
235
|
|
|
@@ -5,21 +5,160 @@
|
|
|
5
5
|
* 为什么单独一个进程:扩展由 pi 用 TS 加载,直接 import playwright 会撞模块解析;
|
|
6
6
|
* 起子进程最省事,也让「没装 playwright」变成可判定的 fail class 而不是崩溃。
|
|
7
7
|
*
|
|
8
|
-
* 用法:node render.mjs <url>
|
|
8
|
+
* 用法:node render.mjs <url> [--allow-private]
|
|
9
9
|
* 输出:单行 JSON { ok, text, html, chars, lines, avgLine, linkDen, finalUrl, ms, err }
|
|
10
10
|
* - text 是正文(优先 article/main/#js_content,退回 body.innerText),保留换行
|
|
11
11
|
* - html 只截前 200KB,够做站点标记判定
|
|
12
12
|
* - lines / avgLine / linkDen 是「骨架页」判据,调用方据此拒绝假装成功
|
|
13
13
|
* - finalUrl 是跳转后的真实地址,登录墙(passport./login./sso.)靠它识别
|
|
14
14
|
*/
|
|
15
|
+
import { lookup } from "node:dns/promises";
|
|
16
|
+
import { isIP } from "node:net";
|
|
15
17
|
import { pathToFileURL } from "node:url";
|
|
16
18
|
|
|
17
|
-
const
|
|
19
|
+
const argv = process.argv.slice(2);
|
|
20
|
+
const allowPrivate = argv.includes("--allow-private");
|
|
21
|
+
const url = argv.find((a) => !a.startsWith("--"));
|
|
18
22
|
if (!url) {
|
|
19
23
|
console.log(JSON.stringify({ ok: false, err: "no_url" }));
|
|
20
24
|
process.exit(0);
|
|
21
25
|
}
|
|
22
26
|
|
|
27
|
+
function normalizeHost(hostname) {
|
|
28
|
+
return hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function parseIPv4(ip) {
|
|
32
|
+
const parts = ip.split(".");
|
|
33
|
+
if (parts.length !== 4) return null;
|
|
34
|
+
const nums = parts.map((p) => (/^\d+$/.test(p) ? Number(p) : NaN));
|
|
35
|
+
if (nums.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return null;
|
|
36
|
+
return nums;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function ipv4IsPrivate(n) {
|
|
40
|
+
const [a, b, c] = n;
|
|
41
|
+
if (a === 0 || a === 10 || a === 127) return true;
|
|
42
|
+
if (a === 100 && b >= 64 && b <= 127) return true;
|
|
43
|
+
if (a === 169 && b === 254) return true;
|
|
44
|
+
if (a === 172 && b >= 16 && b <= 31) return true;
|
|
45
|
+
if (a === 192 && b === 168) return true;
|
|
46
|
+
if (a === 192 && b === 0 && (c === 0 || c === 2)) return true;
|
|
47
|
+
if (a === 192 && b === 88 && c === 99) return true;
|
|
48
|
+
if (a === 198 && (b === 18 || b === 19)) return true;
|
|
49
|
+
if (a === 198 && b === 51 && c === 100) return true;
|
|
50
|
+
if (a === 203 && b === 0 && c === 113) return true;
|
|
51
|
+
if (a >= 224) return true;
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function ipv6Bytes(ip) {
|
|
56
|
+
let s = ip.toLowerCase().replace(/%.*$/, "");
|
|
57
|
+
if (s.includes(".")) {
|
|
58
|
+
const idx = s.lastIndexOf(":");
|
|
59
|
+
const v4 = parseIPv4(s.slice(idx + 1));
|
|
60
|
+
if (!v4) return null;
|
|
61
|
+
s =
|
|
62
|
+
s.slice(0, idx + 1) +
|
|
63
|
+
((v4[0] << 8) | v4[1]).toString(16) +
|
|
64
|
+
":" +
|
|
65
|
+
((v4[2] << 8) | v4[3]).toString(16);
|
|
66
|
+
}
|
|
67
|
+
const halves = s.split("::");
|
|
68
|
+
if (halves.length > 2) return null;
|
|
69
|
+
const head = halves[0] ? halves[0].split(":") : [];
|
|
70
|
+
const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
71
|
+
const missing = 8 - head.length - tail.length;
|
|
72
|
+
if (halves.length === 1 && head.length !== 8) return null;
|
|
73
|
+
if (missing < 0) return null;
|
|
74
|
+
const groups = [
|
|
75
|
+
...head,
|
|
76
|
+
...Array(halves.length === 2 ? missing : 0).fill("0"),
|
|
77
|
+
...tail,
|
|
78
|
+
];
|
|
79
|
+
if (groups.length !== 8) return null;
|
|
80
|
+
const out = [];
|
|
81
|
+
for (const g of groups) {
|
|
82
|
+
if (!/^[0-9a-f]{1,4}$/.test(g)) return null;
|
|
83
|
+
const v = parseInt(g, 16);
|
|
84
|
+
out.push(v >> 8, v & 0xff);
|
|
85
|
+
}
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function ipv6IsPrivate(b) {
|
|
90
|
+
if (b.every((x) => x === 0)) return true;
|
|
91
|
+
if (b.slice(0, 15).every((x) => x === 0) && b[15] === 1) return true;
|
|
92
|
+
if (b.slice(0, 10).every((x) => x === 0) && b[10] === 0xff && b[11] === 0xff)
|
|
93
|
+
return ipv4IsPrivate(b.slice(12));
|
|
94
|
+
if (b.slice(0, 12).every((x) => x === 0)) return ipv4IsPrivate(b.slice(12));
|
|
95
|
+
if (
|
|
96
|
+
b[0] === 0x00 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b &&
|
|
97
|
+
b.slice(4, 12).every((x) => x === 0)
|
|
98
|
+
)
|
|
99
|
+
return ipv4IsPrivate(b.slice(12));
|
|
100
|
+
if ((b[0] & 0xfe) === 0xfc) return true;
|
|
101
|
+
if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) return true;
|
|
102
|
+
if (b[0] === 0xff) return true;
|
|
103
|
+
if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0x0d && b[3] === 0xb8) return true;
|
|
104
|
+
if (b.slice(0, 8).every((x) => x === 0) && b[8] === 1 && b.slice(9).every((x) => x === 0))
|
|
105
|
+
return true;
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function isPrivateIp(ip) {
|
|
110
|
+
const v4 = parseIPv4(ip);
|
|
111
|
+
if (v4) return ipv4IsPrivate(v4);
|
|
112
|
+
if (ip.includes(":")) {
|
|
113
|
+
const bytes = ipv6Bytes(ip);
|
|
114
|
+
return bytes ? ipv6IsPrivate(bytes) : false;
|
|
115
|
+
}
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function isBlockedHostname(host) {
|
|
120
|
+
const h = normalizeHost(host);
|
|
121
|
+
return (
|
|
122
|
+
!h ||
|
|
123
|
+
h === "localhost" ||
|
|
124
|
+
h.endsWith(".localhost") ||
|
|
125
|
+
h.endsWith(".local") ||
|
|
126
|
+
h.endsWith(".internal") ||
|
|
127
|
+
h.endsWith(".home.arpa")
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 校验请求 URL 是否允许发起:禁非 http(s),未放行私网时拦截内网主机与 DNS 解析到的内网 IP。 */
|
|
132
|
+
async function checkRequestTarget(rawUrl) {
|
|
133
|
+
let u;
|
|
134
|
+
try {
|
|
135
|
+
u = new URL(rawUrl);
|
|
136
|
+
} catch {
|
|
137
|
+
return "目标 URL 非法";
|
|
138
|
+
}
|
|
139
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") {
|
|
140
|
+
return `协议不被允许(${u.protocol})`;
|
|
141
|
+
}
|
|
142
|
+
if (allowPrivate) return null;
|
|
143
|
+
const host = normalizeHost(u.hostname);
|
|
144
|
+
if (isBlockedHostname(host)) {
|
|
145
|
+
return `内网/本机主机名被拦截(${host || "empty"})`;
|
|
146
|
+
}
|
|
147
|
+
if (isIP(host)) {
|
|
148
|
+
return isPrivateIp(host) ? `内网/保留 IP 被拦截(${host})` : null;
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
const addrs = await lookup(host, { all: true, verbatim: true });
|
|
152
|
+
const priv = addrs.find((a) => isPrivateIp(a.address));
|
|
153
|
+
if (priv) {
|
|
154
|
+
return `域名 ${host} 解析到内网地址(${priv.address}),已拦截`;
|
|
155
|
+
}
|
|
156
|
+
} catch {
|
|
157
|
+
// DNS 失败交给浏览器自然报错,不伪造 SSRF
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
|
|
23
162
|
const UA =
|
|
24
163
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36";
|
|
25
164
|
|
|
@@ -168,7 +307,13 @@ async function iframeText(page) {
|
|
|
168
307
|
|
|
169
308
|
const t0 = Date.now();
|
|
170
309
|
let browser;
|
|
310
|
+
let blockedReason = "";
|
|
171
311
|
try {
|
|
312
|
+
const initialBlock = await checkRequestTarget(url);
|
|
313
|
+
if (initialBlock) {
|
|
314
|
+
blockedReason = initialBlock;
|
|
315
|
+
throw new Error(`SSRF_BLOCKED: ${initialBlock}`);
|
|
316
|
+
}
|
|
172
317
|
const chromium = await loadChromium();
|
|
173
318
|
browser = await chromium.launch({ headless: true });
|
|
174
319
|
const ctx = await browser.newContext({
|
|
@@ -178,6 +323,18 @@ try {
|
|
|
178
323
|
extraHTTPHeaders: { "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8" },
|
|
179
324
|
});
|
|
180
325
|
const page = await ctx.newPage();
|
|
326
|
+
await page.route("**/*", async (route) => {
|
|
327
|
+
const req = route.request();
|
|
328
|
+
const reason = await checkRequestTarget(req.url());
|
|
329
|
+
if (reason) {
|
|
330
|
+
if (req.isNavigationRequest() && req.frame() === page.mainFrame()) {
|
|
331
|
+
blockedReason = reason;
|
|
332
|
+
}
|
|
333
|
+
await route.abort();
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
await route.continue();
|
|
337
|
+
});
|
|
181
338
|
const resp = await page.goto(url, {
|
|
182
339
|
waitUntil: "domcontentloaded",
|
|
183
340
|
timeout: TIMEOUT_MS,
|
|
@@ -225,9 +382,11 @@ try {
|
|
|
225
382
|
} catch (e) {
|
|
226
383
|
const msg = e instanceof Error ? e.message.slice(0, 200) : String(e);
|
|
227
384
|
// PDF/图片直链:chromium 不渲染,它直接开始下载
|
|
228
|
-
const err =
|
|
229
|
-
?
|
|
230
|
-
: msg
|
|
385
|
+
const err = blockedReason
|
|
386
|
+
? `SSRF_BLOCKED: ${blockedReason}`
|
|
387
|
+
: /Download is starting/i.test(msg)
|
|
388
|
+
? "NOT_A_PAGE: 直接下载,不是网页"
|
|
389
|
+
: msg;
|
|
231
390
|
console.log(JSON.stringify({ ok: false, err, ms: Date.now() - t0 }));
|
|
232
391
|
} finally {
|
|
233
392
|
if (browser) await browser.close().catch(() => {});
|
package/references/channels.md
CHANGED
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
### `fcdev` Firecrawl Developer Index · 编程一手源
|
|
40
40
|
- **擅长**:**官方文档、API 参数、GitHub README、issue**。7000 万+ 编程文档索引,查「某个 API 怎么调」「某个库的参数」最准。
|
|
41
41
|
- **不擅长**:非技术话题完全无用;中文文档覆盖少。
|
|
42
|
-
-
|
|
42
|
+
- **代价**:没 key 走 keyless 免费档(IP 级额度,耗尽后 429 要等十几小时,实测 `retry_after_seconds: 40699`);有 key 时优先走 key,请求前过 `gate firecrawl`、成功后记 1 credit(受 firecrawl 月度额度闸门)。
|
|
43
43
|
- **别用它做**:问旅行、问产品评测、问新闻。
|
|
44
44
|
|
|
45
45
|
### `se` StackExchange · 报错排障
|
|
@@ -119,10 +119,11 @@
|
|
|
119
119
|
- **代价**:0(不记账)。
|
|
120
120
|
- **别用它做**:需要精确控制检索域的场景(它不接受 includeDomains 类参数)。
|
|
121
121
|
|
|
122
|
-
### `youcom` You.com
|
|
123
|
-
- **擅长**:官方定价页明写「No API key, no account, no credit card
|
|
124
|
-
-
|
|
125
|
-
-
|
|
122
|
+
### `youcom` You.com 搜索 · 按需快搜
|
|
123
|
+
- **擅长**:官方定价页明写「No API key, no account, no credit card」,免 Key 档走 `https://api.you.com/mcp?profile=free` 的 `you-search`。官方称 p50 0.4s(实测 2.2s),结果带 `page_age` 日期和 `contents.highlights` 整段摘录,中文实测质量高(门票类问题直接给出各景点票价)。
|
|
124
|
+
- **不擅长**:免 Key 免费档每天 100 次;该网关会 **403 掉 `Python-urllib` 默认 UA**(`scripts/mcp_call.py` 里已固定 `d-reach/1.0`)。
|
|
125
|
+
- **代价**:免 Key 档 0(不记账,受免 Key 100 次/天限制)。配 `YOU_API_KEY` 时走官方 REST,按次计费(Standard $5/1k),请求前过 `gate youcom` 的 100 次/天闸门、成功后记一次账;**有付费 key 时不做中英双查**(只打一版,避免一轮扣两次)。
|
|
126
|
+
- **别用它做**:一天超过 100 次的批量检索;也不要当默认底座(已从 `AUTO_BASE` 移除,只在模型点名时跑)。
|
|
126
127
|
- **别用它做**:一天超过 100 次的批量检索。
|
|
127
128
|
|
|
128
129
|
### `anysearch` AnySearch · 垂直专库
|