fix: 按 Grok 评审修复 Repeater 录制代理地址、数字主机 SSRF、Cookie 合并等问题(Codex gpt-6.1-sol)(#42)

This commit is contained in:
RuoJi6 committed 2026-10-24 22:46:37 +08:00
1 parent 1847b8adb1
commit ddfdc36787
5 files changed
+180 -8

No files matched your search

+4 -5
View File
@@ -462,13 +462,12 @@ func (s *Server) httpProxyTransport(spec httpExec) *http.Transport {
proxyStr := strings.TrimSpace(spec.Proxy)
var caFile string
if spec.UseRecordingProxy {
// ProxyAddr is the local MITM address while capture is enabled, but
// returns the configured global proxy URL when capture is off. Keep the
// latter as a complete URL (including socks5:// and credentials) instead
// of prepending http:// to it.
// ProxyAddr is already a complete URL while capture is enabled, and
// returns the configured global proxy URL when capture is off. Keep both
// forms intact (including socks5:// and credentials).
if s.m.TrafficEnabled() {
if addr := s.m.ProxyAddr(); addr != "" {
proxyStr = "http://" + addr
proxyStr = addr
caFile = s.m.ProxyCACert()
}
} else if global := strings.TrimSpace(s.m.GlobalProxy()); global != "" {
+86
View File
@@ -12,6 +12,7 @@ import (
"net/http"
"net/url"
"os"
"strconv"
"strings"
"syscall"
"time"
@@ -272,12 +273,97 @@ func repeaterCheckURL(u *url.URL) error {
host = host[:zone]
}
ip := net.ParseIP(host)
if ip == nil && repeaterLooksNumericHost(host) {
var ok bool
ip, ok = repeaterParseLegacyIPv4(host)
if !ok {
return fmt.Errorf("拒绝无法解析的数字主机地址 %q", host)
}
}
if strings.EqualFold(host, "localhost") || (ip != nil && repeaterIsBlockedDialIP(ip)) {
return fmt.Errorf("拒绝访问本机/链路本地地址(如确需访问本机服务,设置 %s=1)", repeaterAllowLocalEnv)
}
return nil
}
// repeaterLooksNumericHost identifies the legacy numeric spellings accepted by
// common proxy/resolver implementations (decimal, octal, hexadecimal and
// dotted inet_aton forms). A numeric-looking value that fails to parse is
// rejected instead of being handed to a proxy for its own interpretation.
func repeaterLooksNumericHost(host string) bool {
if host == "" || host[0] < '0' || host[0] > '9' {
return false
}
for i := 0; i < len(host); i++ {
c := host[i]
switch {
case c == '.':
case c >= '0' && c <= '9':
case c >= 'a' && c <= 'f', c >= 'A' && c <= 'F':
case c == 'x' || c == 'X':
default:
return false
}
}
return true
}
// repeaterParseLegacyIPv4 follows inet_aton's 1-, 2-, 3- and 4-part IPv4
// notation. Parts with a leading zero are octal and parts with 0x are hex.
func repeaterParseLegacyIPv4(host string) (net.IP, bool) {
parts := strings.Split(host, ".")
if len(parts) < 1 || len(parts) > 4 {
return nil, false
}
values := make([]uint64, len(parts))
for i, part := range parts {
if part == "" {
return nil, false
}
base := 10
digits := part
if len(digits) > 2 && digits[0] == '0' && (digits[1] == 'x' || digits[1] == 'X') {
base, digits = 16, digits[2:]
} else if len(digits) > 1 && digits[0] == '0' {
base = 8
}
if digits == "" {
return nil, false
}
value, err := strconv.ParseUint(digits, base, 32)
if err != nil {
return nil, false
}
values[i] = value
}
var value uint64
switch len(values) {
case 1:
value = values[0]
case 2:
if values[0] > 0xff || values[1] > 0xffffff {
return nil, false
}
value = values[0]<<24 | values[1]
case 3:
if values[0] > 0xff || values[1] > 0xff || values[2] > 0xffff {
return nil, false
}
value = values[0]<<24 | values[1]<<16 | values[2]
case 4:
for _, part := range values {
if part > 0xff {
return nil, false
}
}
value = values[0]<<24 | values[1]<<16 | values[2]<<8 | values[3]
}
if value > 0xffffffff {
return nil, false
}
return net.IPv4(byte(value>>24), byte(value>>16), byte(value>>8), byte(value)), true
}
func repeaterIsBlockedDialIP(ip net.IP) bool {
if ip == nil {
return true
+62
View File
@@ -7,8 +7,11 @@ import (
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/Autumn-27/artex/traffic"
)
func repeaterTestSend(t *testing.T, s *Server, payload any) (int, repeaterSendResponse, string) {
@@ -72,6 +75,46 @@ func TestRepeaterBlockedIPs(t *testing.T) {
}
}
func TestRepeaterRejectsLegacyNumericHostsIncludingProxyPath(t *testing.T) {
t.Setenv(repeaterAllowLocalEnv, "")
for _, raw := range []string{
"http://2130706433/", // decimal 127.0.0.1
"http://0177.0.0.1/", // octal 127.0.0.1
"http://127.1/", // two-part inet_aton form
"http://0x7f000001/", // hexadecimal 127.0.0.1
"http://9999999999/", // numeric-looking but invalid
} {
u, err := url.Parse(raw)
if err != nil {
t.Fatal(err)
}
if err := repeaterCheckURL(u); err == nil {
t.Errorf("repeaterCheckURL(%q) allowed a legacy numeric host", raw)
}
}
// The check must run before a configured proxy gets a chance to interpret
// the legacy spelling and connect to loopback remotely.
proxy := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
t.Error("proxy received a blocked numeric target")
}))
defer proxy.Close()
s := &Server{m: &Manager{globalProxy: proxy.URL}}
code, _, body := repeaterTestSend(t, s, map[string]any{"url": "http://2130706433/"})
if code != http.StatusBadRequest || !strings.Contains(body, "拒绝") {
t.Fatalf("proxied legacy host status=%d body=%s", code, body)
}
}
func TestRepeaterBlockSensitiveDial(t *testing.T) {
t.Setenv(repeaterAllowLocalEnv, "")
for _, address := range []string{"127.0.0.1:80", "169.254.169.254:80"} {
if err := repeaterBlockSensitiveDial("tcp", address, nil); err == nil {
t.Errorf("repeaterBlockSensitiveDial(%q) allowed blocked address", address)
}
}
}
func TestRepeaterRoundTripHeadersAndBody(t *testing.T) {
t.Setenv(repeaterAllowLocalEnv, "1")
var got http.Request
@@ -183,4 +226,23 @@ func TestRepeaterSocks5TransportConstruction(t *testing.T) {
if err != nil || proxyURL == nil || proxyURL.Scheme != "socks5" {
t.Fatalf("global proxy URL = %#v, err=%v", proxyURL, err)
}
// Capture mode supplies a complete HTTP URL from Traffic.ProxyAddr. The
// helper must preserve that scheme and host rather than prefixing http:// a
// second time.
captured, err := traffic.Open(t.TempDir(), "127.0.0.1:18788")
if err != nil {
t.Fatalf("traffic.Open: %v", err)
}
defer captured.Close()
s.m.traffic = captured
s.m.trafficOn = true
tr = s.httpProxyTransport(httpExec{UseRecordingProxy: true})
if tr == nil || tr.Proxy == nil {
t.Fatal("recording proxy was not configured")
}
proxyURL, err = tr.Proxy(httptest.NewRequest(http.MethodGet, "https://target.example/", nil))
if err != nil || proxyURL == nil || proxyURL.Scheme != "http" || proxyURL.Host != "127.0.0.1:18788" {
t.Fatalf("recording proxy URL = %#v, err=%v", proxyURL, err)
}
}
+10 -3
View File
@@ -45,9 +45,15 @@ export function parseHeadersText(text: string): Record<string, string> {
const name = line.slice(0, separator).trim();
const value = line.slice(separator + 1).trim();
if (!name) continue;
// The API accepts one value per name. Combining duplicates preserves the
// common comma-separated-header semantics for this MVP.
result[name] = result[name] ? `${result[name]}, ${value}` : value;
// The API accepts one value per name. Cookies use semicolon separators;
// other duplicate headers preserve the common comma-separated semantics.
const existingName = Object.keys(result).find((item) => item.toLowerCase() === name.toLowerCase());
if (!existingName) {
result[name] = value;
} else {
const separator = existingName.toLowerCase() === "cookie" ? "; " : ", ";
result[existingName] = `${result[existingName]}${separator}${value}`;
}
}
return result;
}
@@ -224,6 +230,7 @@ export function FindingRepeaterDialog({
<button
key={entry.id}
type="button"
disabled={busy}
className="block w-full rounded-md px-2 py-1.5 text-left hover:bg-muted"
onClick={() => {
setMethod(entry.method);
+18
View File
@@ -1012,6 +1012,24 @@ export async function mockHandle<T>(method: string, rawPath: string, body?: Body
function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Record<string, unknown>): unknown {
const task = q.get("task") ?? undefined;
// The demo client still expects the complete repeater response shape. No
// network request is made in mock mode, but returning the shape keeps the
// dialog's status/body counters safe for every method.
if (path === "/repeater/send" && m === "POST") {
const responseBody = "(演示模式)未发送真实请求。";
return {
status: 200,
status_text: "200 OK",
proto: "HTTP/1.1",
headers: { "Content-Type": ["text/plain; charset=utf-8"] },
body: responseBody,
body_truncated: false,
body_bytes: new TextEncoder().encode(responseBody).length,
elapsed_ms: 0,
url: String(b.url ?? ""),
};
}
if (path === "/chat/mentions" && m === "GET") {
const kind = q.get("kind") ?? "";
const query = (q.get("q") ?? "").trim().toLowerCase();