feat: 增强错误处理逻辑,添加 Cloudflare 风控和网络超时拦截提示

This commit is contained in:
QLHazyCoder
2026-04-18 20:54:00 +08:00
parent 82471af931
commit 609cdeaeb5
12 changed files with 440 additions and 17 deletions
+44 -4
View File
@@ -65,7 +65,7 @@ function createRecoveryApi(state) {
test('auth page recovery detects retry page state', () => {
const state = {
clickCount: 0,
pageText: 'Something went wrong. Operation timed out.',
pageText: 'Something went wrong. Please try again.',
retryVisible: true,
};
const api = createRecoveryApi(state);
@@ -77,13 +77,15 @@ test('auth page recovery detects retry page state', () => {
assert.equal(Boolean(snapshot), true);
assert.equal(snapshot.retryEnabled, true);
assert.equal(snapshot.titleMatched, true);
assert.equal(snapshot.detailMatched, true);
assert.equal(snapshot.detailMatched, false);
assert.equal(snapshot.maxCheckAttemptsBlocked, false);
assert.equal(snapshot.operationTimedOutBlocked, false);
});
test('auth page recovery clicks retry and waits until page recovers', async () => {
const state = {
clickCount: 0,
pageText: 'Something went wrong. Operation timed out.',
pageText: 'Something went wrong. Please try again.',
retryVisible: true,
};
const api = createRecoveryApi(state);
@@ -107,7 +109,7 @@ test('auth page recovery clicks retry and waits until page recovers', async () =
test('auth page recovery can click retry twice before page recovers', async () => {
const state = {
clickCount: 0,
pageText: 'Something went wrong. Operation timed out.',
pageText: 'Something went wrong. Please try again.',
retryVisible: true,
onClick(currentState) {
if (currentState.clickCount >= 2) {
@@ -135,3 +137,41 @@ test('auth page recovery can click retry twice before page recovers', async () =
assert.equal(state.clickCount, 2);
assert.equal(state.retryVisible, false);
});
test('auth page recovery throws cloudflare security blocked error on max_check_attempts page', async () => {
const state = {
clickCount: 0,
pageText: 'Something went wrong. max_check_attempts reached.',
retryVisible: true,
};
const api = createRecoveryApi(state);
await assert.rejects(
() => api.recoverAuthRetryPage({
logLabel: '步骤 7:检测到登录超时报错,正在点击“重试”恢复当前页面',
pathPatterns: [/\/log-in(?:[/?#]|$)/i],
step: 7,
timeoutMs: 1000,
}),
/CF_SECURITY_BLOCKED::/
);
});
test('auth page recovery throws network timeout block error on operation timed out page', async () => {
const state = {
clickCount: 0,
pageText: 'Something went wrong. Operation timed out.',
retryVisible: true,
};
const api = createRecoveryApi(state);
await assert.rejects(
() => api.recoverAuthRetryPage({
logLabel: '步骤 7:检测到登录超时报错,正在点击“重试”恢复当前页面',
pathPatterns: [/\/log-in(?:[/?#]|$)/i],
step: 7,
timeoutMs: 1000,
}),
/NETWORK_TIMEOUT_BLOCKED::/
);
});
@@ -14,6 +14,7 @@ function createRouter(overrides = {}) {
finalizePayloads: [],
notifyCompletions: [],
notifyErrors: [],
securityBlocks: [],
};
const router = api.createMessageRouter({
@@ -56,8 +57,14 @@ function createRouter(overrides = {}) {
getState: async () => overrides.state || { stepStatuses: { 3: 'pending' } },
getStopRequested: () => false,
handleAutoRunLoopUnhandledError: async () => {},
handleCloudflareSecurityBlocked: overrides.handleCloudflareSecurityBlocked || (async (error) => {
const message = typeof error === 'string' ? error : error?.message || '';
events.securityBlocks.push(message);
return message.replace(/^(?:CF_SECURITY_BLOCKED|NETWORK_TIMEOUT_BLOCKED)::/, '') || message;
}),
importSettingsBundle: async () => {},
invalidateDownstreamAfterStepRestart: async () => {},
isCloudflareSecurityBlockedError: overrides.isCloudflareSecurityBlockedError || ((error) => /^(?:CF_SECURITY_BLOCKED|NETWORK_TIMEOUT_BLOCKED)::/.test(typeof error === 'string' ? error : error?.message || '')),
isAutoRunLockedState: () => false,
isHotmailProvider: () => false,
isLocalhostOAuthCallbackUrl: () => true,
@@ -195,3 +202,50 @@ test('message router marks step 3 failed when post-submit finalize fails', async
assert.equal(events.logs.some(({ message }) => /步骤 3 失败步骤 3 提交后仍停留在密码页/.test(message)), true);
assert.deepStrictEqual(response, { ok: true, error: '步骤 3 提交后仍停留在密码页。' });
});
test('message router stops the flow and surfaces cloudflare security block errors', async () => {
const { router, events } = createRouter();
const response = await router.handleMessage({
type: 'STEP_ERROR',
step: 7,
source: 'signup-page',
payload: {},
error: 'CF_SECURITY_BLOCKED::您已触发Cloudflare 安全防护系统',
}, {});
assert.deepStrictEqual(events.securityBlocks, ['CF_SECURITY_BLOCKED::您已触发Cloudflare 安全防护系统']);
assert.deepStrictEqual(events.notifyErrors, [
{
step: 7,
error: '流程已被用户停止。',
},
]);
assert.deepStrictEqual(response, {
ok: true,
error: '您已触发Cloudflare 安全防护系统',
});
});
test('message router stops the flow and surfaces network timeout block errors', async () => {
const { router, events } = createRouter();
const response = await router.handleMessage({
type: 'STEP_ERROR',
step: 7,
source: 'signup-page',
payload: {},
error: 'NETWORK_TIMEOUT_BLOCKED::请检查当前网络节点是否稳定',
}, {});
assert.deepStrictEqual(events.securityBlocks, ['NETWORK_TIMEOUT_BLOCKED::请检查当前网络节点是否稳定']);
assert.deepStrictEqual(events.notifyErrors, [
{
step: 7,
error: '流程已被用户停止。',
},
]);
assert.deepStrictEqual(response, {
ok: true,
error: '请检查当前网络节点是否稳定',
});
});
@@ -0,0 +1,74 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const source = fs.readFileSync('background.js', 'utf8');
function extractFunction(name) {
const markers = [`async function ${name}(`, `function ${name}(`];
const start = markers
.map((marker) => source.indexOf(marker))
.find((index) => index >= 0);
if (start < 0) {
throw new Error(`missing function ${name}`);
}
let parenDepth = 0;
let signatureEnded = false;
let braceStart = -1;
for (let i = start; i < source.length; i += 1) {
const ch = source[i];
if (ch === '(') {
parenDepth += 1;
} else if (ch === ')') {
parenDepth -= 1;
if (parenDepth === 0) {
signatureEnded = true;
}
} else if (ch === '{' && signatureEnded) {
braceStart = i;
break;
}
}
if (braceStart < 0) {
throw new Error(`missing body for function ${name}`);
}
let depth = 0;
let end = braceStart;
for (; end < source.length; end += 1) {
const ch = source[end];
if (ch === '{') depth += 1;
if (ch === '}') {
depth -= 1;
if (depth === 0) {
end += 1;
break;
}
}
}
return source.slice(start, end);
}
test('security blocked alert title distinguishes cloudflare and network timeout', () => {
const api = new Function(`
const CLOUDFLARE_SECURITY_BLOCK_ERROR_PREFIX = 'CF_SECURITY_BLOCKED::';
const NETWORK_TIMEOUT_BLOCK_ERROR_PREFIX = 'NETWORK_TIMEOUT_BLOCKED::';
${extractFunction('getErrorMessage')}
${extractFunction('isCloudflareSecurityBlockedError')}
${extractFunction('isNetworkTimeoutBlockedError')}
${extractFunction('getTerminalSecurityBlockedTitle')}
return { getTerminalSecurityBlockedTitle };
`)();
assert.equal(
api.getTerminalSecurityBlockedTitle(new Error('CF_SECURITY_BLOCKED::blocked')),
'Cloudflare 风控拦截'
);
assert.equal(
api.getTerminalSecurityBlockedTitle(new Error('NETWORK_TIMEOUT_BLOCKED::timeout')),
'网络节点异常'
);
});
+2 -2
View File
@@ -51,7 +51,7 @@ function extractFunction(name) {
return source.slice(start, end);
}
test('step 7 timeout recoverable result no longer clicks retry before asking background to rerun', async () => {
test('step 7 timeout recoverable result clicks retry before asking background to rerun', async () => {
const api = new Function(`
const logs = [];
let recoverCalls = 0;
@@ -97,7 +97,7 @@ return {
const result = await api.run();
const snapshot = api.snapshot();
assert.equal(snapshot.recoverCalls, 0);
assert.equal(snapshot.recoverCalls, 1);
assert.equal(result.step6Outcome, 'recoverable');
assert.equal(result.reason, 'login_timeout_error_page');
assert.equal(result.state, 'login_timeout_error_page');
+73 -5
View File
@@ -58,7 +58,7 @@ function extractFunction(source, name) {
test('ensureStep8VerificationPageReady throws explicit restart-step7 error on login timeout page', async () => {
const api = new Function(`
function getLoginAuthStateLabel(state) {
return state === 'login_timeout_error_page' ? '登录超时报错页' : '未知页面';
return state === 'login_timeout_error_page' ? 'login timeout page' : 'unknown page';
}
async function getLoginAuthStateFromContent() {
@@ -79,7 +79,75 @@ return {
await assert.rejects(
() => api.run(),
/STEP8_RESTART_STEP7::步骤 8:当前认证页进入登录超时报错页/
/STEP8_RESTART_STEP7::/
);
});
test('ensureStep8VerificationPageReady throws cloudflare security block error on max_check_attempts page', async () => {
const api = new Function(`
const CLOUDFLARE_SECURITY_BLOCK_ERROR_PREFIX = 'CF_SECURITY_BLOCKED::';
const CLOUDFLARE_SECURITY_BLOCK_USER_MESSAGE = 'cloudflare blocked';
const NETWORK_TIMEOUT_BLOCK_ERROR_PREFIX = 'NETWORK_TIMEOUT_BLOCKED::';
const NETWORK_TIMEOUT_BLOCK_USER_MESSAGE = 'network timeout blocked';
function getLoginAuthStateLabel(state) {
return state === 'login_timeout_error_page' ? 'login timeout page' : 'unknown page';
}
async function getLoginAuthStateFromContent() {
return {
state: 'login_timeout_error_page',
url: 'https://auth.openai.com/log-in',
maxCheckAttemptsBlocked: true,
};
}
${extractFunction(backgroundSource, 'ensureStep8VerificationPageReady')}
return {
run() {
return ensureStep8VerificationPageReady({});
},
};
`)();
await assert.rejects(
() => api.run(),
/CF_SECURITY_BLOCKED::/
);
});
test('ensureStep8VerificationPageReady throws network timeout block error on operation timed out page', async () => {
const api = new Function(`
const CLOUDFLARE_SECURITY_BLOCK_ERROR_PREFIX = 'CF_SECURITY_BLOCKED::';
const CLOUDFLARE_SECURITY_BLOCK_USER_MESSAGE = 'cloudflare blocked';
const NETWORK_TIMEOUT_BLOCK_ERROR_PREFIX = 'NETWORK_TIMEOUT_BLOCKED::';
const NETWORK_TIMEOUT_BLOCK_USER_MESSAGE = 'network timeout blocked';
function getLoginAuthStateLabel(state) {
return state === 'login_timeout_error_page' ? 'login timeout page' : 'unknown page';
}
async function getLoginAuthStateFromContent() {
return {
state: 'login_timeout_error_page',
url: 'https://auth.openai.com/log-in',
operationTimedOutBlocked: true,
};
}
${extractFunction(backgroundSource, 'ensureStep8VerificationPageReady')}
return {
run() {
return ensureStep8VerificationPageReady({});
},
};
`)();
await assert.rejects(
() => api.run(),
/NETWORK_TIMEOUT_BLOCKED::/
);
});
@@ -106,7 +174,7 @@ test('step 8 reruns step 7 when auth page enters login timeout retry state', asy
ensureStep8VerificationPageReady: async () => {
calls.ensureReady += 1;
if (calls.ensureReady === 1) {
throw new Error('STEP8_RESTART_STEP7::步骤 8:当前认证页进入登录超时报错页,请回到步骤 7 重新开始。 URL: https://auth.openai.com/log-in');
throw new Error('STEP8_RESTART_STEP7::step 8 timeout retry page');
}
return { state: 'verification_page' };
},
@@ -117,7 +185,7 @@ test('step 8 reruns step 7 when auth page enters login timeout retry state', asy
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => Math.min(defaultTimeoutMs, 8000),
getMailConfig: () => ({
provider: 'qq',
label: 'QQ 邮箱',
label: 'QQ mail',
source: 'mail-qq',
url: 'https://mail.qq.com',
navigateOnReuse: false,
@@ -152,6 +220,6 @@ test('step 8 reruns step 7 when auth page enters login timeout retry state', asy
assert.equal(calls.executeStep7, 1);
assert.equal(calls.ensureReady, 2);
assert.equal(calls.resolveCalls, 1);
assert.equal(calls.logs.some(({ message }) => /准备从步骤 7 重新开始/.test(message)), true);
assert.equal(calls.logs.some(({ message }) => /重新开始|重新发起/.test(message)), true);
assert.deepStrictEqual(calls.sleeps, [3000]);
});