feat: 更新 OAuth 流程,调整步骤 6 和步骤 7 的逻辑,添加相关测试

This commit is contained in:
QLHazyCoder
2026-04-19 18:59:32 +08:00
parent 17e1c672f1
commit 7cb1bda672
12 changed files with 372 additions and 68 deletions
+186
View File
@@ -0,0 +1,186 @@
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;
}
}
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('throwIfStopped rethrows an explicit stop error even when stopRequested has been cleared', () => {
const api = new Function(`
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
let stopRequested = false;
${extractFunction('isStopError')}
${extractFunction('throwIfStopped')}
return {
run(error) {
throwIfStopped(error);
},
};
`)();
assert.throws(
() => api.run(new Error('流程已被用户停止。')),
/流程已被用户停止。/
);
});
test('executeStep reuses the active top-level auth chain instead of starting a duplicate step', async () => {
const api = new Function(`
const LOG_PREFIX = '[test]';
const STOP_ERROR_MESSAGE = '流程已被用户停止。';
const AUTH_CHAIN_STEP_IDS = new Set([7, 8, 9, 10]);
let activeTopLevelAuthChainExecution = null;
let stopRequested = false;
let releaseStep8 = null;
const events = {
logs: [],
statusCalls: [],
registryCalls: [],
};
const state = {
stepStatuses: {},
};
async function addLog(message, level = 'info') {
events.logs.push({ message, level });
}
async function setStepStatus(step, status) {
state.stepStatuses[step] = status;
events.statusCalls.push({ step, status });
}
async function humanStepDelay() {}
async function getState() {
return {
flowStartTime: null,
stepStatuses: { ...state.stepStatuses },
};
}
function getErrorMessage(error) {
return error?.message || String(error || '');
}
async function appendManualAccountRunRecordIfNeeded() {}
function isTerminalSecurityBlockedError() {
return false;
}
async function handleCloudflareSecurityBlocked() {}
function doesStepUseCompletionSignal() {
return false;
}
function isRetryableContentScriptTransportError() {
return false;
}
const stepRegistry = {
async executeStep(step) {
events.registryCalls.push(step);
if (step === 8) {
await new Promise((resolve) => {
releaseStep8 = resolve;
});
}
},
};
${extractFunction('isStopError')}
${extractFunction('throwIfStopped')}
${extractFunction('isAuthChainStep')}
${extractFunction('acquireTopLevelAuthChainExecution')}
${extractFunction('executeStep')}
return {
executeStep,
releaseStep8() {
if (releaseStep8) {
releaseStep8();
}
},
snapshot() {
return events;
},
};
`)();
const firstRun = api.executeStep(8);
await new Promise((resolve) => setImmediate(resolve));
const duplicateRun = api.executeStep(7);
await new Promise((resolve) => setImmediate(resolve));
api.releaseStep8();
await firstRun;
await duplicateRun;
const events = api.snapshot();
assert.deepStrictEqual(events.registryCalls, [8]);
assert.deepStrictEqual(events.statusCalls, [
{ step: 8, status: 'running' },
]);
assert.ok(events.logs.some(({ message }) => /复用当前授权链/.test(message)));
});
test('oauth timeout budget ignores stale deadlines from an old oauth url', async () => {
const api = new Function(`
const LOG_PREFIX = '[test]';
const OAUTH_FLOW_TIMEOUT_MS = 6 * 60 * 1000;
${extractFunction('normalizeOAuthFlowDeadlineAt')}
${extractFunction('normalizeOAuthFlowSourceUrl')}
${extractFunction('getOAuthFlowRemainingMs')}
${extractFunction('getOAuthFlowStepTimeoutMs')}
return {
getOAuthFlowStepTimeoutMs,
};
`)();
const timeoutMs = await api.getOAuthFlowStepTimeoutMs(15000, {
step: 8,
actionLabel: '登录验证码流程',
state: {
oauthUrl: 'https://oauth.example/current',
oauthFlowDeadlineAt: Date.now() + 1200,
oauthFlowDeadlineSourceUrl: 'https://oauth.example/old',
},
});
assert.equal(timeoutMs, 15000);
});
@@ -15,3 +15,9 @@ test('panel bridge module exposes a factory', () => {
assert.equal(typeof api?.createPanelBridge, 'function');
});
test('panel bridge requests oauth url with step 7 log label payload', () => {
const source = fs.readFileSync('background/panel-bridge.js', 'utf8');
assert.match(source, /logStep:\s*7/);
assert.doesNotMatch(source, /logStep:\s*6/);
});
@@ -172,6 +172,7 @@ test('step 7 starts a new oauth timeout window for each refreshed oauth url', as
options: {
step: 7,
actionLabel: 'OAuth 登录并进入验证码页',
oauthUrl: 'https://oauth.example/latest',
},
},
]);
+10 -18
View File
@@ -10,8 +10,7 @@ test('step 8 submits login verification directly without replaying step 7', asyn
const calls = {
ensureReady: 0,
ensureReadyOptions: [],
executeStep7: 0,
sleep: [],
rerunStep7: 0,
resolveOptions: null,
setStates: [],
};
@@ -32,8 +31,8 @@ test('step 8 submits login verification directly without replaying step 7', asyn
calls.ensureReadyOptions.push(options || null);
return { state: 'verification_page', displayedEmail: 'display.user@example.com' };
},
executeStep7: async () => {
calls.executeStep7 += 1;
rerunStep7ForStep8Recovery: async () => {
calls.rerunStep7 += 1;
},
getOAuthFlowRemainingMs: async () => 5000,
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => Math.min(defaultTimeoutMs, 5000),
@@ -59,9 +58,6 @@ test('step 8 submits login verification directly without replaying step 7', asyn
},
setStepStatus: async () => {},
shouldUseCustomRegistrationEmail: () => false,
sleepWithStop: async (ms) => {
calls.sleep.push(ms);
},
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS: 8,
throwIfStopped: () => {},
@@ -79,8 +75,7 @@ test('step 8 submits login verification directly without replaying step 7', asyn
assert.equal(calls.resolveOptions.beforeSubmit, undefined);
assert.equal(calls.ensureReady, 1);
assert.equal(calls.executeStep7, 0);
assert.deepStrictEqual(calls.sleep, []);
assert.equal(calls.rerunStep7, 0);
assert.equal(calls.resolveOptions.filterAfterTimestamp, 123456);
assert.equal(typeof calls.resolveOptions.getRemainingTimeMs, 'function');
assert.equal(await calls.resolveOptions.getRemainingTimeMs({ actionLabel: '登录验证码流程' }), 5000);
@@ -107,7 +102,7 @@ test('step 8 disables resend interval for 2925 mailbox polling', async () => {
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
confirmCustomVerificationStepBypass: async () => {},
ensureStep8VerificationPageReady: async () => ({ state: 'verification_page' }),
executeStep7: async () => {},
rerunStep7ForStep8Recovery: async () => {},
getOAuthFlowRemainingMs: async () => 8000,
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => Math.min(defaultTimeoutMs, 8000),
getMailConfig: () => ({
@@ -130,7 +125,6 @@ test('step 8 disables resend interval for 2925 mailbox polling', async () => {
setState: async () => {},
setStepStatus: async () => {},
shouldUseCustomRegistrationEmail: () => false,
sleepWithStop: async () => {},
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS: 8,
throwIfStopped: () => {},
@@ -161,7 +155,7 @@ test('step 8 falls back to the run email when the verification page does not exp
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
confirmCustomVerificationStepBypass: async () => {},
ensureStep8VerificationPageReady: async () => ({ state: 'verification_page', displayedEmail: '' }),
executeStep7: async () => {},
rerunStep7ForStep8Recovery: async () => {},
getOAuthFlowRemainingMs: async () => 8000,
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => Math.min(defaultTimeoutMs, 8000),
getMailConfig: () => ({
@@ -184,7 +178,6 @@ test('step 8 falls back to the run email when the verification page does not exp
setState: async () => {},
setStepStatus: async () => {},
shouldUseCustomRegistrationEmail: () => false,
sleepWithStop: async () => {},
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS: 8,
throwIfStopped: () => {},
@@ -201,7 +194,7 @@ test('step 8 falls back to the run email when the verification page does not exp
test('step 8 does not rerun step 7 when verification submit lands on add-phone', async () => {
const calls = {
executeStep7: 0,
rerunStep7: 0,
logs: [],
};
@@ -217,8 +210,8 @@ test('step 8 does not rerun step 7 when verification submit lands on add-phone',
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
confirmCustomVerificationStepBypass: async () => {},
ensureStep8VerificationPageReady: async () => ({ state: 'verification_page' }),
executeStep7: async () => {
calls.executeStep7 += 1;
rerunStep7ForStep8Recovery: async () => {
calls.rerunStep7 += 1;
},
getOAuthFlowRemainingMs: async () => 8000,
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => Math.min(defaultTimeoutMs, 8000),
@@ -242,7 +235,6 @@ test('step 8 does not rerun step 7 when verification submit lands on add-phone',
setState: async () => {},
setStepStatus: async () => {},
shouldUseCustomRegistrationEmail: () => false,
sleepWithStop: async () => {},
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS: 8,
throwIfStopped: () => {},
@@ -257,6 +249,6 @@ test('step 8 does not rerun step 7 when verification submit lands on add-phone',
/add-phone/
);
assert.equal(calls.executeStep7, 0);
assert.equal(calls.rerunStep7, 0);
assert.ok(!calls.logs.some(({ message }) => /准备从步骤 7 重新开始/.test(message)));
});
+11 -9
View File
@@ -117,10 +117,10 @@ return {
test('step 8 reruns step 7 when auth page enters login timeout retry state', async () => {
const calls = {
executeStep7: 0,
rerunStep7: 0,
ensureReady: 0,
logs: [],
sleeps: [],
rerunOptions: [],
resolveCalls: 0,
};
@@ -142,8 +142,9 @@ test('step 8 reruns step 7 when auth page enters login timeout retry state', asy
}
return { state: 'verification_page' };
},
executeStep7: async () => {
calls.executeStep7 += 1;
rerunStep7ForStep8Recovery: async (options) => {
calls.rerunStep7 += 1;
calls.rerunOptions.push(options || null);
},
getOAuthFlowRemainingMs: async () => 8000,
getOAuthFlowStepTimeoutMs: async (defaultTimeoutMs) => Math.min(defaultTimeoutMs, 8000),
@@ -167,9 +168,6 @@ test('step 8 reruns step 7 when auth page enters login timeout retry state', asy
setState: async () => {},
setStepStatus: async () => {},
shouldUseCustomRegistrationEmail: () => false,
sleepWithStop: async (ms) => {
calls.sleeps.push(ms);
},
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS: 3,
throwIfStopped: () => {},
@@ -181,9 +179,13 @@ test('step 8 reruns step 7 when auth page enters login timeout retry state', asy
oauthUrl: 'https://oauth.example/latest',
});
assert.equal(calls.executeStep7, 1);
assert.equal(calls.rerunStep7, 1);
assert.equal(calls.ensureReady, 2);
assert.equal(calls.resolveCalls, 1);
assert.equal(calls.logs.some(({ message }) => /重新开始|重新发起/.test(message)), true);
assert.deepStrictEqual(calls.sleeps, [3000]);
assert.deepStrictEqual(calls.rerunOptions, [
{
logMessage: '步骤 8:认证页进入重试/超时报错状态,正在回到步骤 7 重新发起登录流程...',
},
]);
});