修复聊天状态同步与验证码验证链路
This commit is contained in:
1 parent
3fdace9492
commit
55904cc409
38 files changed
+884
-139
No files matched your search
@@ -9,6 +9,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -48,6 +49,10 @@ func chromiumLaunchArgs() []string {
|
||||
if captchaIgnoreCertificateErrors() {
|
||||
args = append(args, "--ignore-certificate-errors")
|
||||
}
|
||||
// proxy 是通过受限解析验证后的验证码浏览器代理,仅在部署显式配置时覆盖 Chromium 的系统代理选择。
|
||||
if proxy := captchaBrowserProxy(); proxy != "" {
|
||||
args = append(args, "--proxy-server="+proxy)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
@@ -63,6 +68,28 @@ func captchaIgnoreCertificateErrors() bool {
|
||||
return err == nil && parsed
|
||||
}
|
||||
|
||||
// captchaBrowserProxy 返回仅供 token CAPTCHA Chromium 使用的显式代理地址;默认保留系统代理,非法、带凭证或带查询的值一律忽略,避免把敏感代理信息写入启动参数或日志。
|
||||
func captchaBrowserProxy() string {
|
||||
// value 是环境变量中的代理地址,空值表示让 Chromium 沿用操作系统的正常网络配置。
|
||||
value := strings.TrimSpace(os.Getenv("CAPTCHA_BROWSER_PROXY"))
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
// parsed、parseErr 是受限代理地址的结构化解析结果;仅接受 Chromium 支持的无凭证 HTTP(S)/SOCKS 代理。
|
||||
parsed, parseErr := url.Parse(value)
|
||||
if parseErr != nil || parsed.Host == "" || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
return ""
|
||||
}
|
||||
// scheme 是统一小写后的代理协议,限制集合避免把任意 Chromium flag 拼入 Args。
|
||||
scheme := strings.ToLower(parsed.Scheme)
|
||||
switch scheme {
|
||||
case "http", "https", "socks4", "socks5":
|
||||
return value
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// chromiumExecutablePath 负责chromiumExecutable路径相关处理。
|
||||
func chromiumExecutablePath() *string {
|
||||
if // path 保存路径,供当前处理流程使用
|
||||
|
||||
@@ -129,6 +129,48 @@ func TestCaptchaIgnoreCertificateErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCaptchaBrowserProxy 验证验证码浏览器只接受无凭证的受限代理地址,并在配置为空或非法时保留系统代理行为。
|
||||
func TestCaptchaBrowserProxy(t *testing.T) {
|
||||
// testCases 是输入环境值与预期解析结果,覆盖默认、支持协议及敏感/危险输入。
|
||||
testCases := []struct {
|
||||
// name 是失败时定位具体输入的用例名。
|
||||
name string
|
||||
// value 是待解析的 CAPTCHA 浏览器代理配置。
|
||||
value string
|
||||
// want 是允许传给 Chromium 的预期代理地址,空串代表不追加覆盖参数。
|
||||
want string
|
||||
}{
|
||||
{name: "empty", value: "", want: ""},
|
||||
{name: "http", value: " http://127.0.0.1:1082 ", want: "http://127.0.0.1:1082"},
|
||||
{name: "socks5", value: "socks5://127.0.0.1:1080", want: "socks5://127.0.0.1:1080"},
|
||||
{name: "credentials", value: "http://user:[email protected]:1082", want: ""},
|
||||
{name: "query", value: "http://127.0.0.1:1082?secret=value", want: ""},
|
||||
{name: "unsupported", value: "file:///tmp/proxy", want: ""},
|
||||
}
|
||||
// testCase 是当前要通过独立环境变量验证的代理配置用例。
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
t.Setenv("CAPTCHA_BROWSER_PROXY", testCase.value)
|
||||
// got 是解析后允许写入 Chromium 参数的代理地址。
|
||||
got := captchaBrowserProxy()
|
||||
if got != testCase.want {
|
||||
t.Fatalf("captchaBrowserProxy()=%q, want %q", got, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
t.Setenv("CAPTCHA_BROWSER_PROXY", "http://127.0.0.1:1082")
|
||||
// proxyArgs 是显式代理启用时主 Chromium 引擎的启动参数集合。
|
||||
proxyArgs := strings.Join(chromiumLaunchArgs(), " ")
|
||||
if !strings.Contains(proxyArgs, "--proxy-server=http://127.0.0.1:1082") {
|
||||
t.Fatalf("主引擎未写入显式代理参数: %s", proxyArgs)
|
||||
}
|
||||
// fallbackArgs 是备用直接 CDP 引擎的独立参数集合,必须使用相同代理而不是回退到 Fake-IP 直连。
|
||||
fallbackArgs := strings.Join(fallbackChromiumArgs("/tmp/profile", true), " ")
|
||||
if !strings.Contains(fallbackArgs, "--proxy-server=http://127.0.0.1:1082") {
|
||||
t.Fatalf("备用引擎未写入显式代理参数: %s", fallbackArgs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker 验证规范化不伪造 Chromium 的版本或平台身份。
|
||||
func TestNormalizeBrowserFingerprintRemovesOnlyHeadlessMarker(t *testing.T) {
|
||||
// fingerprint 是含无头标记的实测身份经过规范化后的结果,用于断言只移除产品标记。
|
||||
|
||||
+216
-74
@@ -30,12 +30,19 @@ var sliderSuccessSelectors = []string{
|
||||
const (
|
||||
sliderSuccessCheckAttempts = 4
|
||||
sliderSuccessCheckInterval = 400 * time.Millisecond
|
||||
// sliderContinuousEventMaxInterval 是主引擎按住期间相邻微移动事件的最大间隔,保证提速后仍呈连续轨迹。
|
||||
sliderContinuousEventMaxInterval = 15 * time.Millisecond
|
||||
// sliderMovementMinDuration、sliderMovementMaxDuration 是主引擎按下到释放的目标墙钟范围,较上一版提速一倍。
|
||||
sliderMovementMinDuration = 550 * time.Millisecond
|
||||
sliderMovementMaxDuration = 1050 * time.Millisecond
|
||||
)
|
||||
|
||||
// trajectoryPoint 轨迹中的单个采样点。
|
||||
type trajectoryPoint struct {
|
||||
x float64
|
||||
y float64
|
||||
// x、y 是相对滑块中心的曲线锚点偏移;x 保持单调前进并在末点落到受控超调终点。
|
||||
x float64
|
||||
y float64
|
||||
// delay 是该锚点对应的相对时长权重;连续微移动会按该权重分配时间,不能形成锚点后的静止停顿。
|
||||
delay time.Duration
|
||||
}
|
||||
|
||||
@@ -56,58 +63,155 @@ type sliderResetResult struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// generateTrajectory mirrors the reference Playwright engine's short
|
||||
// acceleration/constant/deceleration trajectory. Each point is a high-level
|
||||
// browser protocol call, so generating dozens of points makes the drag unlike
|
||||
// the reference implementation even when the wall-clock duration is similar.
|
||||
func generateTrajectory(distance float64) []trajectoryPoint {
|
||||
requestedSteps := 5 + rng.Intn(2)
|
||||
totalDuration := randomFloat(0.010, 0.020)
|
||||
avgDelay := totalDuration / float64(requestedSteps)
|
||||
|
||||
accelRatio := 0.35 + randomFloat(-0.05, 0.05)
|
||||
decelRatio := 0.30 + randomFloat(-0.05, 0.05)
|
||||
// generateTrajectory 根据 distance 和 verticalSpan 生成标准 NC 的单调三阶段曲线锚点。
|
||||
// distance 是按钮可用移动距离;verticalSpan 是 Y 轴峰峰值,锚点之间由连续微移动连接,末点会受控超出可用距离。
|
||||
func generateTrajectory(distance, verticalSpan float64) []trajectoryPoint {
|
||||
// requestedSteps 是本次高层鼠标移动采样数,范围避免固定轨迹特征,同时保持在 Chromium CDP 的低开销区间。
|
||||
requestedSteps := 8 + rng.Intn(5)
|
||||
// averageDelay 是各采样点的基础等待秒数;实际总时长由 simulateSlide 的墙钟预算补偿。
|
||||
averageDelay := randomFloat(0.045, 0.085)
|
||||
// accelRatio、decelRatio 分别限定加速和减速阶段所占轨迹比例,余量构成中速前进阶段。
|
||||
accelRatio := randomFloat(0.26, 0.34)
|
||||
decelRatio := randomFloat(0.24, 0.32)
|
||||
// accelSteps、decelSteps、constantSteps 是三段分别包含的采样点数,至少各保留两个点以避免变成直线移动。
|
||||
accelSteps := max(2, int(math.Round(float64(requestedSteps)*accelRatio)))
|
||||
decelSteps := max(2, int(math.Round(float64(requestedSteps)*decelRatio)))
|
||||
constantSteps := max(2, requestedSteps-accelSteps-decelSteps)
|
||||
|
||||
accelDistance := distance * randomFloat(0.25, 0.35)
|
||||
constantDistance := distance * randomFloat(0.50, 0.60)
|
||||
decelDistance := distance - accelDistance - constantDistance
|
||||
pts := make([]trajectoryPoint, 0, accelSteps+constantSteps+decelSteps)
|
||||
// overshoot 是鼠标终点超出可用滑轨的像素量;页面控件自身会在轨道边界钳位,因此不会被拖出滑轨。
|
||||
overshoot := randomFloat(4, 20)
|
||||
// targetDistance 是鼠标实际行进的水平目标,包含受控超调;三段距离相加后在末点落到该目标。
|
||||
targetDistance := distance + overshoot
|
||||
// accelDistance、constantDistance、decelDistance 是三段覆盖的水平距离;三者相加始终等于带超调的鼠标目标距离。
|
||||
accelDistance := targetDistance * randomFloat(0.24, 0.34)
|
||||
constantDistance := targetDistance * randomFloat(0.46, 0.56)
|
||||
decelDistance := targetDistance - accelDistance - constantDistance
|
||||
// points 保存按加速、中速、减速依次生成的高层鼠标坐标。
|
||||
points := make([]trajectoryPoint, 0, accelSteps+constantSteps+decelSteps)
|
||||
|
||||
for i := 1; i <= accelSteps; i++ {
|
||||
progress := float64(i) / float64(accelSteps)
|
||||
pts = append(pts, trajectoryPoint{
|
||||
// step 表示当前加速段采样点序号。
|
||||
for step := 1; step <= accelSteps; step++ {
|
||||
// progress 是当前采样点在加速段中的归一化进度。
|
||||
progress := float64(step) / float64(accelSteps)
|
||||
points = append(points, trajectoryPoint{
|
||||
x: accelDistance * progress * progress,
|
||||
y: randomFloat(-1, 1),
|
||||
delay: secondsDuration(avgDelay * randomFloat(1, 1.3)),
|
||||
delay: secondsDuration(averageDelay * randomFloat(0.70, 1.20)),
|
||||
})
|
||||
}
|
||||
for i := 1; i <= constantSteps; i++ {
|
||||
progress := float64(i) / float64(constantSteps)
|
||||
delay := avgDelay * randomFloat(0.85, 1.15)
|
||||
if randomFloat(0, 1) < 0.03 {
|
||||
delay *= randomFloat(1.1, 1.3)
|
||||
}
|
||||
pts = append(pts, trajectoryPoint{
|
||||
// step 表示当前中速段采样点序号。
|
||||
for step := 1; step <= constantSteps; step++ {
|
||||
// progress 是当前采样点在中速段中的归一化进度。
|
||||
progress := float64(step) / float64(constantSteps)
|
||||
// delay 是中速段本点后的基础等待,刻意保留差异而非固定间隔。
|
||||
delay := averageDelay * randomFloat(0.65, 1.25)
|
||||
points = append(points, trajectoryPoint{
|
||||
x: accelDistance + constantDistance*progress,
|
||||
y: randomFloat(-1, 1) * 0.6,
|
||||
delay: secondsDuration(delay),
|
||||
})
|
||||
}
|
||||
for i := 1; i <= decelSteps; i++ {
|
||||
progress := float64(i) / float64(decelSteps)
|
||||
pts = append(pts, trajectoryPoint{
|
||||
// step 表示当前减速段采样点序号。
|
||||
for step := 1; step <= decelSteps; step++ {
|
||||
// progress 是当前采样点在减速段中的归一化进度。
|
||||
progress := float64(step) / float64(decelSteps)
|
||||
points = append(points, trajectoryPoint{
|
||||
x: accelDistance + constantDistance + decelDistance*(1-math.Pow(1-progress, 2)),
|
||||
y: randomFloat(-1, 1) * 0.4,
|
||||
delay: secondsDuration(avgDelay * randomFloat(1.1, 1.5)),
|
||||
delay: secondsDuration(averageDelay * randomFloat(0.90, 1.55)),
|
||||
})
|
||||
}
|
||||
if len(pts) > 0 {
|
||||
pts[len(pts)-1].x = distance
|
||||
applyContinuousVerticalDrift(points, verticalSpan)
|
||||
if len(points) > 0 {
|
||||
points[len(points)-1].x = targetDistance
|
||||
}
|
||||
return pts
|
||||
return points
|
||||
}
|
||||
|
||||
// expandContinuousTrajectory 把稀疏曲线锚点展开为连续事件流,避免鼠标在每个锚点后肉眼可见地停住。
|
||||
// points 是调用方生成的有序锚点;target 是按下到释放的目标总时长;返回点中的 delay 不超过连续事件允许的最大间隔。
|
||||
func expandContinuousTrajectory(points []trajectoryPoint, target time.Duration) []trajectoryPoint {
|
||||
// totalWeight 汇总各锚点的相对时长权重,以便保持加速、中速、减速三段的时间比例。
|
||||
var totalWeight time.Duration
|
||||
for _, point := range points {
|
||||
totalWeight += point.delay
|
||||
}
|
||||
if len(points) == 0 || target <= 0 || totalWeight <= 0 {
|
||||
return nil
|
||||
}
|
||||
// expanded 保存连接每一对锚点后的连续微移动事件。
|
||||
expanded := make([]trajectoryPoint, 0, len(points)*8)
|
||||
// previous 是本段的起点;首次从按钮中心开始,后续从前一个锚点继续。
|
||||
previous := trajectoryPoint{}
|
||||
for _, point := range points {
|
||||
// segmentDuration 是本段在总拖动窗口中所占时长,按生成轨迹的非均匀权重分配。
|
||||
segmentDuration := time.Duration(int64(target) * int64(point.delay) / int64(totalWeight))
|
||||
if segmentDuration <= 0 {
|
||||
segmentDuration = time.Nanosecond
|
||||
}
|
||||
// eventCount 是本段需要发出的微移动数量,预留节奏变化空间且至少两个事件以避免跨锚点跳跃。
|
||||
eventCount := max(2, int(math.Ceil(float64(segmentDuration)/float64(sliderContinuousEventMaxInterval)*1.34)))
|
||||
// rhythmPhase、rhythmRate 为本段节奏曲线的随机相位和周期,产生平滑的快慢变化而不是逐点抖动。
|
||||
rhythmPhase := randomFloat(0, 2*math.Pi)
|
||||
rhythmRate := randomFloat(0.8, 1.6)
|
||||
// eventWeights 保存每个微移动的相对时长,归一化后总和仍等于本段预算。
|
||||
eventWeights := make([]float64, eventCount)
|
||||
var weightTotal float64
|
||||
for eventIndex := range eventWeights {
|
||||
// progress 是本段节奏曲线的归一化位置;较低权重代表更快移动,较高权重代表更慢移动。
|
||||
progress := float64(eventIndex) / float64(max(1, eventCount-1))
|
||||
weight := 1 + 0.22*math.Sin(2*math.Pi*rhythmRate*progress+rhythmPhase)
|
||||
eventWeights[eventIndex] = weight
|
||||
weightTotal += weight
|
||||
}
|
||||
for eventIndex := 1; eventIndex <= eventCount; eventIndex++ {
|
||||
// progress 是当前微移动在本段中的线性进度,使拖动一直前进而不在锚点处驻留。
|
||||
progress := float64(eventIndex) / float64(eventCount)
|
||||
// eventDelay 是归一化后的本次微移动间隔,确保节奏变化不突破连续事件上限。
|
||||
eventDelay := time.Duration(float64(segmentDuration) * eventWeights[eventIndex-1] / weightTotal)
|
||||
if eventDelay <= 0 {
|
||||
eventDelay = time.Nanosecond
|
||||
}
|
||||
expanded = append(expanded, trajectoryPoint{
|
||||
x: previous.x + (point.x-previous.x)*progress,
|
||||
y: previous.y + (point.y-previous.y)*progress,
|
||||
delay: eventDelay,
|
||||
})
|
||||
}
|
||||
previous = point
|
||||
}
|
||||
return expanded
|
||||
}
|
||||
|
||||
// applyContinuousVerticalDrift 把 Y 坐标改为连续的正弦形曲线。
|
||||
// points 由调用方拥有;verticalSpan 是轨迹实际达到的 Y 轴峰峰值,非正值或不足三个点时保留水平路径作为降级行为。
|
||||
func applyContinuousVerticalDrift(points []trajectoryPoint, verticalSpan float64) {
|
||||
if len(points) < 3 || verticalSpan <= 0 {
|
||||
return
|
||||
}
|
||||
// direction 决定本次先向上还是先向下偏移,避免每次都从相同方向开始。
|
||||
direction := 1.0
|
||||
if rng.Intn(2) == 0 {
|
||||
direction = -1
|
||||
}
|
||||
// rawY 保存未缩放的完整正弦周期;minY、maxY 用于把离散采样后的实际峰峰值精确映射到滑轨高度的一半。
|
||||
rawY := make([]float64, len(points))
|
||||
minY, maxY := math.Inf(1), math.Inf(-1)
|
||||
// pointIndex 是当前轨迹点下标;pointCount 是轨迹总点数减一,用于得到闭区间的归一化进度。
|
||||
pointCount := len(points) - 1
|
||||
for pointIndex := range points {
|
||||
// progress 是从按下到释放的归一化进度,正弦曲线让纵向移动连续且不呈线性变化。
|
||||
progress := float64(pointIndex) / float64(pointCount)
|
||||
rawY[pointIndex] = math.Sin(2 * math.Pi * progress)
|
||||
minY = min(minY, rawY[pointIndex])
|
||||
maxY = max(maxY, rawY[pointIndex])
|
||||
}
|
||||
// scale 把当前离散采样的最大纵向范围精确缩放到请求的峰峰值。
|
||||
scale := verticalSpan / (maxY - minY)
|
||||
// centre 让曲线围绕滑块中心上下摆动,而不是单向贴近轨道边缘。
|
||||
centre := (minY + maxY) / 2
|
||||
for pointIndex := range points {
|
||||
points[pointIndex].y = direction * (rawY[pointIndex] - centre) * scale
|
||||
}
|
||||
points[0].y = 0
|
||||
points[len(points)-1].y = 0
|
||||
}
|
||||
|
||||
func randomFloat(minValue, maxValue float64) float64 {
|
||||
@@ -171,7 +275,7 @@ func solveSliderStrict(page playwright.Page, scratch bool, logger sliderLogger,
|
||||
}
|
||||
logSliderAttemptStart(logger, page, frame, btn, track, attempt+1, dist)
|
||||
|
||||
motion, err := simulateSlide(page, btn, dist)
|
||||
motion, err := simulateSlide(page, btn, track, dist)
|
||||
if err != nil {
|
||||
logger.Warn("模拟滑动失败", "err", err)
|
||||
if attempt < 2 {
|
||||
@@ -214,7 +318,8 @@ func solveSliderStrict(page playwright.Page, scratch bool, logger sliderLogger,
|
||||
}
|
||||
logSliderFailureState(logger, page, attempt+1)
|
||||
if attempt < 2 {
|
||||
reset := resetSliderForRetry(context.Background(), page, deadline)
|
||||
// reset 是已完成拖动后点击页面失败按钮得到的恢复结果;该路径禁止 reload,避免丢失平台重新生成的滑块状态。
|
||||
reset := retrySliderAfterFailedDrag(context.Background(), page, deadline)
|
||||
logSliderReset(logger, attempt+1, reset)
|
||||
if reset.err != nil {
|
||||
return fmt.Errorf("滑块第 %d 次失败后无法恢复: %w", attempt+1, reset.err)
|
||||
@@ -347,7 +452,8 @@ func calculateSlideDistance(btn, track playwright.ElementHandle, scratch bool) (
|
||||
}
|
||||
|
||||
// simulateSlide 模拟人类滑动,并返回协议调用后的真实墙钟耗时。
|
||||
func simulateSlide(page playwright.Page, btn playwright.ElementHandle, distance float64) (slideMotionMetrics, error) {
|
||||
// btn 和 track 必须来自同一 frame;distance 是精确水平距离,纵向范围优先使用 track 的实际高度。
|
||||
func simulateSlide(page playwright.Page, btn, track playwright.ElementHandle, distance float64) (slideMotionMetrics, error) {
|
||||
metrics := slideMotionMetrics{}
|
||||
totalStarted := time.Now()
|
||||
time.Sleep(secondsDuration(randomFloat(0.1, 0.3)))
|
||||
@@ -357,6 +463,13 @@ func simulateSlide(page playwright.Page, btn playwright.ElementHandle, distance
|
||||
}
|
||||
startX := bb.X + bb.Width/2
|
||||
startY := bb.Y + bb.Height/2
|
||||
// verticalSpan 是拖动 Y 坐标的峰峰值,默认使用按钮高度的一半;track 可测量时改用实际滑轨高度的一半。
|
||||
verticalSpan := bb.Height / 2
|
||||
// trackBox、trackErr 保存同一滑轨的几何信息及其读取错误;读取失败时保持按钮高度的安全降级值。
|
||||
trackBox, trackErr := track.BoundingBox()
|
||||
if trackErr == nil && trackBox != nil && trackBox.Height > 0 {
|
||||
verticalSpan = trackBox.Height / 2
|
||||
}
|
||||
mouse := page.Mouse()
|
||||
|
||||
// 第一阶段:从左侧附近自然接近滑块。
|
||||
@@ -377,28 +490,36 @@ func simulateSlide(page playwright.Page, btn playwright.ElementHandle, distance
|
||||
}
|
||||
time.Sleep(secondsDuration(randomFloat(0.05, 0.15)))
|
||||
|
||||
pts := generateTrajectory(distance)
|
||||
pts := generateTrajectory(distance, verticalSpan)
|
||||
metrics.points = len(pts)
|
||||
for _, pt := range pts {
|
||||
metrics.plannedDelay += pt.delay
|
||||
// point 是当前曲线锚点;plannedDelay 汇总锚点相对时长权重,便于诊断曲线规划。
|
||||
for _, point := range pts {
|
||||
metrics.plannedDelay += point.delay
|
||||
}
|
||||
// The reference implementation gets roughly 80-150ms of CDP round-trip
|
||||
// latency per high-level point. The Go driver is often much faster, so keep
|
||||
// the same six-point shape while compensating to the observed 480-900ms
|
||||
// movement window using wall-clock time.
|
||||
metrics.targetMovement = secondsDuration(randomFloat(0.48, 0.90))
|
||||
// targetMovement 是拖动阶段的目标墙钟时长,保持连续且非匀速的前提下按用户要求提速一倍。
|
||||
metrics.targetMovement = secondsDuration(randomFloat(
|
||||
float64(sliderMovementMinDuration)/float64(time.Second),
|
||||
float64(sliderMovementMaxDuration)/float64(time.Second),
|
||||
))
|
||||
// continuousPoints 是在相邻曲线锚点间持续分发的微移动事件;按下后至释放前不允许插入独立的静止停顿。
|
||||
continuousPoints := expandContinuousTrajectory(pts, metrics.targetMovement)
|
||||
movementStarted := time.Now()
|
||||
currentX, currentY := startX, startY
|
||||
for index, pt := range pts {
|
||||
// scheduledElapsed 是当前微移动完成后的目标累计时间;浏览器调用本身消耗的时间会从后续等待中扣除。
|
||||
var scheduledElapsed time.Duration
|
||||
for _, pt := range continuousPoints {
|
||||
currentX, currentY = startX+pt.x, startY+pt.y
|
||||
if err := mouse.Move(currentX, currentY, playwright.MouseMoveOptions{Steps: playwright.Int(1 + rng.Intn(3))}); err != nil {
|
||||
if err := mouse.Move(currentX, currentY, playwright.MouseMoveOptions{Steps: playwright.Int(1)}); err != nil {
|
||||
_ = mouse.Up()
|
||||
return metrics, err
|
||||
}
|
||||
planned := time.Duration(float64(pt.delay) * randomFloat(0.9, 1.1))
|
||||
remainingPoints := len(pts) - index
|
||||
delay := compensatedTrajectoryDelay(planned, metrics.targetMovement, time.Since(movementStarted), remainingPoints)
|
||||
time.Sleep(delay)
|
||||
// scheduledElapsed 按平滑节奏曲线推进,保证整段的快慢变化不会被浏览器调用开销累积拉长。
|
||||
scheduledElapsed += pt.delay
|
||||
// delay 是到下一计划时间点的剩余等待;非正值表示浏览器调用已耗尽本次等待预算,应立即继续移动。
|
||||
delay := scheduledElapsed - time.Since(movementStarted)
|
||||
if delay > 0 {
|
||||
time.Sleep(delay)
|
||||
}
|
||||
}
|
||||
metrics.movementElapsed = time.Since(movementStarted)
|
||||
if isScratchCaptchaFromPage(page) {
|
||||
@@ -549,12 +670,21 @@ func sliderRetryText(text string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func resetSliderForRetry(ctx context.Context, page playwright.Page, deadline time.Time) sliderResetResult {
|
||||
// retrySliderAfterFailedDrag 在一次拖动已经完成且页面明确失败后,点击平台提供的失败按钮重新生成滑块。
|
||||
// ctx 控制等待;page 是当前验证页;deadline 是浏览器总期限;该函数绝不 reload 页面,调用方应保留本次失败现场。
|
||||
func retrySliderAfterFailedDrag(ctx context.Context, page playwright.Page, deadline time.Time) sliderResetResult {
|
||||
return clickSliderRetry(ctx, page, deadline)
|
||||
}
|
||||
|
||||
// clickSliderRetry 等待并点击可见的失败重试控件,然后确认新滑块已回到轨道起点。
|
||||
// ctx 控制轮询;page 是当前验证页;deadline 限制等待;返回结果只描述点击恢复,绝不包含页面刷新。
|
||||
func clickSliderRetry(ctx context.Context, page playwright.Page, deadline time.Time) sliderResetResult {
|
||||
// result 保存重试按钮点击与新滑块归位的观察结果,供调用方决定是否允许后续刷新恢复。
|
||||
result := sliderResetResult{}
|
||||
// selector、clickErr 分别保存命中的失败按钮选择器和首次点击结果。
|
||||
selector, clickErr := clickRetry(page)
|
||||
if clickErr != nil {
|
||||
// AWSC can publish the failure control shortly after its verification
|
||||
// request completes. Give it a brief chance before reloading the page.
|
||||
// waitDeadline 给平台渲染失败按钮一个短暂窗口;轮询期间不刷新当前验证页。
|
||||
waitDeadline := boundedDeadline(deadline, 800*time.Millisecond)
|
||||
for time.Now().Before(waitDeadline) {
|
||||
if err := sleepUntil(ctx, waitDeadline, 100*time.Millisecond); err != nil {
|
||||
@@ -566,34 +696,46 @@ func resetSliderForRetry(ctx context.Context, page playwright.Page, deadline tim
|
||||
}
|
||||
}
|
||||
}
|
||||
if clickErr == nil {
|
||||
result.method = "click"
|
||||
result.selector = selector
|
||||
result.ready = waitForSliderReady(ctx, page, boundedDeadline(deadline, 4*time.Second))
|
||||
if result.ready {
|
||||
return result
|
||||
}
|
||||
if clickErr != nil {
|
||||
result.err = fmt.Errorf("未找到可点击的滑块失败重试控件: %w", clickErr)
|
||||
return result
|
||||
}
|
||||
result.method = "click"
|
||||
result.selector = selector
|
||||
result.ready = waitForSliderReady(ctx, page, boundedDeadline(deadline, 4*time.Second))
|
||||
if !result.ready {
|
||||
result.err = fmt.Errorf("点击滑块失败重试控件后未重新归位")
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func resetSliderForRetry(ctx context.Context, page playwright.Page, deadline time.Time) sliderResetResult {
|
||||
// result 保存先尝试点击恢复后的结果;只有非拖动失败的调用方才允许在其失败时回退到 reload。
|
||||
result := clickSliderRetry(ctx, page, deadline)
|
||||
if result.err == nil {
|
||||
return result
|
||||
}
|
||||
|
||||
result.method = "reload"
|
||||
// reloadResult 清除点击失败的细节,记录初始页面恢复场景允许使用的页面重载结果。
|
||||
reloadResult := sliderResetResult{method: "reload"}
|
||||
reloadTimeout := boundedDuration(deadline, 8*time.Second)
|
||||
if reloadTimeout <= 0 {
|
||||
result.err = fmt.Errorf("滑块恢复前已超过总超时")
|
||||
return result
|
||||
reloadResult.err = fmt.Errorf("滑块恢复前已超过总超时")
|
||||
return reloadResult
|
||||
}
|
||||
_, reloadErr := page.Reload(playwright.PageReloadOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(float64(reloadTimeout.Milliseconds())),
|
||||
})
|
||||
if reloadErr != nil {
|
||||
result.err = fmt.Errorf("重载滑块验证页: %w", reloadErr)
|
||||
return result
|
||||
reloadResult.err = fmt.Errorf("重载滑块验证页: %w", reloadErr)
|
||||
return reloadResult
|
||||
}
|
||||
result.ready = waitForSliderReady(ctx, page, boundedDeadline(deadline, 5*time.Second))
|
||||
if !result.ready {
|
||||
result.err = fmt.Errorf("重载后滑块未重新出现")
|
||||
reloadResult.ready = waitForSliderReady(ctx, page, boundedDeadline(deadline, 5*time.Second))
|
||||
if !reloadResult.ready {
|
||||
reloadResult.err = fmt.Errorf("重载后滑块未重新出现")
|
||||
}
|
||||
return result
|
||||
return reloadResult
|
||||
}
|
||||
|
||||
func waitForSliderReady(ctx context.Context, page playwright.Page, deadline time.Time) bool {
|
||||
|
||||
@@ -6,41 +6,124 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestGenerateTrajectoryShape 验证标准 NC 轨迹保持单调前进,并在末端使用受控鼠标超调。
|
||||
func TestGenerateTrajectoryShape(t *testing.T) {
|
||||
pts := generateTrajectory(200)
|
||||
if len(pts) != 6 {
|
||||
t.Fatalf("参考三阶段轨迹应生成 6 个高层点,got %d", len(pts))
|
||||
// pts 是本次生成的轨迹采样点,用于核验水平移动的边界与顺序。
|
||||
pts := generateTrajectory(200, 34)
|
||||
if len(pts) < 8 || len(pts) > 12 {
|
||||
t.Fatalf("主引擎应生成 8 至 12 个高层点,got %d", len(pts))
|
||||
}
|
||||
// 参考实现明确禁止超调,最后一点必须精确落在目标位置。
|
||||
// last 是最后一个鼠标目标点;其 X 应位于可用距离外的受控超调范围。
|
||||
last := pts[len(pts)-1]
|
||||
if math.Abs(last.x-200) > 1e-9 {
|
||||
t.Fatalf("末端 x 必须精确等于 distance,got %.6f", last.x)
|
||||
if last.x < 204 || last.x > 220 {
|
||||
t.Fatalf("末端 x 应超出 distance 4 至 20px,got %.6f", last.x)
|
||||
}
|
||||
// 三阶段轨迹不超调,且保持向目标方向移动。
|
||||
// 三阶段轨迹保持向目标方向移动;超调只允许落在最后的受控鼠标目标范围内。
|
||||
for i := 1; i < len(pts); i++ {
|
||||
if pts[i].x < pts[i-1].x {
|
||||
t.Fatalf("轨迹 x 不单调: pts[%d]=%.1f < pts[%d]=%.1f", i, pts[i].x, i-1, pts[i-1].x)
|
||||
}
|
||||
if pts[i].x > 200 {
|
||||
t.Fatalf("主引擎轨迹不应超调: pts[%d]=%.1f", i, pts[i].x)
|
||||
if pts[i].x > 220 {
|
||||
t.Fatalf("主引擎轨迹超出受控范围: pts[%d]=%.1f", i, pts[i].x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenerateTrajectoryDelay 验证曲线锚点的相对时长有效,连续拖动由后续微移动事件负责分发。
|
||||
func TestGenerateTrajectoryDelay(t *testing.T) {
|
||||
pts := generateTrajectory(150)
|
||||
// pts 是本次生成的曲线锚点,用于汇总相对时长权重。
|
||||
pts := generateTrajectory(150, 34)
|
||||
// total 汇总锚点相对时长。
|
||||
var total time.Duration
|
||||
// i 表示采样点下标;pt 是当前待检查的轨迹点。
|
||||
for i, pt := range pts {
|
||||
total += pt.delay
|
||||
if pt.delay <= 0 || pt.delay > 8*time.Millisecond {
|
||||
if pt.delay <= 0 || pt.delay > 140*time.Millisecond {
|
||||
t.Fatalf("delay[%d]=%v 超出合理范围", i, pt.delay)
|
||||
}
|
||||
if pt.y < -1 || pt.y > 1 {
|
||||
t.Fatalf("y[%d]=%.2f 超出合理抖动", i, pt.y)
|
||||
}
|
||||
if total < 180*time.Millisecond || total > 1700*time.Millisecond {
|
||||
t.Fatalf("总轨迹时长不合理: %s", total)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExpandContinuousTrajectory 验证锚点间被拆为密集连续事件,且没有可见的中段静止间隔。
|
||||
func TestExpandContinuousTrajectory(t *testing.T) {
|
||||
// anchors 是简化的三段曲线锚点,delay 仅用作时间权重。
|
||||
anchors := []trajectoryPoint{
|
||||
{x: 20, y: 3, delay: 40 * time.Millisecond},
|
||||
{x: 110, y: -5, delay: 70 * time.Millisecond},
|
||||
{x: 180, y: 0, delay: 50 * time.Millisecond},
|
||||
}
|
||||
// target 是提速后完整按住拖动的墙钟目标时长;points 是展开后的微移动事件。
|
||||
target := 800 * time.Millisecond
|
||||
points := expandContinuousTrajectory(anchors, target)
|
||||
if len(points) <= len(anchors) {
|
||||
t.Fatalf("连续事件数=%d,应多于锚点数=%d", len(points), len(anchors))
|
||||
}
|
||||
// total 汇总事件延时;previousX 用于确认鼠标全程只向目标方向前进;distinctDelays 检查节奏是否有变化。
|
||||
var total time.Duration
|
||||
previousX := 0.0
|
||||
distinctDelays := make(map[time.Duration]struct{})
|
||||
for pointIndex, point := range points {
|
||||
if point.delay <= 0 || point.delay > sliderContinuousEventMaxInterval {
|
||||
t.Fatalf("delay[%d]=%s,不应形成可感知停顿", pointIndex, point.delay)
|
||||
}
|
||||
if point.x < previousX {
|
||||
t.Fatalf("x[%d]=%.3f 小于前一点 %.3f", pointIndex, point.x, previousX)
|
||||
}
|
||||
total += point.delay
|
||||
previousX = point.x
|
||||
distinctDelays[point.delay] = struct{}{}
|
||||
}
|
||||
if len(distinctDelays) < 2 {
|
||||
t.Fatalf("连续事件间隔不应全部相同: %v", distinctDelays)
|
||||
}
|
||||
if points[len(points)-1].x != anchors[len(anchors)-1].x || points[len(points)-1].y != anchors[len(anchors)-1].y {
|
||||
t.Fatalf("末点=(%.3f, %.3f),want=(%.3f, %.3f)", points[len(points)-1].x, points[len(points)-1].y, anchors[len(anchors)-1].x, anchors[len(anchors)-1].y)
|
||||
}
|
||||
if total > target || total < target-sliderContinuousEventMaxInterval {
|
||||
t.Fatalf("连续事件计划总时长=%s,want 接近 %s", total, target)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSliderMovementDurationRange 验证提速后的主引擎墙钟窗口仍有明确上下限。
|
||||
func TestSliderMovementDurationRange(t *testing.T) {
|
||||
if sliderMovementMinDuration != 550*time.Millisecond || sliderMovementMaxDuration != 1050*time.Millisecond {
|
||||
t.Fatalf("主引擎目标窗口=(%s,%s),want=(550ms,1050ms)", sliderMovementMinDuration, sliderMovementMaxDuration)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGenerateTrajectoryVerticalDrift 验证纵向路径连续、非线性,并且实际峰峰值严格等于滑轨高度的一半。
|
||||
func TestGenerateTrajectoryVerticalDrift(t *testing.T) {
|
||||
// trackHeight 是模拟标准 NC 轨道的像素高度;pts 是使用该高度生成的鼠标路径。
|
||||
const trackHeight = 34.0
|
||||
pts := generateTrajectory(258, trackHeight/2)
|
||||
// minY、maxY 收集路径的纵向边界;hasDirectionChange 确认路径不是单向线性斜线。
|
||||
minY, maxY := math.Inf(1), math.Inf(-1)
|
||||
hasDirectionChange := false
|
||||
// previousDelta 保存前一段的纵向增量;pointIndex、point 是当前遍历的路径位置和坐标。
|
||||
previousDelta := 0.0
|
||||
for pointIndex, point := range pts {
|
||||
minY = min(minY, point.y)
|
||||
maxY = max(maxY, point.y)
|
||||
if pointIndex == 0 {
|
||||
continue
|
||||
}
|
||||
// currentDelta 是当前段的纵向变化,符号改变表示连续曲线已穿过极值而非维持线性斜率。
|
||||
currentDelta := point.y - pts[pointIndex-1].y
|
||||
if previousDelta != 0 && currentDelta*previousDelta < 0 {
|
||||
hasDirectionChange = true
|
||||
}
|
||||
if currentDelta != 0 {
|
||||
previousDelta = currentDelta
|
||||
}
|
||||
}
|
||||
if total < 8*time.Millisecond || total > 35*time.Millisecond {
|
||||
t.Fatalf("总轨迹时长不合理: %s", total)
|
||||
if math.Abs((maxY-minY)-trackHeight/2) > 1e-9 {
|
||||
t.Fatalf("纵向峰峰值=%.6f want %.6f", maxY-minY, trackHeight/2)
|
||||
}
|
||||
if !hasDirectionChange || math.Abs(pts[0].y) > 1e-9 || math.Abs(pts[len(pts)-1].y) > 1e-9 {
|
||||
t.Fatalf("纵向路径必须从中心出发并以连续非线性曲线回到中心: first=%.6f last=%.6f changed=%v", pts[0].y, pts[len(pts)-1].y, hasDirectionChange)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,7 +218,7 @@ func TestSliderContainerStatesSucceeded(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestTrajectoryPhysics(t *testing.T) {
|
||||
pts := generateTrajectory(100)
|
||||
pts := generateTrajectory(100, 34)
|
||||
half := len(pts) / 2
|
||||
frontIncrement := pts[half-1].x - pts[0].x
|
||||
backIncrement := pts[len(pts)-1].x - pts[half].x
|
||||
|
||||
@@ -75,6 +75,8 @@ type tokenCaptchaDiagnosticNetworkEvent struct {
|
||||
Status int `json:"status,omitempty"`
|
||||
ContentType string `json:"content_type,omitempty"`
|
||||
Failure string `json:"failure,omitempty"`
|
||||
// BusinessResult 仅保存滑块接口响应中的脱敏业务结果,帮助区分轨迹被拒绝与网络失败;绝不保存滑块参数、Cookie 或响应正文。
|
||||
BusinessResult string `json:"business_result,omitempty"`
|
||||
}
|
||||
|
||||
// tokenCaptchaDiagnosticConsoleEvent 保存页面控制台输出,默认先去除可能出现的凭证和验证参数。
|
||||
@@ -238,29 +240,95 @@ func (d *tokenCaptchaDiagnostic) recordRequest(request playwright.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
// recordResponse 在 d.mu 保护下记录一条脱敏响应元数据,不读取可能包含凭证的响应正文。
|
||||
// recordResponse 在 d.mu 保护下记录一条脱敏响应元数据;仅对 /slide 响应提取受限业务结果,不持久化响应正文。
|
||||
func (d *tokenCaptchaDiagnostic) recordResponse(response playwright.Response) {
|
||||
// request 是与响应关联的请求,只用于记录方法、资源类型与是否为滑块提交。
|
||||
request := response.Request()
|
||||
// businessResult 是从滑块接口响应提炼出的有限状态,空值表示非滑块请求或响应不可安全解析。
|
||||
businessResult := ""
|
||||
if isTokenCaptchaSlideResponse(response.URL()) {
|
||||
// body、bodyErr 是 Playwright 已接收的响应副本及读取错误;只交给脱敏摘要器,不能写入诊断包或普通日志。
|
||||
body, bodyErr := response.Body()
|
||||
if bodyErr == nil {
|
||||
businessResult = tokenCaptchaSlideBusinessResult(body)
|
||||
}
|
||||
}
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.responses) >= tokenCaptchaDiagnosticMaxEvents {
|
||||
return
|
||||
}
|
||||
// request 是与响应关联的请求,只用于记录方法和资源类型;contentType 只记录公开的响应媒体类型。
|
||||
request := response.Request()
|
||||
// contentType 记录响应的公开媒体类型,不读取可能携带账号数据的响应正文。
|
||||
contentType := response.Headers()["content-type"]
|
||||
d.responses = append(d.responses, tokenCaptchaDiagnosticNetworkEvent{
|
||||
Kind: "response",
|
||||
At: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
URL: d.safeURL(response.URL()),
|
||||
Method: request.Method(),
|
||||
ResourceType: request.ResourceType(),
|
||||
Navigation: request.IsNavigationRequest(),
|
||||
Status: response.Status(),
|
||||
ContentType: contentType,
|
||||
Kind: "response",
|
||||
At: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
URL: d.safeURL(response.URL()),
|
||||
Method: request.Method(),
|
||||
ResourceType: request.ResourceType(),
|
||||
Navigation: request.IsNavigationRequest(),
|
||||
Status: response.Status(),
|
||||
ContentType: contentType,
|
||||
BusinessResult: businessResult,
|
||||
})
|
||||
}
|
||||
|
||||
// isTokenCaptchaSlideResponse 判断 URL 是否为当前 token 风控的滑块提交接口;只匹配路径,避免读取其他账号接口的响应体。
|
||||
func isTokenCaptchaSlideResponse(rawURL string) bool {
|
||||
// parsed 是结构化后的请求地址;err 表示地址无法解析,此时按非滑块接口处理以保持诊断最小化。
|
||||
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
return err == nil && strings.HasSuffix(strings.TrimRight(parsed.Path, "/"), "/slide")
|
||||
}
|
||||
|
||||
// tokenCaptchaSlideBusinessResult 从 /slide JSON 响应中提取顶层 ret、code 与 success 的脱敏摘要;body 只在函数栈内存在,返回值不含正文和验证参数。
|
||||
func tokenCaptchaSlideBusinessResult(body []byte) string {
|
||||
// decoded 只声明平台响应中允许诊断的顶层状态字段,未知字段包括滑块数据与会话信息均不会被解码或输出。
|
||||
decoded := struct {
|
||||
// Ret 是 MTOP 风格的业务结果数组,通常说明风控验证接受或拒绝原因。
|
||||
Ret []string `json:"ret"`
|
||||
// Code 是部分响应使用的数值或字符串状态码;RawMessage 防止把嵌套业务数据展开。
|
||||
Code json.RawMessage `json:"code"`
|
||||
// Success 是部分响应使用的顶层布尔成功标志。
|
||||
Success *bool `json:"success"`
|
||||
}{}
|
||||
// decodeErr 表示响应不是预期 JSON,诊断保持空而不把原文误写入工件。
|
||||
if decodeErr := json.Unmarshal(body, &decoded); decodeErr != nil {
|
||||
return ""
|
||||
}
|
||||
// parts 以固定、少量字段构成诊断摘要,禁止从 data 等嵌套字段拷贝内容。
|
||||
parts := make([]string, 0, 3)
|
||||
if len(decoded.Ret) > 0 {
|
||||
// retValues 是逐项脱敏后的 MTOP 结果,最多记录前三项以限制诊断大小与信息范围。
|
||||
retValues := make([]string, 0, min(3, len(decoded.Ret)))
|
||||
// retIndex、retValue 分别表示当前结果位置和原始结果文本;只把脱敏后的文本写入摘要。
|
||||
for retIndex, retValue := range decoded.Ret {
|
||||
if retIndex >= 3 {
|
||||
break
|
||||
}
|
||||
retValues = append(retValues, redactDiagnosticText(retValue))
|
||||
}
|
||||
parts = append(parts, "ret="+strings.Join(retValues, ","))
|
||||
}
|
||||
if len(decoded.Code) > 0 && string(decoded.Code) != "null" {
|
||||
// code 是顶层原始 JSON 标量;先验证其为字符串或数字,避免嵌套对象进入诊断。
|
||||
code := ""
|
||||
if json.Unmarshal(decoded.Code, &code) == nil {
|
||||
parts = append(parts, "code="+redactDiagnosticText(code))
|
||||
} else {
|
||||
// numericCode 是仅接受数字的备选状态码,其他 JSON 形状保持不记录。
|
||||
var numericCode json.Number
|
||||
if json.Unmarshal(decoded.Code, &numericCode) == nil {
|
||||
parts = append(parts, "code="+numericCode.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
if decoded.Success != nil {
|
||||
// success 是明确的布尔结果,格式化后不携带平台任意文本。
|
||||
parts = append(parts, fmt.Sprintf("success=%t", *decoded.Success))
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// safeURL 在默认模式删除 URL 查询值与 fragment,仅保留排序后的参数名和查询摘要;敏感模式由显式环境授权才原样返回。
|
||||
func (d *tokenCaptchaDiagnostic) safeURL(raw string) string {
|
||||
if d.includeSensitive {
|
||||
|
||||
@@ -35,6 +35,37 @@ func TestTokenCaptchaDiagnosticRedactsSensitiveValues(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestTokenCaptchaSlideBusinessResult 验证滑块响应诊断只保留受限顶层结果,并且不会将嵌套滑块数据或秘密值写入工件。
|
||||
func TestTokenCaptchaSlideBusinessResult(t *testing.T) {
|
||||
// body 是包含业务结果、敏感嵌套数据和无关字段的模拟滑块响应,测试仅允许前者进入摘要。
|
||||
body := []byte(`{"ret":["FAIL_SYS_USER_VALIDATE::x5secdata=secret-value","SECOND"],"code":403,"success":false,"data":{"slidedata":"secret-slide"}}`)
|
||||
// got 是默认诊断模式下的业务摘要。
|
||||
got := tokenCaptchaSlideBusinessResult(body)
|
||||
if !strings.Contains(got, "ret=FAIL_SYS_USER_VALIDATE::x5secdata=<redacted>,SECOND") || !strings.Contains(got, "code=403") || !strings.Contains(got, "success=false") {
|
||||
t.Fatalf("unexpected slide business result: %q", got)
|
||||
}
|
||||
if strings.Contains(got, "secret-value") || strings.Contains(got, "secret-slide") {
|
||||
t.Fatalf("slide business result leaked sensitive data: %q", got)
|
||||
}
|
||||
// nonSlideURL 是普通 MTOP 地址,不得触发任何响应正文读取。
|
||||
nonSlideURL := "https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.login.token/1.0/report"
|
||||
if isTokenCaptchaSlideResponse(nonSlideURL) {
|
||||
t.Fatalf("ordinary response incorrectly treated as slide: %q", nonSlideURL)
|
||||
}
|
||||
// slideURL 是真实接口形状的滑块地址,尾部斜杠也必须被正确识别。
|
||||
slideURL := "https://h5api.m.goofish.com/h5/mtop.taobao.idlemessage.pc.login.token/1.0/slide/"
|
||||
if !isTokenCaptchaSlideResponse(slideURL) {
|
||||
t.Fatalf("slide response was not recognized: %q", slideURL)
|
||||
}
|
||||
// malformedBody 不能被当作可诊断 JSON,必须返回空摘要而非回显原文。
|
||||
malformedBody := []byte("secret malformed response")
|
||||
// malformedResult 是无法解析的响应摘要,必须保持为空以避免泄漏原始文本。
|
||||
malformedResult := tokenCaptchaSlideBusinessResult(malformedBody)
|
||||
if malformedResult != "" {
|
||||
t.Fatalf("malformed response should not be recorded: %q", malformedResult)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTokenCaptchaDiagnosticBundleBrowserIntegration 在真实 Chromium 中验证诊断包包含必要现场且默认不泄漏验证码查询值;仅在显式浏览器集成模式运行。
|
||||
func TestTokenCaptchaDiagnosticBundleBrowserIntegration(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
|
||||
@@ -221,6 +221,9 @@ func fallbackChromiumArgs(profileDir string, headless bool, headlessUserAgent ..
|
||||
if captchaIgnoreCertificateErrors() {
|
||||
args = append(args, "--ignore-certificate-errors")
|
||||
}
|
||||
if proxy := captchaBrowserProxy(); proxy != "" {
|
||||
args = append(args, "--proxy-server="+proxy)
|
||||
}
|
||||
if headless && len(headlessUserAgent) > 0 && headlessUserAgent[0] != nil {
|
||||
if userAgent := normalizeHeadlessUserAgent(*headlessUserAgent[0]); userAgent != "" {
|
||||
args = append(args, "--user-agent="+userAgent)
|
||||
|
||||
@@ -8,7 +8,9 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -32,12 +34,27 @@ const slider = document.querySelector('#nc_1_n1z');
|
||||
let pressed = false;
|
||||
let released = false;
|
||||
let startX = 0;
|
||||
let dragMoveCount = 0;
|
||||
let dragStartedAt = 0;
|
||||
let dragEndedAt = 0;
|
||||
let dragMinY = Infinity;
|
||||
let dragMaxY = -Infinity;
|
||||
let dragMaxX = -Infinity;
|
||||
slider.addEventListener('mousedown', event => {
|
||||
pressed = true;
|
||||
startX = event.clientX;
|
||||
dragStartedAt = performance.now();
|
||||
});
|
||||
document.addEventListener('mousemove', event => {
|
||||
if (!pressed) return;
|
||||
dragMoveCount++;
|
||||
dragMinY = Math.min(dragMinY, event.clientY);
|
||||
dragMaxY = Math.max(dragMaxY, event.clientY);
|
||||
dragMaxX = Math.max(dragMaxX, event.clientX);
|
||||
});
|
||||
window.addEventListener('mouseup', () => {
|
||||
released = pressed;
|
||||
if (released) dragEndedAt = performance.now();
|
||||
});
|
||||
slider.addEventListener('click', event => {
|
||||
if (!released || event.clientX - startX < 300) return;
|
||||
@@ -86,13 +103,37 @@ slider.addEventListener('click', event => {
|
||||
if _, fresh := freshX5Cookies(cookies, nil); !fresh || isPunishURL(page.URL()) {
|
||||
t.Fatalf("slider did not complete reference success flow: url=%s cookies=%v", page.URL(), cookies)
|
||||
}
|
||||
// motionState 记录页面实际观察到的按下后移动数和拖动耗时,用真实 Chromium 防止轨迹退回固定短促动作。
|
||||
motionState, err := page.Evaluate(`() => ({ dragMoveCount, dragDuration: dragEndedAt - dragStartedAt, dragVerticalSpan: dragMaxY - dragMinY, dragOvershoot: dragMaxX - startX - 376 })`)
|
||||
if err != nil {
|
||||
t.Fatalf("读取真实滑动轨迹状态: %v", err)
|
||||
}
|
||||
// motionValues 是页面返回的可序列化状态,后续只读取非敏感的事件计数与耗时。
|
||||
motionValues, ok := motionState.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("真实滑动状态类型=%T", motionState)
|
||||
}
|
||||
// moveCount、durationMS、verticalSpan、overshoot 分别是按下后事件数、墙钟毫秒数、实际纵向峰峰值和超出可用轨道的鼠标距离;Playwright 可能把 JS 数字解码为不同 Go 数字类型。
|
||||
moveCount, moveCountErr := strconv.ParseFloat(fmt.Sprint(motionValues["dragMoveCount"]), 64)
|
||||
durationMS, durationErr := strconv.ParseFloat(fmt.Sprint(motionValues["dragDuration"]), 64)
|
||||
verticalSpan, verticalSpanErr := strconv.ParseFloat(fmt.Sprint(motionValues["dragVerticalSpan"]), 64)
|
||||
overshoot, overshootErr := strconv.ParseFloat(fmt.Sprint(motionValues["dragOvershoot"]), 64)
|
||||
if moveCountErr != nil || durationErr != nil || verticalSpanErr != nil || overshootErr != nil {
|
||||
t.Fatalf("真实滑动状态字段无效: %#v", motionValues)
|
||||
}
|
||||
if moveCount < 8 || durationMS < 450 || durationMS > 1300 || verticalSpan < 20 || verticalSpan > 24 || overshoot < 4 || overshoot > 20 {
|
||||
t.Fatalf("真实轨迹应包含连续多点、提速后的墙钟范围、半轨道高度纵向范围和受控超调: moves=%.0f duration_ms=%.0f vertical_span=%.0f overshoot=%.0f", moveCount, durationMS, verticalSpan, overshoot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlaywrightSliderRecoversFromHiddenFailureState(t *testing.T) {
|
||||
if os.Getenv("RUN_BROWSER_INTEGRATION") != "1" {
|
||||
t.Skip("set RUN_BROWSER_INTEGRATION=1 to exercise slider failure recovery")
|
||||
}
|
||||
// requestCount 统计验证页文档请求次数,已滑动失败后的重试必须保持为一次请求,不能通过 reload 恢复。
|
||||
var requestCount atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requestCount.Add(1)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
_, _ = io.WriteString(w, `<!doctype html><html><head><title>验证码拦截</title></head><body>
|
||||
<div id="nocaptcha" class="nc-container"><div id="nc_1_wrapper"></div></div>
|
||||
@@ -168,6 +209,11 @@ document.addEventListener('click', event => {
|
||||
if !ok || fmt.Sprint(values["dragAttempts"]) != "2" || fmt.Sprint(values["retryClicks"]) != "1" {
|
||||
t.Fatalf("unexpected retry state: %#v", state)
|
||||
}
|
||||
// requests 是测试期间导航验证页的文档请求数;第二次请求意味着恢复逻辑错误地刷新了页面。
|
||||
requests := requestCount.Load()
|
||||
if requests != 1 {
|
||||
t.Fatalf("滑动失败后应点击失败按钮直接重试,验证页请求数=%d", requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenCaptchaDirectErrorPageBrowserIntegration(t *testing.T) {
|
||||
|
||||
Reference in new issue
Block a user