修复自定义邮箱收码模式默认手动

This commit is contained in:
QLHazyCoder
2026-05-28 06:14:04 +08:00
parent 1960b6e21a
commit 2992cc88ac
18 changed files with 1154 additions and 6 deletions
@@ -54,6 +54,84 @@ test('flow mail polling service dispatches API mail providers through shared hel
assert.equal(logs.some((entry) => entry.message.includes('Hotmail')), true);
});
test('flow mail polling service dispatches custom helper when custom provider is in helper mode', async () => {
const api = loadFlowMailPollingApi();
let customCall = null;
const service = api.createFlowMailPollingService({
addLog: async () => {},
buildVerificationPollPayloadForNode: (nodeId, state, overrides) => ({
flowId: state.activeFlowId,
nodeId,
step: 4,
targetEmail: 'custom@example.com',
maxAttempts: 1,
intervalMs: 100,
...overrides,
}),
CUSTOM_MAIL_PROVIDER: 'custom',
getMailConfig: () => ({ provider: 'custom', label: '自定义邮箱' }),
pollCustomMailVerificationCode: async (step, state, payload) => {
customCall = { step, state, payload };
return { code: '654321', emailTimestamp: 123 };
},
});
const result = await service.pollFlowVerificationCode({
flowId: 'kiro',
nodeId: 'kiro-submit-verification-code',
state: {
activeFlowId: 'kiro',
mailProvider: 'custom',
customMailReceiveMode: 'helper',
email: 'custom@example.com',
},
step: 4,
});
assert.equal(result.code, '654321');
assert.equal(customCall.step, 4);
assert.equal(customCall.payload.targetEmail, 'custom@example.com');
});
test('flow mail polling service rejects custom manual mode before helper polling', async () => {
const api = loadFlowMailPollingApi();
let customCallCount = 0;
const service = api.createFlowMailPollingService({
addLog: async () => {},
buildVerificationPollPayloadForNode: (nodeId, state, overrides) => ({
flowId: state.activeFlowId,
nodeId,
step: 4,
targetEmail: 'custom@example.com',
maxAttempts: 1,
intervalMs: 100,
...overrides,
}),
CUSTOM_MAIL_PROVIDER: 'custom',
getMailConfig: () => ({ provider: 'custom', label: '自定义邮箱' }),
pollCustomMailVerificationCode: async () => {
customCallCount += 1;
return { code: '654321', emailTimestamp: 123 };
},
});
await assert.rejects(
() => service.pollFlowVerificationCode({
flowId: 'kiro',
nodeId: 'kiro-submit-verification-code',
state: {
activeFlowId: 'kiro',
mailProvider: 'custom',
customMailReceiveMode: 'manual',
email: 'custom@example.com',
},
step: 4,
}),
/手动确认模式/
);
assert.equal(customCallCount, 0);
});
test('flow mail polling service prepares browser mail provider sessions and payload timeouts', async () => {
const api = loadFlowMailPollingApi();
let ensured2925 = null;
@@ -81,6 +81,8 @@ const SETTINGS_SCHEMA_VIEW_KEYS = Object.freeze([
'plusPaymentMethod',
'plusAccountAccessStrategy',
'mailProvider',
'customMailReceiveMode',
'customMailHelperBaseUrl',
'ipProxyEnabled',
'ipProxyService',
'ipProxyMode',
@@ -98,6 +100,8 @@ const PERSISTED_SETTING_DEFAULTS = {
plusAccountAccessStrategy: 'oauth',
phoneVerificationEnabled: false,
mailProvider: '163',
customMailReceiveMode: 'manual',
customMailHelperBaseUrl: 'http://127.0.0.1:17374',
ipProxyEnabled: false,
ipProxyService: '711proxy',
ipProxyMode: 'account',
@@ -135,6 +139,24 @@ function normalizeCloudflareDomains(value) { return Array.isArray(value) ? value
function normalizeCloudflareTempEmailDomains(value) { return Array.isArray(value) ? value : []; }
function normalizeCloudMailDomains(value) { return Array.isArray(value) ? value : []; }
function normalizeMailProvider(value = '') { return String(value || '163').trim().toLowerCase() || '163'; }
function normalizeCustomMailReceiveMode(value = '') { return String(value || '').trim().toLowerCase() === 'helper' ? 'helper' : 'manual'; }
function normalizeCustomMailHelperBaseUrl(value = '') {
const trimmed = String(value || '').trim();
const candidate = trimmed || 'http://127.0.0.1:17374';
try {
const parsed = new URL(candidate);
if (!['http:', 'https:'].includes(parsed.protocol)) {
return 'http://127.0.0.1:17374';
}
parsed.hash = '';
parsed.search = '';
parsed.pathname = parsed.pathname.replace(/[/]+$/, '');
const path = parsed.pathname === '/' ? '' : parsed.pathname;
return (parsed.origin + path) || 'http://127.0.0.1:17374';
} catch {
return 'http://127.0.0.1:17374';
}
}
function normalizeStepExecutionRangeByFlow(value) { return value && typeof value === 'object' && !Array.isArray(value) ? value : {}; }
function normalizeIpProxyProviderValue(value) { return String(value || '711proxy').trim() || '711proxy'; }
function normalizeIpProxyMode(value) { return String(value || 'account').trim() || 'account'; }
@@ -564,6 +586,49 @@ function getRemovedKeys() {
assert.equal(Object.prototype.hasOwnProperty.call(write, 'mailProvider'), false);
});
test('setPersistentSettings mirrors custom mail helper mode into canonical email settings', async () => {
const api = buildHarness(`
const persistedWrites = [];
const removedKeys = [];
const chrome = {
storage: {
local: {
async get() {
return {};
},
async remove(keys) {
removedKeys.push(...(Array.isArray(keys) ? keys : [keys]));
},
async set(payload) {
persistedWrites.push(JSON.parse(JSON.stringify(payload)));
},
},
},
};
function getPersistedWrites() {
return persistedWrites;
}
function getRemovedKeys() {
return removedKeys;
}
`);
const persisted = await api.setPersistentSettings({
mailProvider: 'custom',
customMailReceiveMode: 'helper',
customMailHelperBaseUrl: 'http://127.0.0.1:17374/',
});
const write = api.getPersistedWrites().at(-1);
assert.equal(persisted.mailProvider, 'custom');
assert.equal(persisted.customMailReceiveMode, 'helper');
assert.equal(persisted.customMailHelperBaseUrl, 'http://127.0.0.1:17374');
assert.equal(write.settingsState.services.email.provider, 'custom');
assert.equal(write.settingsState.services.email.customReceiveMode, 'helper');
assert.equal(write.settingsState.services.email.customHelperBaseUrl, 'http://127.0.0.1:17374');
assert.equal(Object.prototype.hasOwnProperty.call(write, 'customMailReceiveMode'), false);
});
test('setPersistentSettings mirrors flat schema updates without resetting other canonical settings', async () => {
const api = buildHarness(`
const persistedWrites = [];
@@ -0,0 +1,91 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const source = fs.readFileSync('flows/openai/background/steps/fetch-login-code.js', 'utf8');
const globalScope = {};
const api = new Function('self', `${source}; return self.MultiPageBackgroundStep8;`)(globalScope);
function createExecutorHarness(overrides = {}) {
let bypassCalls = 0;
let capturedMail = null;
let capturedState = null;
let capturedOptions = null;
const executor = api.createStep8Executor({
addLog: async () => {},
chrome: { tabs: { update: async () => {} } },
completeNodeFromBackground: async () => {},
confirmCustomVerificationStepBypass: async () => { bypassCalls += 1; },
ensureStep8VerificationPageReady: async () => ({
state: 'verification_page',
displayedEmail: 'target@example.com',
url: 'https://auth.openai.com/verify',
}),
getMailConfig: () => ({ provider: 'custom', label: '自定义邮箱' }),
getState: async () => ({ mailProvider: 'custom', email: 'target@example.com' }),
getTabId: async () => 1,
HOTMAIL_PROVIDER: 'hotmail-api',
isTabAlive: async () => false,
isVerificationMailPollingError: () => false,
LUCKMAIL_PROVIDER: 'luckmail-api',
CLOUDFLARE_TEMP_EMAIL_PROVIDER: 'cloudflare-temp-email',
CLOUD_MAIL_PROVIDER: 'cloudmail',
resolveVerificationStep: async (_step, state, mail, options) => {
capturedState = state;
capturedMail = mail;
capturedOptions = options;
},
rerunStep7ForStep8Recovery: async () => {},
resolveSignupEmailForFlow: async () => 'target@example.com',
reuseOrCreateTab: async () => {},
sendToContentScriptResilient: async () => ({}),
setState: async () => {},
shouldUseCustomRegistrationEmail: () => true,
shouldUseCustomMailHelper: () => false,
sleepWithStop: async () => {},
STANDARD_MAIL_VERIFICATION_RESEND_INTERVAL_MS: 25000,
STEP7_MAIL_POLLING_RECOVERY_MAX_ATTEMPTS: 1,
throwIfStopped: () => {},
...overrides,
});
return {
executor,
getBypassCalls: () => bypassCalls,
getCapturedMail: () => capturedMail,
getCapturedState: () => capturedState,
getCapturedOptions: () => capturedOptions,
};
}
test('step 8 keeps custom mail provider on manual confirmation by default', async () => {
const harness = createExecutorHarness();
await harness.executor.executeStep8({
mailProvider: 'custom',
customMailReceiveMode: 'manual',
email: 'target@example.com',
oauthUrl: 'https://auth.openai.com/oauth',
});
assert.equal(harness.getBypassCalls(), 1);
assert.equal(harness.getCapturedMail(), null);
});
test('step 8 routes custom mail provider through resolver only when helper mode is enabled', async () => {
const harness = createExecutorHarness({
shouldUseCustomMailHelper: () => true,
});
await harness.executor.executeStep8({
mailProvider: 'custom',
customMailReceiveMode: 'helper',
email: 'target@example.com',
oauthUrl: 'https://auth.openai.com/oauth',
});
assert.equal(harness.getBypassCalls(), 0);
assert.equal(harness.getCapturedMail().provider, 'custom');
assert.equal(harness.getCapturedState().step8VerificationTargetEmail, 'target@example.com');
assert.equal(harness.getCapturedOptions().targetEmail, 'target@example.com');
});
@@ -50,3 +50,108 @@ test('verification flow routes YYDS Mail provider to background poller', async (
assert.equal(pollCalls[0].step, 4);
assert.equal(pollCalls[0].payload.maxAttempts, 1);
});
test('verification flow routes custom mail provider to local helper poller', async () => {
const source = fs.readFileSync('background/verification-flow.js', 'utf8');
const globalScope = {};
const api = new Function('self', `${source}; return self.MultiPageBackgroundVerificationFlow;`)(globalScope);
const pollCalls = [];
const helpers = api.createVerificationFlowHelpers({
addLog: async () => {},
buildVerificationPollPayload: () => ({ maxAttempts: 1, intervalMs: 1, targetEmail: 'target@example.com' }),
CUSTOM_MAIL_PROVIDER: 'custom',
getState: async () => ({}),
getTabId: async () => 1,
isStopError: () => false,
pollCustomMailVerificationCode: async (step, state, payload) => {
pollCalls.push({ step, state, payload });
return { ok: true, code: '654321', emailTimestamp: 2, mailId: 'custom-msg-1' };
},
sendToContentScript: async () => ({}),
setState: async () => {},
sleepWithStop: async () => {},
throwIfStopped: () => {},
});
const result = await helpers.pollFreshVerificationCode(
4,
{ mailProvider: 'custom', customMailReceiveMode: 'helper', email: 'target@example.com' },
{ provider: 'custom', label: '自定义邮箱' },
{ disableTimeBudgetCap: true }
);
assert.equal(result.code, '654321');
assert.equal(pollCalls.length, 1);
assert.equal(pollCalls[0].step, 4);
assert.equal(pollCalls[0].payload.targetEmail, 'target@example.com');
});
test('background custom mail poller rejects manual mode before calling local helper', async () => {
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;
if (ch === ')') {
parenDepth -= 1;
if (parenDepth === 0) signatureEnded = true;
}
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);
}
const api = new Function(`
const CUSTOM_MAIL_RECEIVE_MODE_HELPER = 'helper';
const DEFAULT_CUSTOM_MAIL_RECEIVE_MODE = 'manual';
function isCustomMailProvider(stateOrProvider) {
const provider = typeof stateOrProvider === 'string' ? stateOrProvider : stateOrProvider?.mailProvider;
return provider === 'custom';
}
${extractFunction('normalizeCustomMailReceiveMode')}
${extractFunction('shouldUseCustomMailHelper')}
async function addLog() {}
async function sleepWithStop() {}
function throwIfStopped() {}
async function requestCustomMailLocalCode() {
throw new Error('should not request helper in manual mode');
}
${extractFunction('pollCustomMailVerificationCode')}
return { pollCustomMailVerificationCode };
`)();
await assert.rejects(
() => api.pollCustomMailVerificationCode(4, {
mailProvider: 'custom',
customMailReceiveMode: 'manual',
}, { maxAttempts: 1, intervalMs: 1 }),
/手动确认模式/
);
});
+17
View File
@@ -60,6 +60,10 @@ test('sidepanel html exposes custom email pool generator option and input row',
assert.match(html, /id="input-custom-email-pool-import"/);
assert.match(html, /id="custom-email-pool-list"/);
assert.match(html, /id="btn-custom-email-pool-bulk-used"/);
assert.match(html, /id="row-custom-mail-receive-mode"/);
assert.match(html, /id="select-custom-mail-receive-mode"/);
assert.match(html, /id="row-custom-mail-helper-base-url"/);
assert.match(html, /id="input-custom-mail-helper-base-url"/);
assert.match(html, /id="row-custom-mail-provider-pool"/);
assert.match(html, /id="input-custom-mail-provider-pool"/);
});
@@ -187,6 +191,19 @@ test('sidepanel queues custom email pool refresh when the pool row is visible',
);
});
test('sidepanel only shows custom mail helper url when helper receive mode is selected', () => {
const source = extractFunction('updateMailProviderUI');
assert.match(
source,
/rowCustomMailReceiveMode\.style\.display = useCustomEmail \? '' : 'none'/
);
assert.match(
source,
/rowCustomMailHelperBaseUrl\.style\.display = useCustomEmail && getSelectedCustomMailReceiveMode\(\) === CUSTOM_MAIL_RECEIVE_MODE_HELPER \? '' : 'none'/
);
});
test('sidepanel custom verification dialog exposes add-phone action for step 8', async () => {
const bundle = [
extractFunction('getCustomVerificationPromptCopy'),