edgeone 1.6.48 → 1.7.0

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.
@@ -27,6 +27,11 @@ from .store import InMemoryStore, BlobBackedStore
27
27
  from .runtime import AgentRuntime, RouteEntry
28
28
  from .context import EoContext, StreamResponse
29
29
 
30
+ # 外网访问拦截:import 时自动安装 socket.create_connection hook。
31
+ # 请求入口通过 set_restricted / reset_restricted 传递每次请求的标志位。
32
+ # dev 模式或 EDGEONE_OUTBOUND_HOOK_DISABLED=1 时 hook 不会实际拦截。
33
+ from . import net_hook as _edgeone_net_hook
34
+
30
35
 
31
36
  # --- Geo parsing (aligns with Node agent-node.ts parseEoConnectingGeo) ---
32
37
 
@@ -506,6 +511,28 @@ async def app(scope: dict, receive, send) -> None:
506
511
  if scope["type"] != "http":
507
512
  return
508
513
 
514
+ # 请求进入就打会话 ID。结束日志要等 runtime.handle 返回才有 statusCode,
515
+ # 长请求的第一条 ClickHouse 记录会缺 conversation_id。这里在读 body / 进 runtime 之前打,并 flush。
516
+ _enter_headers = {
517
+ (k.decode("utf-8") if isinstance(k, bytes) else k).lower(): (
518
+ v.decode("utf-8") if isinstance(v, bytes) else v
519
+ )
520
+ for k, v in scope.get("headers", [])
521
+ }
522
+ _enter_path = scope.get("path", "/") or "/"
523
+ _enter_host = _enter_headers.get("eo-pages-host", "") or _enter_headers.get("host", "")
524
+ _enter_full_path = _enter_path
525
+ if _enter_host:
526
+ _enter_proto = str(_enter_headers.get("x-forwarded-proto", "") or "").split(",")[0].strip().lower() or "https"
527
+ _enter_full_path = f"{_enter_proto}://{_enter_host}{_enter_path}"
528
+ _enter_request_id = _enter_headers.get("x-scf-request-id", "") or ""
529
+ _enter_conv_id = _enter_headers.get("makers-conversation-id") or _enter_headers.get("conversation-id") or ""
530
+ print(
531
+ f"Makers request path: {_enter_full_path} |scfRequestId={_enter_request_id}|conversationId={_enter_conv_id}|",
532
+ file=sys.stderr,
533
+ flush=True,
534
+ )
535
+
509
536
  # --- MCP endpoint:拦截 /mcp(及 /mcp/*),交给 MCP session manager 处理 JSON-RPC。---
510
537
  # 对齐 Node agent-node.ts 的 requestHandler /mcp 拦截。透传 ASGI 三件套即可,
511
538
  # 无需自己读body(StreamableHTTPSessionManager 内部处理)。
@@ -597,7 +624,14 @@ async def app(scope: dict, receive, send) -> None:
597
624
  else:
598
625
  headers.pop("makers-user-id", None)
599
626
 
600
- # 计算完整请求路径和 scfRequestId(日志合并到 response 后统一打印)
627
+ # ---- 外网访问拦截 · 请求级 restricted 标志 ----
628
+ # 网关保证下游收到的头是最终态(用户请求头中的 x-cube-* 已被剥离)。
629
+ # headers 只交给 runtime.handle 消费,不回写业务侧,天然不透传。
630
+ _outer_restricted = str(headers.get("x-cube-outer-flux-restricted", "")).lower() == "true"
631
+ _outer_request_id = str(headers.get("x-scf-request-id", "") or "")
632
+ _net_hook_token = _edgeone_net_hook.set_restricted(_outer_restricted, _outer_request_id)
633
+
634
+ # 计算完整请求路径和 scfRequestId。会话 ID 已在请求进入时打过;这里只补 statusCode。
601
635
  _pages_host = headers.get("eo-pages-host", "") or headers.get("host", "")
602
636
  _pages_full_path = path
603
637
  if _pages_host:
@@ -927,6 +961,11 @@ async def app(scope: dict, receive, send) -> None:
927
961
  clear_request_context()
928
962
  except (ImportError, Exception):
929
963
  pass
964
+ # Reset outbound restricted ContextVar
965
+ try:
966
+ _edgeone_net_hook.reset_restricted(_net_hook_token)
967
+ except Exception:
968
+ pass
930
969
  return
931
970
 
932
971
  # ───────── 非流式分支(旧行为,原样保留) ─────────
@@ -981,6 +1020,11 @@ async def app(scope: dict, receive, send) -> None:
981
1020
  clear_request_context()
982
1021
  except (ImportError, Exception):
983
1022
  pass
1023
+ # Reset outbound restricted ContextVar
1024
+ try:
1025
+ _edgeone_net_hook.reset_restricted(_net_hook_token)
1026
+ except Exception:
1027
+ pass
984
1028
 
985
1029
 
986
1030
  def _encode_stream_chunk(chunk: Any) -> bytes:
@@ -0,0 +1,271 @@
1
+ # src/pages/builder/templates/agent-python/net_hook.py
2
+ """Cloud-function 外网访问拦截 · Python runtime 侧共用注入模块
3
+
4
+ 覆盖 runtime:
5
+ - agent-python(本目录会被 Step 4 复制到部署包 _platform/ 下)
6
+ - python-function(把该文件内容内联到 app.py,见 python-function.ts 的
7
+ generateAppPy 中的 net_hook 内联字段)
8
+
9
+ 设计要点:
10
+ 1. 只 hook socket.create_connection —— stdlib http.client / requests /
11
+ httpx / urllib3 / aiohttp 底层全部走这条路径;hook 一处即可覆盖。
12
+ 2. 使用 contextvars.ContextVar 传递「当前请求是否 restricted」,兼容 WSGI
13
+ (线程池) 与 ASGI (asyncio) 两种模式。
14
+ 3. hook 幂等:模块级 _HOOKED 标记,避免重复包装 socket 模块。
15
+ 4. 白名单(编译期 + 环境变量):
16
+ 静态 suffix:.edgeone.site / .tencentyun.com
17
+ 静态 host:localhost / ip6-localhost / ip6-loopback
18
+ 环境变量:EDGEONE_OTLP_ENDPOINT / EDGEONE_OUTBOUND_BYPASS_HOSTS
19
+ loopback:127.0.0.0/8 / ::1
20
+ 5. 灰度开关:
21
+ EDGEONE_OUTBOUND_HOOK_DISABLED=1 → 不 hook
22
+ EDGEONE_OUTBOUND_HOOK_MODE=observe → 只打日志不拦
23
+ 6. 抛出 OutboundRestrictedError(OSError 子类),走标准网络错误路径,
24
+ 业务层 except OSError / Exception 都能捕获——保持语义一致。
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import contextvars
29
+ import json
30
+ import os
31
+ import socket
32
+ import sys
33
+ import time
34
+ from typing import Optional
35
+
36
+
37
+ class OutboundRestrictedError(OSError):
38
+ """外网访问被 EdgeOne 平台拦截。
39
+
40
+ 继承 OSError:保持与 socket 层原生错误一致的异常语义,业务侧现有的
41
+ `except OSError` / `except ConnectionError` 都能自然接住。
42
+ """
43
+
44
+ def __init__(self, host: str, port: int, request_id: str = ""):
45
+ self.host = host
46
+ self.port = port
47
+ self.request_id = request_id
48
+ msg = "PagesLimit: egress quota may have been exceeded"
49
+ # OSError 的 errno 用 EACCES(13) 语义上「无权限访问」
50
+ super().__init__(13, msg)
51
+
52
+
53
+ # ---------- ContextVar:请求级 restricted 状态 ----------
54
+ # 存 dict 而非 bool,避免以后要塞 requestId / traceId 等再改签名。
55
+ _restricted_var: contextvars.ContextVar[Optional[dict]] = contextvars.ContextVar(
56
+ "_edgeone_outbound_restricted", default=None
57
+ )
58
+
59
+
60
+ def set_restricted(restricted: bool, request_id: str = "") -> contextvars.Token:
61
+ """在请求入口调用,返回 token 用于 finally 中 reset。"""
62
+ return _restricted_var.set({"restricted": bool(restricted), "requestId": request_id or ""})
63
+
64
+
65
+ def reset_restricted(token: contextvars.Token) -> None:
66
+ """在请求出口 finally 中调用。"""
67
+ try:
68
+ _restricted_var.reset(token)
69
+ except (LookupError, ValueError):
70
+ # token 已被 reset 或跨 context —— 忽略,避免影响主流程
71
+ pass
72
+
73
+
74
+ def _current() -> dict:
75
+ v = _restricted_var.get()
76
+ return v if isinstance(v, dict) else {"restricted": False, "requestId": ""}
77
+
78
+
79
+ # ---------- 白名单 ----------
80
+ _STATIC_SUFFIXES = (
81
+ ".edgeone.site",
82
+ ".tencentyun.com",
83
+ )
84
+ _STATIC_HOSTS = frozenset({
85
+ "localhost",
86
+ "ip6-localhost",
87
+ "ip6-loopback",
88
+ })
89
+
90
+
91
+ def _host_from_endpoint(v: str) -> str:
92
+ if not v:
93
+ return ""
94
+ s = str(v).strip()
95
+ if not s:
96
+ return ""
97
+ try:
98
+ if "://" in s:
99
+ from urllib.parse import urlparse
100
+ return urlparse(s).hostname or ""
101
+ return s.split("/", 1)[0].split(":", 1)[0]
102
+ except Exception:
103
+ return ""
104
+
105
+
106
+ def _build_dynamic_hosts() -> set[str]:
107
+ hosts: set[str] = set()
108
+ otlp = _host_from_endpoint(os.environ.get("EDGEONE_OTLP_ENDPOINT", ""))
109
+ if otlp:
110
+ hosts.add(otlp)
111
+ bypass = os.environ.get("EDGEONE_OUTBOUND_BYPASS_HOSTS", "")
112
+ if bypass:
113
+ for item in bypass.split(","):
114
+ h = item.strip()
115
+ if h:
116
+ hosts.add(h)
117
+ return hosts
118
+
119
+
120
+ _DYNAMIC_HOSTS = _build_dynamic_hosts()
121
+
122
+
123
+ def _is_loopback(host: str) -> bool:
124
+ if not host:
125
+ return False
126
+ if host in ("::1", "[::1]"):
127
+ return True
128
+ if host.startswith("127."):
129
+ return True
130
+ return False
131
+
132
+
133
+ def _is_whitelisted(host: str) -> bool:
134
+ if not host:
135
+ return True # host 缺失(Unix socket 等),交给上层
136
+ h = str(host).lower().strip("[]")
137
+ if h in _STATIC_HOSTS:
138
+ return True
139
+ if h in _DYNAMIC_HOSTS:
140
+ return True
141
+ for suffix in _STATIC_SUFFIXES:
142
+ if h.endswith(suffix):
143
+ return True
144
+ if _is_loopback(h):
145
+ return True
146
+ return False
147
+
148
+
149
+ # ---------- 灰度开关 ----------
150
+ def _is_disabled() -> bool:
151
+ v = os.environ.get("EDGEONE_OUTBOUND_HOOK_DISABLED", "").strip().lower()
152
+ return v in ("1", "true", "yes")
153
+
154
+
155
+ def _observe_only() -> bool:
156
+ return os.environ.get("EDGEONE_OUTBOUND_HOOK_MODE", "enforce").strip().lower() == "observe"
157
+
158
+
159
+ def _log_observe(host: str, port: int, request_id: str) -> None:
160
+ try:
161
+ payload = {
162
+ "type": "outbound_restricted_observe",
163
+ "kind": "socket",
164
+ "host": host,
165
+ "port": port,
166
+ "requestId": request_id,
167
+ "ts": int(time.time() * 1000),
168
+ }
169
+ sys.stderr.write(json.dumps(payload, ensure_ascii=False) + "\n")
170
+ sys.stderr.flush()
171
+ except Exception:
172
+ pass
173
+
174
+
175
+ # ---------- Hook 安装 ----------
176
+ _HOOKED = False
177
+
178
+
179
+ def install() -> None:
180
+ """安装 socket.create_connection hook;幂等。
181
+
182
+ 在模块 import 时调用一次;也可显式再调,重复调用无副作用。
183
+ """
184
+ global _HOOKED
185
+ if _HOOKED:
186
+ return
187
+ if _is_disabled():
188
+ _HOOKED = True
189
+ return
190
+
191
+ _orig_create_connection = socket.create_connection
192
+ _observe = _observe_only()
193
+
194
+ def _guarded_create_connection(address, *args, **kwargs):
195
+ # address 通常是 (host, port) 元组
196
+ host = ""
197
+ port = 0
198
+ try:
199
+ if isinstance(address, tuple) and len(address) >= 2:
200
+ host = str(address[0] or "")
201
+ port = int(address[1] or 0)
202
+ except (TypeError, ValueError):
203
+ pass
204
+
205
+ state = _current()
206
+ if state.get("restricted") and not _is_whitelisted(host):
207
+ if _observe:
208
+ _log_observe(host, port, state.get("requestId", ""))
209
+ else:
210
+ raise OutboundRestrictedError(host, port, state.get("requestId", ""))
211
+
212
+ return _orig_create_connection(address, *args, **kwargs)
213
+
214
+ socket.create_connection = _guarded_create_connection # type: ignore[assignment]
215
+
216
+ # ---- asyncio loop.create_connection hook ----
217
+ # asyncio 的 loop.create_connection 底层用 socket.socket()+sock.connect(),
218
+ # 不走 socket.create_connection,导致 async HTTP 客户端(aiohttp / httpx async)
219
+ # 全部漏拦。补 hook 覆盖 async 路径。
220
+ try:
221
+ import asyncio as _asyncio
222
+ _orig_loop_cc = _asyncio.base_events.BaseEventLoop.create_connection
223
+
224
+ async def _guarded_loop_cc(self, protocol_factory, host=None, port=None, *args, **kwargs):
225
+ h = str(host or "")
226
+ p = 0
227
+ try:
228
+ p = int(port) if port is not None else 0
229
+ except (TypeError, ValueError):
230
+ pass
231
+ state = _current()
232
+ if state.get("restricted") and not _is_whitelisted(h):
233
+ if _observe:
234
+ _log_observe(h, p, state.get("requestId", ""))
235
+ else:
236
+ raise OutboundRestrictedError(h, p, state.get("requestId", ""))
237
+ return await _orig_loop_cc(self, protocol_factory, host, port, *args, **kwargs)
238
+
239
+ _asyncio.base_events.BaseEventLoop.create_connection = _guarded_loop_cc
240
+ except Exception:
241
+ pass
242
+
243
+ # uvloop 兼容(sanic / uvicorn 默认用 uvloop)
244
+ try:
245
+ import uvloop as _uvloop
246
+ _orig_uvloop_cc = _uvloop.Loop.create_connection
247
+
248
+ async def _guarded_uvloop_cc(self, protocol_factory, host=None, port=None, *args, **kwargs):
249
+ h = str(host or "")
250
+ p = 0
251
+ try:
252
+ p = int(port) if port is not None else 0
253
+ except (TypeError, ValueError):
254
+ pass
255
+ state = _current()
256
+ if state.get("restricted") and not _is_whitelisted(h):
257
+ if _observe:
258
+ _log_observe(h, p, state.get("requestId", ""))
259
+ else:
260
+ raise OutboundRestrictedError(h, p, state.get("requestId", ""))
261
+ return await _orig_uvloop_cc(self, protocol_factory, host, port, *args, **kwargs)
262
+
263
+ _uvloop.Loop.create_connection = _guarded_uvloop_cc
264
+ except Exception:
265
+ pass
266
+
267
+ _HOOKED = True
268
+
269
+
270
+ # 模块被 import 的一刻就安装 hook,让「先 import 业务再启动」的场景也生效。
271
+ install()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "edgeone",
3
- "version": "1.6.48",
3
+ "version": "1.7.0",
4
4
  "description": "Command-line interface for TencentCloud Pages Functions",
5
5
  "bin": {
6
6
  "edgeone": "./edgeone-bin/edgeone.js"
@@ -32,6 +32,7 @@
32
32
  "scripts": {
33
33
  "clean": "rimraf ./edgeone-dist ./edgeone-bin ./libs-node-ai ./libs-kv-client",
34
34
  "bundle": "node -r esbuild-register ./scripts/bundle.ts",
35
+ "postbundle": "node ./scripts/check-bundle-test-data.js",
35
36
  "watch": "node -r esbuild-register ./scripts/bundle.ts watch",
36
37
  "build": "npm run clean && npm run build:pages-ai && npm run build:kv-client && npm run prepare:blob-wheel && npm run prepare:agent-toolkit-wheel && npm run bundle",
37
38
  "build:pages-ai": "node ./scripts/build-pages-ai.js",